9702eb860ac5c04bee0bcf25f90651d8a8580052
[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   RetOps[0] = Chain;  // Update chain.
2315
2316   // Add the flag if we have it.
2317   if (Flag.getNode())
2318     RetOps.push_back(Flag);
2319
2320   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2321   if (CallConv == CallingConv::X86_INTR)
2322     opcode = X86ISD::IRET;
2323   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2324 }
2325
2326 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2327   if (N->getNumValues() != 1)
2328     return false;
2329   if (!N->hasNUsesOfValue(1, 0))
2330     return false;
2331
2332   SDValue TCChain = Chain;
2333   SDNode *Copy = *N->use_begin();
2334   if (Copy->getOpcode() == ISD::CopyToReg) {
2335     // If the copy has a glue operand, we conservatively assume it isn't safe to
2336     // perform a tail call.
2337     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2338       return false;
2339     TCChain = Copy->getOperand(0);
2340   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2341     return false;
2342
2343   bool HasRet = false;
2344   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2345        UI != UE; ++UI) {
2346     if (UI->getOpcode() != X86ISD::RET_FLAG)
2347       return false;
2348     // If we are returning more than one value, we can definitely
2349     // not make a tail call see PR19530
2350     if (UI->getNumOperands() > 4)
2351       return false;
2352     if (UI->getNumOperands() == 4 &&
2353         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2354       return false;
2355     HasRet = true;
2356   }
2357
2358   if (!HasRet)
2359     return false;
2360
2361   Chain = TCChain;
2362   return true;
2363 }
2364
2365 EVT
2366 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2367                                             ISD::NodeType ExtendKind) const {
2368   MVT ReturnMVT;
2369   // TODO: Is this also valid on 32-bit?
2370   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2371     ReturnMVT = MVT::i8;
2372   else
2373     ReturnMVT = MVT::i32;
2374
2375   EVT MinVT = getRegisterType(Context, ReturnMVT);
2376   return VT.bitsLT(MinVT) ? MinVT : VT;
2377 }
2378
2379 /// Lower the result values of a call into the
2380 /// appropriate copies out of appropriate physical registers.
2381 ///
2382 SDValue
2383 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2384                                    CallingConv::ID CallConv, bool isVarArg,
2385                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2386                                    SDLoc dl, SelectionDAG &DAG,
2387                                    SmallVectorImpl<SDValue> &InVals) const {
2388
2389   // Assign locations to each value returned by this call.
2390   SmallVector<CCValAssign, 16> RVLocs;
2391   bool Is64Bit = Subtarget->is64Bit();
2392   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2393                  *DAG.getContext());
2394   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2395
2396   // Copy all of the result registers out of their specified physreg.
2397   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2398     CCValAssign &VA = RVLocs[i];
2399     EVT CopyVT = VA.getLocVT();
2400
2401     // If this is x86-64, and we disabled SSE, we can't return FP values
2402     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2403         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2404       report_fatal_error("SSE register return with SSE disabled");
2405     }
2406
2407     // If we prefer to use the value in xmm registers, copy it out as f80 and
2408     // use a truncate to move it from fp stack reg to xmm reg.
2409     bool RoundAfterCopy = false;
2410     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2411         isScalarFPTypeInSSEReg(VA.getValVT())) {
2412       CopyVT = MVT::f80;
2413       RoundAfterCopy = (CopyVT != VA.getLocVT());
2414     }
2415
2416     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2417                                CopyVT, InFlag).getValue(1);
2418     SDValue Val = Chain.getValue(0);
2419
2420     if (RoundAfterCopy)
2421       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2422                         // This truncation won't change the value.
2423                         DAG.getIntPtrConstant(1, dl));
2424
2425     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2426       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2427
2428     InFlag = Chain.getValue(2);
2429     InVals.push_back(Val);
2430   }
2431
2432   return Chain;
2433 }
2434
2435 //===----------------------------------------------------------------------===//
2436 //                C & StdCall & Fast Calling Convention implementation
2437 //===----------------------------------------------------------------------===//
2438 //  StdCall calling convention seems to be standard for many Windows' API
2439 //  routines and around. It differs from C calling convention just a little:
2440 //  callee should clean up the stack, not caller. Symbols should be also
2441 //  decorated in some fancy way :) It doesn't support any vector arguments.
2442 //  For info on fast calling convention see Fast Calling Convention (tail call)
2443 //  implementation LowerX86_32FastCCCallTo.
2444
2445 /// CallIsStructReturn - Determines whether a call uses struct return
2446 /// semantics.
2447 enum StructReturnType {
2448   NotStructReturn,
2449   RegStructReturn,
2450   StackStructReturn
2451 };
2452 static StructReturnType
2453 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2454   if (Outs.empty())
2455     return NotStructReturn;
2456
2457   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2458   if (!Flags.isSRet())
2459     return NotStructReturn;
2460   if (Flags.isInReg() || IsMCU)
2461     return RegStructReturn;
2462   return StackStructReturn;
2463 }
2464
2465 /// Determines whether a function uses struct return semantics.
2466 static StructReturnType
2467 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2468   if (Ins.empty())
2469     return NotStructReturn;
2470
2471   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2472   if (!Flags.isSRet())
2473     return NotStructReturn;
2474   if (Flags.isInReg() || IsMCU)
2475     return RegStructReturn;
2476   return StackStructReturn;
2477 }
2478
2479 /// Make a copy of an aggregate at address specified by "Src" to address
2480 /// "Dst" with size and alignment information specified by the specific
2481 /// parameter attribute. The copy will be passed as a byval function parameter.
2482 static SDValue
2483 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2484                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2485                           SDLoc dl) {
2486   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2487
2488   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2489                        /*isVolatile*/false, /*AlwaysInline=*/true,
2490                        /*isTailCall*/false,
2491                        MachinePointerInfo(), MachinePointerInfo());
2492 }
2493
2494 /// Return true if the calling convention is one that we can guarantee TCO for.
2495 static bool canGuaranteeTCO(CallingConv::ID CC) {
2496   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2497           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2498 }
2499
2500 /// Return true if we might ever do TCO for calls with this calling convention.
2501 static bool mayTailCallThisCC(CallingConv::ID CC) {
2502   switch (CC) {
2503   // C calling conventions:
2504   case CallingConv::C:
2505   case CallingConv::X86_64_Win64:
2506   case CallingConv::X86_64_SysV:
2507   // Callee pop conventions:
2508   case CallingConv::X86_ThisCall:
2509   case CallingConv::X86_StdCall:
2510   case CallingConv::X86_VectorCall:
2511   case CallingConv::X86_FastCall:
2512     return true;
2513   default:
2514     return canGuaranteeTCO(CC);
2515   }
2516 }
2517
2518 /// Return true if the function is being made into a tailcall target by
2519 /// changing its ABI.
2520 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2521   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2522 }
2523
2524 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2525   auto Attr =
2526       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2527   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2528     return false;
2529
2530   CallSite CS(CI);
2531   CallingConv::ID CalleeCC = CS.getCallingConv();
2532   if (!mayTailCallThisCC(CalleeCC))
2533     return false;
2534
2535   return true;
2536 }
2537
2538 SDValue
2539 X86TargetLowering::LowerMemArgument(SDValue Chain,
2540                                     CallingConv::ID CallConv,
2541                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2542                                     SDLoc dl, SelectionDAG &DAG,
2543                                     const CCValAssign &VA,
2544                                     MachineFrameInfo *MFI,
2545                                     unsigned i) const {
2546   // Create the nodes corresponding to a load from this parameter slot.
2547   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2548   bool AlwaysUseMutable = shouldGuaranteeTCO(
2549       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2550   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2551   EVT ValVT;
2552
2553   // If value is passed by pointer we have address passed instead of the value
2554   // itself.
2555   bool ExtendedInMem = VA.isExtInLoc() &&
2556     VA.getValVT().getScalarType() == MVT::i1;
2557
2558   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2559     ValVT = VA.getLocVT();
2560   else
2561     ValVT = VA.getValVT();
2562
2563   // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2564   // taken by a return address.
2565   int Offset = 0;
2566   if (CallConv == CallingConv::X86_INTR) {
2567     const X86Subtarget& Subtarget =
2568         static_cast<const X86Subtarget&>(DAG.getSubtarget());
2569     // X86 interrupts may take one or two arguments.
2570     // On the stack there will be no return address as in regular call.
2571     // Offset of last argument need to be set to -4/-8 bytes.
2572     // Where offset of the first argument out of two, should be set to 0 bytes.
2573     Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2574   }
2575
2576   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2577   // changed with more analysis.
2578   // In case of tail call optimization mark all arguments mutable. Since they
2579   // could be overwritten by lowering of arguments in case of a tail call.
2580   if (Flags.isByVal()) {
2581     unsigned Bytes = Flags.getByValSize();
2582     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2583     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2584     // Adjust SP offset of interrupt parameter.
2585     if (CallConv == CallingConv::X86_INTR) {
2586       MFI->setObjectOffset(FI, Offset);
2587     }
2588     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2589   } else {
2590     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2591                                     VA.getLocMemOffset(), isImmutable);
2592     // Adjust SP offset of interrupt parameter.
2593     if (CallConv == CallingConv::X86_INTR) {
2594       MFI->setObjectOffset(FI, Offset);
2595     }
2596
2597     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2598     SDValue Val = DAG.getLoad(
2599         ValVT, dl, Chain, FIN,
2600         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2601         false, false, 0);
2602     return ExtendedInMem ?
2603       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2604   }
2605 }
2606
2607 // FIXME: Get this from tablegen.
2608 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2609                                                 const X86Subtarget *Subtarget) {
2610   assert(Subtarget->is64Bit());
2611
2612   if (Subtarget->isCallingConvWin64(CallConv)) {
2613     static const MCPhysReg GPR64ArgRegsWin64[] = {
2614       X86::RCX, X86::RDX, X86::R8,  X86::R9
2615     };
2616     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2617   }
2618
2619   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2620     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2621   };
2622   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2623 }
2624
2625 // FIXME: Get this from tablegen.
2626 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2627                                                 CallingConv::ID CallConv,
2628                                                 const X86Subtarget *Subtarget) {
2629   assert(Subtarget->is64Bit());
2630   if (Subtarget->isCallingConvWin64(CallConv)) {
2631     // The XMM registers which might contain var arg parameters are shadowed
2632     // in their paired GPR.  So we only need to save the GPR to their home
2633     // slots.
2634     // TODO: __vectorcall will change this.
2635     return None;
2636   }
2637
2638   const Function *Fn = MF.getFunction();
2639   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2640   bool isSoftFloat = Subtarget->useSoftFloat();
2641   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2642          "SSE register cannot be used when SSE is disabled!");
2643   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2644     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2645     // registers.
2646     return None;
2647
2648   static const MCPhysReg XMMArgRegs64Bit[] = {
2649     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2650     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2651   };
2652   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2653 }
2654
2655 SDValue X86TargetLowering::LowerFormalArguments(
2656     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2657     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2658     SmallVectorImpl<SDValue> &InVals) const {
2659   MachineFunction &MF = DAG.getMachineFunction();
2660   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2661   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2662
2663   const Function* Fn = MF.getFunction();
2664   if (Fn->hasExternalLinkage() &&
2665       Subtarget->isTargetCygMing() &&
2666       Fn->getName() == "main")
2667     FuncInfo->setForceFramePointer(true);
2668
2669   MachineFrameInfo *MFI = MF.getFrameInfo();
2670   bool Is64Bit = Subtarget->is64Bit();
2671   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2672
2673   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2674          "Var args not supported with calling convention fastcc, ghc or hipe");
2675
2676   if (CallConv == CallingConv::X86_INTR) {
2677     bool isLegal = Ins.size() == 1 ||
2678                    (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2679                                         (!Is64Bit && Ins[1].VT == MVT::i32)));
2680     if (!isLegal)
2681       report_fatal_error("X86 interrupts may take one or two arguments");
2682   }
2683
2684   // Assign locations to all of the incoming arguments.
2685   SmallVector<CCValAssign, 16> ArgLocs;
2686   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2687
2688   // Allocate shadow area for Win64
2689   if (IsWin64)
2690     CCInfo.AllocateStack(32, 8);
2691
2692   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2693
2694   unsigned LastVal = ~0U;
2695   SDValue ArgValue;
2696   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2697     CCValAssign &VA = ArgLocs[i];
2698     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2699     // places.
2700     assert(VA.getValNo() != LastVal &&
2701            "Don't support value assigned to multiple locs yet");
2702     (void)LastVal;
2703     LastVal = VA.getValNo();
2704
2705     if (VA.isRegLoc()) {
2706       EVT RegVT = VA.getLocVT();
2707       const TargetRegisterClass *RC;
2708       if (RegVT == MVT::i32)
2709         RC = &X86::GR32RegClass;
2710       else if (Is64Bit && RegVT == MVT::i64)
2711         RC = &X86::GR64RegClass;
2712       else if (RegVT == MVT::f32)
2713         RC = &X86::FR32RegClass;
2714       else if (RegVT == MVT::f64)
2715         RC = &X86::FR64RegClass;
2716       else if (RegVT == MVT::f128)
2717         RC = &X86::FR128RegClass;
2718       else if (RegVT.is512BitVector())
2719         RC = &X86::VR512RegClass;
2720       else if (RegVT.is256BitVector())
2721         RC = &X86::VR256RegClass;
2722       else if (RegVT.is128BitVector())
2723         RC = &X86::VR128RegClass;
2724       else if (RegVT == MVT::x86mmx)
2725         RC = &X86::VR64RegClass;
2726       else if (RegVT == MVT::i1)
2727         RC = &X86::VK1RegClass;
2728       else if (RegVT == MVT::v8i1)
2729         RC = &X86::VK8RegClass;
2730       else if (RegVT == MVT::v16i1)
2731         RC = &X86::VK16RegClass;
2732       else if (RegVT == MVT::v32i1)
2733         RC = &X86::VK32RegClass;
2734       else if (RegVT == MVT::v64i1)
2735         RC = &X86::VK64RegClass;
2736       else
2737         llvm_unreachable("Unknown argument type!");
2738
2739       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2740       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2741
2742       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2743       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2744       // right size.
2745       if (VA.getLocInfo() == CCValAssign::SExt)
2746         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2747                                DAG.getValueType(VA.getValVT()));
2748       else if (VA.getLocInfo() == CCValAssign::ZExt)
2749         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2750                                DAG.getValueType(VA.getValVT()));
2751       else if (VA.getLocInfo() == CCValAssign::BCvt)
2752         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2753
2754       if (VA.isExtInLoc()) {
2755         // Handle MMX values passed in XMM regs.
2756         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2757           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2758         else
2759           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2760       }
2761     } else {
2762       assert(VA.isMemLoc());
2763       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2764     }
2765
2766     // If value is passed via pointer - do a load.
2767     if (VA.getLocInfo() == CCValAssign::Indirect)
2768       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2769                              MachinePointerInfo(), false, false, false, 0);
2770
2771     InVals.push_back(ArgValue);
2772   }
2773
2774   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2775     // All x86 ABIs require that for returning structs by value we copy the
2776     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2777     // the argument into a virtual register so that we can access it from the
2778     // return points.
2779     if (Ins[i].Flags.isSRet()) {
2780       unsigned Reg = FuncInfo->getSRetReturnReg();
2781       if (!Reg) {
2782         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2783         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2784         FuncInfo->setSRetReturnReg(Reg);
2785       }
2786       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2787       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2788       break;
2789     }
2790   }
2791
2792   unsigned StackSize = CCInfo.getNextStackOffset();
2793   // Align stack specially for tail calls.
2794   if (shouldGuaranteeTCO(CallConv,
2795                          MF.getTarget().Options.GuaranteedTailCallOpt))
2796     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2797
2798   // If the function takes variable number of arguments, make a frame index for
2799   // the start of the first vararg value... for expansion of llvm.va_start. We
2800   // can skip this if there are no va_start calls.
2801   if (MFI->hasVAStart() &&
2802       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2803                    CallConv != CallingConv::X86_ThisCall))) {
2804     FuncInfo->setVarArgsFrameIndex(
2805         MFI->CreateFixedObject(1, StackSize, true));
2806   }
2807
2808   // Figure out if XMM registers are in use.
2809   assert(!(Subtarget->useSoftFloat() &&
2810            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2811          "SSE register cannot be used when SSE is disabled!");
2812
2813   // 64-bit calling conventions support varargs and register parameters, so we
2814   // have to do extra work to spill them in the prologue.
2815   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2816     // Find the first unallocated argument registers.
2817     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2818     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2819     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2820     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2821     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2822            "SSE register cannot be used when SSE is disabled!");
2823
2824     // Gather all the live in physical registers.
2825     SmallVector<SDValue, 6> LiveGPRs;
2826     SmallVector<SDValue, 8> LiveXMMRegs;
2827     SDValue ALVal;
2828     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2829       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2830       LiveGPRs.push_back(
2831           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2832     }
2833     if (!ArgXMMs.empty()) {
2834       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2835       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2836       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2837         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2838         LiveXMMRegs.push_back(
2839             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2840       }
2841     }
2842
2843     if (IsWin64) {
2844       // Get to the caller-allocated home save location.  Add 8 to account
2845       // for the return address.
2846       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2847       FuncInfo->setRegSaveFrameIndex(
2848           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2849       // Fixup to set vararg frame on shadow area (4 x i64).
2850       if (NumIntRegs < 4)
2851         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2852     } else {
2853       // For X86-64, if there are vararg parameters that are passed via
2854       // registers, then we must store them to their spots on the stack so
2855       // they may be loaded by deferencing the result of va_next.
2856       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2857       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2858       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2859           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2860     }
2861
2862     // Store the integer parameter registers.
2863     SmallVector<SDValue, 8> MemOps;
2864     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2865                                       getPointerTy(DAG.getDataLayout()));
2866     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2867     for (SDValue Val : LiveGPRs) {
2868       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2869                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2870       SDValue Store =
2871           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2872                        MachinePointerInfo::getFixedStack(
2873                            DAG.getMachineFunction(),
2874                            FuncInfo->getRegSaveFrameIndex(), Offset),
2875                        false, false, 0);
2876       MemOps.push_back(Store);
2877       Offset += 8;
2878     }
2879
2880     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2881       // Now store the XMM (fp + vector) parameter registers.
2882       SmallVector<SDValue, 12> SaveXMMOps;
2883       SaveXMMOps.push_back(Chain);
2884       SaveXMMOps.push_back(ALVal);
2885       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2886                              FuncInfo->getRegSaveFrameIndex(), dl));
2887       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2888                              FuncInfo->getVarArgsFPOffset(), dl));
2889       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2890                         LiveXMMRegs.end());
2891       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2892                                    MVT::Other, SaveXMMOps));
2893     }
2894
2895     if (!MemOps.empty())
2896       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2897   }
2898
2899   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2900     // Find the largest legal vector type.
2901     MVT VecVT = MVT::Other;
2902     // FIXME: Only some x86_32 calling conventions support AVX512.
2903     if (Subtarget->hasAVX512() &&
2904         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2905                      CallConv == CallingConv::Intel_OCL_BI)))
2906       VecVT = MVT::v16f32;
2907     else if (Subtarget->hasAVX())
2908       VecVT = MVT::v8f32;
2909     else if (Subtarget->hasSSE2())
2910       VecVT = MVT::v4f32;
2911
2912     // We forward some GPRs and some vector types.
2913     SmallVector<MVT, 2> RegParmTypes;
2914     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2915     RegParmTypes.push_back(IntVT);
2916     if (VecVT != MVT::Other)
2917       RegParmTypes.push_back(VecVT);
2918
2919     // Compute the set of forwarded registers. The rest are scratch.
2920     SmallVectorImpl<ForwardedRegister> &Forwards =
2921         FuncInfo->getForwardedMustTailRegParms();
2922     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2923
2924     // Conservatively forward AL on x86_64, since it might be used for varargs.
2925     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2926       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2927       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2928     }
2929
2930     // Copy all forwards from physical to virtual registers.
2931     for (ForwardedRegister &F : Forwards) {
2932       // FIXME: Can we use a less constrained schedule?
2933       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2934       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2935       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2936     }
2937   }
2938
2939   // Some CCs need callee pop.
2940   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2941                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2942     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2943   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2944     // X86 interrupts must pop the error code if present
2945     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2946   } else {
2947     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2948     // If this is an sret function, the return should pop the hidden pointer.
2949     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2950         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2951         argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2952       FuncInfo->setBytesToPopOnReturn(4);
2953   }
2954
2955   if (!Is64Bit) {
2956     // RegSaveFrameIndex is X86-64 only.
2957     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2958     if (CallConv == CallingConv::X86_FastCall ||
2959         CallConv == CallingConv::X86_ThisCall)
2960       // fastcc functions can't have varargs.
2961       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2962   }
2963
2964   FuncInfo->setArgumentStackSize(StackSize);
2965
2966   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2967     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2968     if (Personality == EHPersonality::CoreCLR) {
2969       assert(Is64Bit);
2970       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2971       // that we'd prefer this slot be allocated towards the bottom of the frame
2972       // (i.e. near the stack pointer after allocating the frame).  Every
2973       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2974       // offset from the bottom of this and each funclet's frame must be the
2975       // same, so the size of funclets' (mostly empty) frames is dictated by
2976       // how far this slot is from the bottom (since they allocate just enough
2977       // space to accomodate holding this slot at the correct offset).
2978       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2979       EHInfo->PSPSymFrameIdx = PSPSymFI;
2980     }
2981   }
2982
2983   return Chain;
2984 }
2985
2986 SDValue
2987 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2988                                     SDValue StackPtr, SDValue Arg,
2989                                     SDLoc dl, SelectionDAG &DAG,
2990                                     const CCValAssign &VA,
2991                                     ISD::ArgFlagsTy Flags) const {
2992   unsigned LocMemOffset = VA.getLocMemOffset();
2993   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2994   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2995                        StackPtr, PtrOff);
2996   if (Flags.isByVal())
2997     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2998
2999   return DAG.getStore(
3000       Chain, dl, Arg, PtrOff,
3001       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3002       false, false, 0);
3003 }
3004
3005 /// Emit a load of return address if tail call
3006 /// optimization is performed and it is required.
3007 SDValue
3008 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3009                                            SDValue &OutRetAddr, SDValue Chain,
3010                                            bool IsTailCall, bool Is64Bit,
3011                                            int FPDiff, SDLoc dl) const {
3012   // Adjust the Return address stack slot.
3013   EVT VT = getPointerTy(DAG.getDataLayout());
3014   OutRetAddr = getReturnAddressFrameIndex(DAG);
3015
3016   // Load the "old" Return address.
3017   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3018                            false, false, false, 0);
3019   return SDValue(OutRetAddr.getNode(), 1);
3020 }
3021
3022 /// Emit a store of the return address if tail call
3023 /// optimization is performed and it is required (FPDiff!=0).
3024 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3025                                         SDValue Chain, SDValue RetAddrFrIdx,
3026                                         EVT PtrVT, unsigned SlotSize,
3027                                         int FPDiff, SDLoc dl) {
3028   // Store the return address to the appropriate stack slot.
3029   if (!FPDiff) return Chain;
3030   // Calculate the new stack slot for the return address.
3031   int NewReturnAddrFI =
3032     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3033                                          false);
3034   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3035   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3036                        MachinePointerInfo::getFixedStack(
3037                            DAG.getMachineFunction(), NewReturnAddrFI),
3038                        false, false, 0);
3039   return Chain;
3040 }
3041
3042 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3043 /// operation of specified width.
3044 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3045                        SDValue V2) {
3046   unsigned NumElems = VT.getVectorNumElements();
3047   SmallVector<int, 8> Mask;
3048   Mask.push_back(NumElems);
3049   for (unsigned i = 1; i != NumElems; ++i)
3050     Mask.push_back(i);
3051   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3052 }
3053
3054 SDValue
3055 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3056                              SmallVectorImpl<SDValue> &InVals) const {
3057   SelectionDAG &DAG                     = CLI.DAG;
3058   SDLoc &dl                             = CLI.DL;
3059   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3060   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3061   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3062   SDValue Chain                         = CLI.Chain;
3063   SDValue Callee                        = CLI.Callee;
3064   CallingConv::ID CallConv              = CLI.CallConv;
3065   bool &isTailCall                      = CLI.IsTailCall;
3066   bool isVarArg                         = CLI.IsVarArg;
3067
3068   MachineFunction &MF = DAG.getMachineFunction();
3069   bool Is64Bit        = Subtarget->is64Bit();
3070   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3071   StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3072   bool IsSibcall      = false;
3073   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3074   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3075
3076   if (CallConv == CallingConv::X86_INTR)
3077     report_fatal_error("X86 interrupts may not be called directly");
3078
3079   if (Attr.getValueAsString() == "true")
3080     isTailCall = false;
3081
3082   if (Subtarget->isPICStyleGOT() &&
3083       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3084     // If we are using a GOT, disable tail calls to external symbols with
3085     // default visibility. Tail calling such a symbol requires using a GOT
3086     // relocation, which forces early binding of the symbol. This breaks code
3087     // that require lazy function symbol resolution. Using musttail or
3088     // GuaranteedTailCallOpt will override this.
3089     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3090     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3091                G->getGlobal()->hasDefaultVisibility()))
3092       isTailCall = false;
3093   }
3094
3095   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3096   if (IsMustTail) {
3097     // Force this to be a tail call.  The verifier rules are enough to ensure
3098     // that we can lower this successfully without moving the return address
3099     // around.
3100     isTailCall = true;
3101   } else if (isTailCall) {
3102     // Check if it's really possible to do a tail call.
3103     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3104                     isVarArg, SR != NotStructReturn,
3105                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3106                     Outs, OutVals, Ins, DAG);
3107
3108     // Sibcalls are automatically detected tailcalls which do not require
3109     // ABI changes.
3110     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3111       IsSibcall = true;
3112
3113     if (isTailCall)
3114       ++NumTailCalls;
3115   }
3116
3117   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3118          "Var args not supported with calling convention fastcc, ghc or hipe");
3119
3120   // Analyze operands of the call, assigning locations to each operand.
3121   SmallVector<CCValAssign, 16> ArgLocs;
3122   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3123
3124   // Allocate shadow area for Win64
3125   if (IsWin64)
3126     CCInfo.AllocateStack(32, 8);
3127
3128   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3129
3130   // Get a count of how many bytes are to be pushed on the stack.
3131   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3132   if (IsSibcall)
3133     // This is a sibcall. The memory operands are available in caller's
3134     // own caller's stack.
3135     NumBytes = 0;
3136   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3137            canGuaranteeTCO(CallConv))
3138     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3139
3140   int FPDiff = 0;
3141   if (isTailCall && !IsSibcall && !IsMustTail) {
3142     // Lower arguments at fp - stackoffset + fpdiff.
3143     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3144
3145     FPDiff = NumBytesCallerPushed - NumBytes;
3146
3147     // Set the delta of movement of the returnaddr stackslot.
3148     // But only set if delta is greater than previous delta.
3149     if (FPDiff < X86Info->getTCReturnAddrDelta())
3150       X86Info->setTCReturnAddrDelta(FPDiff);
3151   }
3152
3153   unsigned NumBytesToPush = NumBytes;
3154   unsigned NumBytesToPop = NumBytes;
3155
3156   // If we have an inalloca argument, all stack space has already been allocated
3157   // for us and be right at the top of the stack.  We don't support multiple
3158   // arguments passed in memory when using inalloca.
3159   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3160     NumBytesToPush = 0;
3161     if (!ArgLocs.back().isMemLoc())
3162       report_fatal_error("cannot use inalloca attribute on a register "
3163                          "parameter");
3164     if (ArgLocs.back().getLocMemOffset() != 0)
3165       report_fatal_error("any parameter with the inalloca attribute must be "
3166                          "the only memory argument");
3167   }
3168
3169   if (!IsSibcall)
3170     Chain = DAG.getCALLSEQ_START(
3171         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3172
3173   SDValue RetAddrFrIdx;
3174   // Load return address for tail calls.
3175   if (isTailCall && FPDiff)
3176     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3177                                     Is64Bit, FPDiff, dl);
3178
3179   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3180   SmallVector<SDValue, 8> MemOpChains;
3181   SDValue StackPtr;
3182
3183   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3184   // of tail call optimization arguments are handle later.
3185   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3186   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3187     // Skip inalloca arguments, they have already been written.
3188     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3189     if (Flags.isInAlloca())
3190       continue;
3191
3192     CCValAssign &VA = ArgLocs[i];
3193     EVT RegVT = VA.getLocVT();
3194     SDValue Arg = OutVals[i];
3195     bool isByVal = Flags.isByVal();
3196
3197     // Promote the value if needed.
3198     switch (VA.getLocInfo()) {
3199     default: llvm_unreachable("Unknown loc info!");
3200     case CCValAssign::Full: break;
3201     case CCValAssign::SExt:
3202       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3203       break;
3204     case CCValAssign::ZExt:
3205       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3206       break;
3207     case CCValAssign::AExt:
3208       if (Arg.getValueType().isVector() &&
3209           Arg.getValueType().getVectorElementType() == MVT::i1)
3210         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3211       else if (RegVT.is128BitVector()) {
3212         // Special case: passing MMX values in XMM registers.
3213         Arg = DAG.getBitcast(MVT::i64, Arg);
3214         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3215         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3216       } else
3217         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3218       break;
3219     case CCValAssign::BCvt:
3220       Arg = DAG.getBitcast(RegVT, Arg);
3221       break;
3222     case CCValAssign::Indirect: {
3223       // Store the argument.
3224       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3225       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3226       Chain = DAG.getStore(
3227           Chain, dl, Arg, SpillSlot,
3228           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3229           false, false, 0);
3230       Arg = SpillSlot;
3231       break;
3232     }
3233     }
3234
3235     if (VA.isRegLoc()) {
3236       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3237       if (isVarArg && IsWin64) {
3238         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3239         // shadow reg if callee is a varargs function.
3240         unsigned ShadowReg = 0;
3241         switch (VA.getLocReg()) {
3242         case X86::XMM0: ShadowReg = X86::RCX; break;
3243         case X86::XMM1: ShadowReg = X86::RDX; break;
3244         case X86::XMM2: ShadowReg = X86::R8; break;
3245         case X86::XMM3: ShadowReg = X86::R9; break;
3246         }
3247         if (ShadowReg)
3248           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3249       }
3250     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3251       assert(VA.isMemLoc());
3252       if (!StackPtr.getNode())
3253         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3254                                       getPointerTy(DAG.getDataLayout()));
3255       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3256                                              dl, DAG, VA, Flags));
3257     }
3258   }
3259
3260   if (!MemOpChains.empty())
3261     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3262
3263   if (Subtarget->isPICStyleGOT()) {
3264     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3265     // GOT pointer.
3266     if (!isTailCall) {
3267       RegsToPass.push_back(std::make_pair(
3268           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3269                                           getPointerTy(DAG.getDataLayout()))));
3270     } else {
3271       // If we are tail calling and generating PIC/GOT style code load the
3272       // address of the callee into ECX. The value in ecx is used as target of
3273       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3274       // for tail calls on PIC/GOT architectures. Normally we would just put the
3275       // address of GOT into ebx and then call target@PLT. But for tail calls
3276       // ebx would be restored (since ebx is callee saved) before jumping to the
3277       // target@PLT.
3278
3279       // Note: The actual moving to ECX is done further down.
3280       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3281       if (G && !G->getGlobal()->hasLocalLinkage() &&
3282           G->getGlobal()->hasDefaultVisibility())
3283         Callee = LowerGlobalAddress(Callee, DAG);
3284       else if (isa<ExternalSymbolSDNode>(Callee))
3285         Callee = LowerExternalSymbol(Callee, DAG);
3286     }
3287   }
3288
3289   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3290     // From AMD64 ABI document:
3291     // For calls that may call functions that use varargs or stdargs
3292     // (prototype-less calls or calls to functions containing ellipsis (...) in
3293     // the declaration) %al is used as hidden argument to specify the number
3294     // of SSE registers used. The contents of %al do not need to match exactly
3295     // the number of registers, but must be an ubound on the number of SSE
3296     // registers used and is in the range 0 - 8 inclusive.
3297
3298     // Count the number of XMM registers allocated.
3299     static const MCPhysReg XMMArgRegs[] = {
3300       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3301       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3302     };
3303     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3304     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3305            && "SSE registers cannot be used when SSE is disabled");
3306
3307     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3308                                         DAG.getConstant(NumXMMRegs, dl,
3309                                                         MVT::i8)));
3310   }
3311
3312   if (isVarArg && IsMustTail) {
3313     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3314     for (const auto &F : Forwards) {
3315       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3316       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3317     }
3318   }
3319
3320   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3321   // don't need this because the eligibility check rejects calls that require
3322   // shuffling arguments passed in memory.
3323   if (!IsSibcall && isTailCall) {
3324     // Force all the incoming stack arguments to be loaded from the stack
3325     // before any new outgoing arguments are stored to the stack, because the
3326     // outgoing stack slots may alias the incoming argument stack slots, and
3327     // the alias isn't otherwise explicit. This is slightly more conservative
3328     // than necessary, because it means that each store effectively depends
3329     // on every argument instead of just those arguments it would clobber.
3330     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3331
3332     SmallVector<SDValue, 8> MemOpChains2;
3333     SDValue FIN;
3334     int FI = 0;
3335     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3336       CCValAssign &VA = ArgLocs[i];
3337       if (VA.isRegLoc())
3338         continue;
3339       assert(VA.isMemLoc());
3340       SDValue Arg = OutVals[i];
3341       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3342       // Skip inalloca arguments.  They don't require any work.
3343       if (Flags.isInAlloca())
3344         continue;
3345       // Create frame index.
3346       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3347       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3348       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3349       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3350
3351       if (Flags.isByVal()) {
3352         // Copy relative to framepointer.
3353         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3354         if (!StackPtr.getNode())
3355           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3356                                         getPointerTy(DAG.getDataLayout()));
3357         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3358                              StackPtr, Source);
3359
3360         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3361                                                          ArgChain,
3362                                                          Flags, DAG, dl));
3363       } else {
3364         // Store relative to framepointer.
3365         MemOpChains2.push_back(DAG.getStore(
3366             ArgChain, dl, Arg, FIN,
3367             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3368             false, false, 0));
3369       }
3370     }
3371
3372     if (!MemOpChains2.empty())
3373       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3374
3375     // Store the return address to the appropriate stack slot.
3376     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3377                                      getPointerTy(DAG.getDataLayout()),
3378                                      RegInfo->getSlotSize(), FPDiff, dl);
3379   }
3380
3381   // Build a sequence of copy-to-reg nodes chained together with token chain
3382   // and flag operands which copy the outgoing args into registers.
3383   SDValue InFlag;
3384   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3385     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3386                              RegsToPass[i].second, InFlag);
3387     InFlag = Chain.getValue(1);
3388   }
3389
3390   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3391     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3392     // In the 64-bit large code model, we have to make all calls
3393     // through a register, since the call instruction's 32-bit
3394     // pc-relative offset may not be large enough to hold the whole
3395     // address.
3396   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3397     // If the callee is a GlobalAddress node (quite common, every direct call
3398     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3399     // it.
3400     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3401
3402     // We should use extra load for direct calls to dllimported functions in
3403     // non-JIT mode.
3404     const GlobalValue *GV = G->getGlobal();
3405     if (!GV->hasDLLImportStorageClass()) {
3406       unsigned char OpFlags = 0;
3407       bool ExtraLoad = false;
3408       unsigned WrapperKind = ISD::DELETED_NODE;
3409
3410       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3411       // external symbols most go through the PLT in PIC mode.  If the symbol
3412       // has hidden or protected visibility, or if it is static or local, then
3413       // we don't need to use the PLT - we can directly call it.
3414       if (Subtarget->isTargetELF() &&
3415           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3416           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3417         OpFlags = X86II::MO_PLT;
3418       } else if (Subtarget->isPICStyleStubAny() &&
3419                  !GV->isStrongDefinitionForLinker() &&
3420                  (!Subtarget->getTargetTriple().isMacOSX() ||
3421                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3422         // PC-relative references to external symbols should go through $stub,
3423         // unless we're building with the leopard linker or later, which
3424         // automatically synthesizes these stubs.
3425         OpFlags = X86II::MO_DARWIN_STUB;
3426       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3427                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3428         // If the function is marked as non-lazy, generate an indirect call
3429         // which loads from the GOT directly. This avoids runtime overhead
3430         // at the cost of eager binding (and one extra byte of encoding).
3431         OpFlags = X86II::MO_GOTPCREL;
3432         WrapperKind = X86ISD::WrapperRIP;
3433         ExtraLoad = true;
3434       }
3435
3436       Callee = DAG.getTargetGlobalAddress(
3437           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3438
3439       // Add a wrapper if needed.
3440       if (WrapperKind != ISD::DELETED_NODE)
3441         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3442                              getPointerTy(DAG.getDataLayout()), Callee);
3443       // Add extra indirection if needed.
3444       if (ExtraLoad)
3445         Callee = DAG.getLoad(
3446             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3447             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3448             false, 0);
3449     }
3450   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3451     unsigned char OpFlags = 0;
3452
3453     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3454     // external symbols should go through the PLT.
3455     if (Subtarget->isTargetELF() &&
3456         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3457       OpFlags = X86II::MO_PLT;
3458     } else if (Subtarget->isPICStyleStubAny() &&
3459                (!Subtarget->getTargetTriple().isMacOSX() ||
3460                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3461       // PC-relative references to external symbols should go through $stub,
3462       // unless we're building with the leopard linker or later, which
3463       // automatically synthesizes these stubs.
3464       OpFlags = X86II::MO_DARWIN_STUB;
3465     }
3466
3467     Callee = DAG.getTargetExternalSymbol(
3468         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3469   } else if (Subtarget->isTarget64BitILP32() &&
3470              Callee->getValueType(0) == MVT::i32) {
3471     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3472     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3473   }
3474
3475   // Returns a chain & a flag for retval copy to use.
3476   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3477   SmallVector<SDValue, 8> Ops;
3478
3479   if (!IsSibcall && isTailCall) {
3480     Chain = DAG.getCALLSEQ_END(Chain,
3481                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3482                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3483     InFlag = Chain.getValue(1);
3484   }
3485
3486   Ops.push_back(Chain);
3487   Ops.push_back(Callee);
3488
3489   if (isTailCall)
3490     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3491
3492   // Add argument registers to the end of the list so that they are known live
3493   // into the call.
3494   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3495     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3496                                   RegsToPass[i].second.getValueType()));
3497
3498   // Add a register mask operand representing the call-preserved registers.
3499   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3500   assert(Mask && "Missing call preserved mask for calling convention");
3501
3502   // If this is an invoke in a 32-bit function using a funclet-based
3503   // personality, assume the function clobbers all registers. If an exception
3504   // is thrown, the runtime will not restore CSRs.
3505   // FIXME: Model this more precisely so that we can register allocate across
3506   // the normal edge and spill and fill across the exceptional edge.
3507   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3508     const Function *CallerFn = MF.getFunction();
3509     EHPersonality Pers =
3510         CallerFn->hasPersonalityFn()
3511             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3512             : EHPersonality::Unknown;
3513     if (isFuncletEHPersonality(Pers))
3514       Mask = RegInfo->getNoPreservedMask();
3515   }
3516
3517   Ops.push_back(DAG.getRegisterMask(Mask));
3518
3519   if (InFlag.getNode())
3520     Ops.push_back(InFlag);
3521
3522   if (isTailCall) {
3523     // We used to do:
3524     //// If this is the first return lowered for this function, add the regs
3525     //// to the liveout set for the function.
3526     // This isn't right, although it's probably harmless on x86; liveouts
3527     // should be computed from returns not tail calls.  Consider a void
3528     // function making a tail call to a function returning int.
3529     MF.getFrameInfo()->setHasTailCall();
3530     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3531   }
3532
3533   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3534   InFlag = Chain.getValue(1);
3535
3536   // Create the CALLSEQ_END node.
3537   unsigned NumBytesForCalleeToPop;
3538   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3539                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3540     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3541   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3542            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3543            SR == StackStructReturn)
3544     // If this is a call to a struct-return function, the callee
3545     // pops the hidden struct pointer, so we have to push it back.
3546     // This is common for Darwin/X86, Linux & Mingw32 targets.
3547     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3548     NumBytesForCalleeToPop = 4;
3549   else
3550     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3551
3552   // Returns a flag for retval copy to use.
3553   if (!IsSibcall) {
3554     Chain = DAG.getCALLSEQ_END(Chain,
3555                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3556                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3557                                                      true),
3558                                InFlag, dl);
3559     InFlag = Chain.getValue(1);
3560   }
3561
3562   // Handle result values, copying them out of physregs into vregs that we
3563   // return.
3564   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3565                          Ins, dl, DAG, InVals);
3566 }
3567
3568 //===----------------------------------------------------------------------===//
3569 //                Fast Calling Convention (tail call) implementation
3570 //===----------------------------------------------------------------------===//
3571
3572 //  Like std call, callee cleans arguments, convention except that ECX is
3573 //  reserved for storing the tail called function address. Only 2 registers are
3574 //  free for argument passing (inreg). Tail call optimization is performed
3575 //  provided:
3576 //                * tailcallopt is enabled
3577 //                * caller/callee are fastcc
3578 //  On X86_64 architecture with GOT-style position independent code only local
3579 //  (within module) calls are supported at the moment.
3580 //  To keep the stack aligned according to platform abi the function
3581 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3582 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3583 //  If a tail called function callee has more arguments than the caller the
3584 //  caller needs to make sure that there is room to move the RETADDR to. This is
3585 //  achieved by reserving an area the size of the argument delta right after the
3586 //  original RETADDR, but before the saved framepointer or the spilled registers
3587 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3588 //  stack layout:
3589 //    arg1
3590 //    arg2
3591 //    RETADDR
3592 //    [ new RETADDR
3593 //      move area ]
3594 //    (possible EBP)
3595 //    ESI
3596 //    EDI
3597 //    local1 ..
3598
3599 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3600 /// requirement.
3601 unsigned
3602 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3603                                                SelectionDAG& DAG) const {
3604   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3605   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3606   unsigned StackAlignment = TFI.getStackAlignment();
3607   uint64_t AlignMask = StackAlignment - 1;
3608   int64_t Offset = StackSize;
3609   unsigned SlotSize = RegInfo->getSlotSize();
3610   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3611     // Number smaller than 12 so just add the difference.
3612     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3613   } else {
3614     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3615     Offset = ((~AlignMask) & Offset) + StackAlignment +
3616       (StackAlignment-SlotSize);
3617   }
3618   return Offset;
3619 }
3620
3621 /// Return true if the given stack call argument is already available in the
3622 /// same position (relatively) of the caller's incoming argument stack.
3623 static
3624 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3625                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3626                          const X86InstrInfo *TII) {
3627   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3628   int FI = INT_MAX;
3629   if (Arg.getOpcode() == ISD::CopyFromReg) {
3630     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3631     if (!TargetRegisterInfo::isVirtualRegister(VR))
3632       return false;
3633     MachineInstr *Def = MRI->getVRegDef(VR);
3634     if (!Def)
3635       return false;
3636     if (!Flags.isByVal()) {
3637       if (!TII->isLoadFromStackSlot(Def, FI))
3638         return false;
3639     } else {
3640       unsigned Opcode = Def->getOpcode();
3641       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3642            Opcode == X86::LEA64_32r) &&
3643           Def->getOperand(1).isFI()) {
3644         FI = Def->getOperand(1).getIndex();
3645         Bytes = Flags.getByValSize();
3646       } else
3647         return false;
3648     }
3649   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3650     if (Flags.isByVal())
3651       // ByVal argument is passed in as a pointer but it's now being
3652       // dereferenced. e.g.
3653       // define @foo(%struct.X* %A) {
3654       //   tail call @bar(%struct.X* byval %A)
3655       // }
3656       return false;
3657     SDValue Ptr = Ld->getBasePtr();
3658     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3659     if (!FINode)
3660       return false;
3661     FI = FINode->getIndex();
3662   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3663     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3664     FI = FINode->getIndex();
3665     Bytes = Flags.getByValSize();
3666   } else
3667     return false;
3668
3669   assert(FI != INT_MAX);
3670   if (!MFI->isFixedObjectIndex(FI))
3671     return false;
3672   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3673 }
3674
3675 /// Check whether the call is eligible for tail call optimization. Targets
3676 /// that want to do tail call optimization should implement this function.
3677 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3678     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3679     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3680     const SmallVectorImpl<ISD::OutputArg> &Outs,
3681     const SmallVectorImpl<SDValue> &OutVals,
3682     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3683   if (!mayTailCallThisCC(CalleeCC))
3684     return false;
3685
3686   // If -tailcallopt is specified, make fastcc functions tail-callable.
3687   MachineFunction &MF = DAG.getMachineFunction();
3688   const Function *CallerF = MF.getFunction();
3689
3690   // If the function return type is x86_fp80 and the callee return type is not,
3691   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3692   // perform a tailcall optimization here.
3693   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3694     return false;
3695
3696   CallingConv::ID CallerCC = CallerF->getCallingConv();
3697   bool CCMatch = CallerCC == CalleeCC;
3698   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3699   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3700
3701   // Win64 functions have extra shadow space for argument homing. Don't do the
3702   // sibcall if the caller and callee have mismatched expectations for this
3703   // space.
3704   if (IsCalleeWin64 != IsCallerWin64)
3705     return false;
3706
3707   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3708     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3709       return true;
3710     return false;
3711   }
3712
3713   // Look for obvious safe cases to perform tail call optimization that do not
3714   // require ABI changes. This is what gcc calls sibcall.
3715
3716   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3717   // emit a special epilogue.
3718   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3719   if (RegInfo->needsStackRealignment(MF))
3720     return false;
3721
3722   // Also avoid sibcall optimization if either caller or callee uses struct
3723   // return semantics.
3724   if (isCalleeStructRet || isCallerStructRet)
3725     return false;
3726
3727   // Do not sibcall optimize vararg calls unless all arguments are passed via
3728   // registers.
3729   if (isVarArg && !Outs.empty()) {
3730     // Optimizing for varargs on Win64 is unlikely to be safe without
3731     // additional testing.
3732     if (IsCalleeWin64 || IsCallerWin64)
3733       return false;
3734
3735     SmallVector<CCValAssign, 16> ArgLocs;
3736     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3737                    *DAG.getContext());
3738
3739     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3740     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3741       if (!ArgLocs[i].isRegLoc())
3742         return false;
3743   }
3744
3745   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3746   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3747   // this into a sibcall.
3748   bool Unused = false;
3749   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3750     if (!Ins[i].Used) {
3751       Unused = true;
3752       break;
3753     }
3754   }
3755   if (Unused) {
3756     SmallVector<CCValAssign, 16> RVLocs;
3757     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3758                    *DAG.getContext());
3759     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3760     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3761       CCValAssign &VA = RVLocs[i];
3762       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3763         return false;
3764     }
3765   }
3766
3767   // If the calling conventions do not match, then we'd better make sure the
3768   // results are returned in the same way as what the caller expects.
3769   if (!CCMatch) {
3770     SmallVector<CCValAssign, 16> RVLocs1;
3771     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3772                     *DAG.getContext());
3773     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3774
3775     SmallVector<CCValAssign, 16> RVLocs2;
3776     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3777                     *DAG.getContext());
3778     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3779
3780     if (RVLocs1.size() != RVLocs2.size())
3781       return false;
3782     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3783       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3784         return false;
3785       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3786         return false;
3787       if (RVLocs1[i].isRegLoc()) {
3788         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3789           return false;
3790       } else {
3791         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3792           return false;
3793       }
3794     }
3795   }
3796
3797   unsigned StackArgsSize = 0;
3798
3799   // If the callee takes no arguments then go on to check the results of the
3800   // call.
3801   if (!Outs.empty()) {
3802     // Check if stack adjustment is needed. For now, do not do this if any
3803     // argument is passed on the stack.
3804     SmallVector<CCValAssign, 16> ArgLocs;
3805     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3806                    *DAG.getContext());
3807
3808     // Allocate shadow area for Win64
3809     if (IsCalleeWin64)
3810       CCInfo.AllocateStack(32, 8);
3811
3812     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3813     StackArgsSize = CCInfo.getNextStackOffset();
3814
3815     if (CCInfo.getNextStackOffset()) {
3816       // Check if the arguments are already laid out in the right way as
3817       // the caller's fixed stack objects.
3818       MachineFrameInfo *MFI = MF.getFrameInfo();
3819       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3820       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3821       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3822         CCValAssign &VA = ArgLocs[i];
3823         SDValue Arg = OutVals[i];
3824         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3825         if (VA.getLocInfo() == CCValAssign::Indirect)
3826           return false;
3827         if (!VA.isRegLoc()) {
3828           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3829                                    MFI, MRI, TII))
3830             return false;
3831         }
3832       }
3833     }
3834
3835     // If the tailcall address may be in a register, then make sure it's
3836     // possible to register allocate for it. In 32-bit, the call address can
3837     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3838     // callee-saved registers are restored. These happen to be the same
3839     // registers used to pass 'inreg' arguments so watch out for those.
3840     if (!Subtarget->is64Bit() &&
3841         ((!isa<GlobalAddressSDNode>(Callee) &&
3842           !isa<ExternalSymbolSDNode>(Callee)) ||
3843          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3844       unsigned NumInRegs = 0;
3845       // In PIC we need an extra register to formulate the address computation
3846       // for the callee.
3847       unsigned MaxInRegs =
3848         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3849
3850       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3851         CCValAssign &VA = ArgLocs[i];
3852         if (!VA.isRegLoc())
3853           continue;
3854         unsigned Reg = VA.getLocReg();
3855         switch (Reg) {
3856         default: break;
3857         case X86::EAX: case X86::EDX: case X86::ECX:
3858           if (++NumInRegs == MaxInRegs)
3859             return false;
3860           break;
3861         }
3862       }
3863     }
3864   }
3865
3866   bool CalleeWillPop =
3867       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3868                        MF.getTarget().Options.GuaranteedTailCallOpt);
3869
3870   if (unsigned BytesToPop =
3871           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3872     // If we have bytes to pop, the callee must pop them.
3873     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3874     if (!CalleePopMatches)
3875       return false;
3876   } else if (CalleeWillPop && StackArgsSize > 0) {
3877     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3878     return false;
3879   }
3880
3881   return true;
3882 }
3883
3884 FastISel *
3885 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3886                                   const TargetLibraryInfo *libInfo) const {
3887   return X86::createFastISel(funcInfo, libInfo);
3888 }
3889
3890 //===----------------------------------------------------------------------===//
3891 //                           Other Lowering Hooks
3892 //===----------------------------------------------------------------------===//
3893
3894 static bool MayFoldLoad(SDValue Op) {
3895   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3896 }
3897
3898 static bool MayFoldIntoStore(SDValue Op) {
3899   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3900 }
3901
3902 static bool isTargetShuffle(unsigned Opcode) {
3903   switch(Opcode) {
3904   default: return false;
3905   case X86ISD::BLENDI:
3906   case X86ISD::PSHUFB:
3907   case X86ISD::PSHUFD:
3908   case X86ISD::PSHUFHW:
3909   case X86ISD::PSHUFLW:
3910   case X86ISD::SHUFP:
3911   case X86ISD::INSERTPS:
3912   case X86ISD::PALIGNR:
3913   case X86ISD::MOVLHPS:
3914   case X86ISD::MOVLHPD:
3915   case X86ISD::MOVHLPS:
3916   case X86ISD::MOVLPS:
3917   case X86ISD::MOVLPD:
3918   case X86ISD::MOVSHDUP:
3919   case X86ISD::MOVSLDUP:
3920   case X86ISD::MOVDDUP:
3921   case X86ISD::MOVSS:
3922   case X86ISD::MOVSD:
3923   case X86ISD::UNPCKL:
3924   case X86ISD::UNPCKH:
3925   case X86ISD::VPERMILPI:
3926   case X86ISD::VPERM2X128:
3927   case X86ISD::VPERMI:
3928   case X86ISD::VPERMV:
3929   case X86ISD::VPERMV3:
3930     return true;
3931   }
3932 }
3933
3934 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3935                                     SDValue V1, unsigned TargetMask,
3936                                     SelectionDAG &DAG) {
3937   switch(Opc) {
3938   default: llvm_unreachable("Unknown x86 shuffle node");
3939   case X86ISD::PSHUFD:
3940   case X86ISD::PSHUFHW:
3941   case X86ISD::PSHUFLW:
3942   case X86ISD::VPERMILPI:
3943   case X86ISD::VPERMI:
3944     return DAG.getNode(Opc, dl, VT, V1,
3945                        DAG.getConstant(TargetMask, dl, MVT::i8));
3946   }
3947 }
3948
3949 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3950                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3951   switch(Opc) {
3952   default: llvm_unreachable("Unknown x86 shuffle node");
3953   case X86ISD::MOVLHPS:
3954   case X86ISD::MOVLHPD:
3955   case X86ISD::MOVHLPS:
3956   case X86ISD::MOVLPS:
3957   case X86ISD::MOVLPD:
3958   case X86ISD::MOVSS:
3959   case X86ISD::MOVSD:
3960   case X86ISD::UNPCKL:
3961   case X86ISD::UNPCKH:
3962     return DAG.getNode(Opc, dl, VT, V1, V2);
3963   }
3964 }
3965
3966 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3967   MachineFunction &MF = DAG.getMachineFunction();
3968   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3969   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3970   int ReturnAddrIndex = FuncInfo->getRAIndex();
3971
3972   if (ReturnAddrIndex == 0) {
3973     // Set up a frame object for the return address.
3974     unsigned SlotSize = RegInfo->getSlotSize();
3975     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3976                                                            -(int64_t)SlotSize,
3977                                                            false);
3978     FuncInfo->setRAIndex(ReturnAddrIndex);
3979   }
3980
3981   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3982 }
3983
3984 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3985                                        bool hasSymbolicDisplacement) {
3986   // Offset should fit into 32 bit immediate field.
3987   if (!isInt<32>(Offset))
3988     return false;
3989
3990   // If we don't have a symbolic displacement - we don't have any extra
3991   // restrictions.
3992   if (!hasSymbolicDisplacement)
3993     return true;
3994
3995   // FIXME: Some tweaks might be needed for medium code model.
3996   if (M != CodeModel::Small && M != CodeModel::Kernel)
3997     return false;
3998
3999   // For small code model we assume that latest object is 16MB before end of 31
4000   // bits boundary. We may also accept pretty large negative constants knowing
4001   // that all objects are in the positive half of address space.
4002   if (M == CodeModel::Small && Offset < 16*1024*1024)
4003     return true;
4004
4005   // For kernel code model we know that all object resist in the negative half
4006   // of 32bits address space. We may not accept negative offsets, since they may
4007   // be just off and we may accept pretty large positive ones.
4008   if (M == CodeModel::Kernel && Offset >= 0)
4009     return true;
4010
4011   return false;
4012 }
4013
4014 /// Determines whether the callee is required to pop its own arguments.
4015 /// Callee pop is necessary to support tail calls.
4016 bool X86::isCalleePop(CallingConv::ID CallingConv,
4017                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4018   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4019   // can guarantee TCO.
4020   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4021     return true;
4022
4023   switch (CallingConv) {
4024   default:
4025     return false;
4026   case CallingConv::X86_StdCall:
4027   case CallingConv::X86_FastCall:
4028   case CallingConv::X86_ThisCall:
4029   case CallingConv::X86_VectorCall:
4030     return !is64Bit;
4031   }
4032 }
4033
4034 /// \brief Return true if the condition is an unsigned comparison operation.
4035 static bool isX86CCUnsigned(unsigned X86CC) {
4036   switch (X86CC) {
4037   default: llvm_unreachable("Invalid integer condition!");
4038   case X86::COND_E:     return true;
4039   case X86::COND_G:     return false;
4040   case X86::COND_GE:    return false;
4041   case X86::COND_L:     return false;
4042   case X86::COND_LE:    return false;
4043   case X86::COND_NE:    return true;
4044   case X86::COND_B:     return true;
4045   case X86::COND_A:     return true;
4046   case X86::COND_BE:    return true;
4047   case X86::COND_AE:    return true;
4048   }
4049 }
4050
4051 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4052   switch (SetCCOpcode) {
4053   default: llvm_unreachable("Invalid integer condition!");
4054   case ISD::SETEQ:  return X86::COND_E;
4055   case ISD::SETGT:  return X86::COND_G;
4056   case ISD::SETGE:  return X86::COND_GE;
4057   case ISD::SETLT:  return X86::COND_L;
4058   case ISD::SETLE:  return X86::COND_LE;
4059   case ISD::SETNE:  return X86::COND_NE;
4060   case ISD::SETULT: return X86::COND_B;
4061   case ISD::SETUGT: return X86::COND_A;
4062   case ISD::SETULE: return X86::COND_BE;
4063   case ISD::SETUGE: return X86::COND_AE;
4064   }
4065 }
4066
4067 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4068 /// condition code, returning the condition code and the LHS/RHS of the
4069 /// comparison to make.
4070 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4071                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4072   if (!isFP) {
4073     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4074       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4075         // X > -1   -> X == 0, jump !sign.
4076         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4077         return X86::COND_NS;
4078       }
4079       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4080         // X < 0   -> X == 0, jump on sign.
4081         return X86::COND_S;
4082       }
4083       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4084         // X < 1   -> X <= 0
4085         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4086         return X86::COND_LE;
4087       }
4088     }
4089
4090     return TranslateIntegerX86CC(SetCCOpcode);
4091   }
4092
4093   // First determine if it is required or is profitable to flip the operands.
4094
4095   // If LHS is a foldable load, but RHS is not, flip the condition.
4096   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4097       !ISD::isNON_EXTLoad(RHS.getNode())) {
4098     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4099     std::swap(LHS, RHS);
4100   }
4101
4102   switch (SetCCOpcode) {
4103   default: break;
4104   case ISD::SETOLT:
4105   case ISD::SETOLE:
4106   case ISD::SETUGT:
4107   case ISD::SETUGE:
4108     std::swap(LHS, RHS);
4109     break;
4110   }
4111
4112   // On a floating point condition, the flags are set as follows:
4113   // ZF  PF  CF   op
4114   //  0 | 0 | 0 | X > Y
4115   //  0 | 0 | 1 | X < Y
4116   //  1 | 0 | 0 | X == Y
4117   //  1 | 1 | 1 | unordered
4118   switch (SetCCOpcode) {
4119   default: llvm_unreachable("Condcode should be pre-legalized away");
4120   case ISD::SETUEQ:
4121   case ISD::SETEQ:   return X86::COND_E;
4122   case ISD::SETOLT:              // flipped
4123   case ISD::SETOGT:
4124   case ISD::SETGT:   return X86::COND_A;
4125   case ISD::SETOLE:              // flipped
4126   case ISD::SETOGE:
4127   case ISD::SETGE:   return X86::COND_AE;
4128   case ISD::SETUGT:              // flipped
4129   case ISD::SETULT:
4130   case ISD::SETLT:   return X86::COND_B;
4131   case ISD::SETUGE:              // flipped
4132   case ISD::SETULE:
4133   case ISD::SETLE:   return X86::COND_BE;
4134   case ISD::SETONE:
4135   case ISD::SETNE:   return X86::COND_NE;
4136   case ISD::SETUO:   return X86::COND_P;
4137   case ISD::SETO:    return X86::COND_NP;
4138   case ISD::SETOEQ:
4139   case ISD::SETUNE:  return X86::COND_INVALID;
4140   }
4141 }
4142
4143 /// Is there a floating point cmov for the specific X86 condition code?
4144 /// Current x86 isa includes the following FP cmov instructions:
4145 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4146 static bool hasFPCMov(unsigned X86CC) {
4147   switch (X86CC) {
4148   default:
4149     return false;
4150   case X86::COND_B:
4151   case X86::COND_BE:
4152   case X86::COND_E:
4153   case X86::COND_P:
4154   case X86::COND_A:
4155   case X86::COND_AE:
4156   case X86::COND_NE:
4157   case X86::COND_NP:
4158     return true;
4159   }
4160 }
4161
4162 /// Returns true if the target can instruction select the
4163 /// specified FP immediate natively. If false, the legalizer will
4164 /// materialize the FP immediate as a load from a constant pool.
4165 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4166   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4167     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4168       return true;
4169   }
4170   return false;
4171 }
4172
4173 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4174                                               ISD::LoadExtType ExtTy,
4175                                               EVT NewVT) const {
4176   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4177   // relocation target a movq or addq instruction: don't let the load shrink.
4178   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4179   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4180     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4181       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4182   return true;
4183 }
4184
4185 /// \brief Returns true if it is beneficial to convert a load of a constant
4186 /// to just the constant itself.
4187 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4188                                                           Type *Ty) const {
4189   assert(Ty->isIntegerTy());
4190
4191   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4192   if (BitSize == 0 || BitSize > 64)
4193     return false;
4194   return true;
4195 }
4196
4197 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4198                                                 unsigned Index) const {
4199   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4200     return false;
4201
4202   return (Index == 0 || Index == ResVT.getVectorNumElements());
4203 }
4204
4205 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4206   // Speculate cttz only if we can directly use TZCNT.
4207   return Subtarget->hasBMI();
4208 }
4209
4210 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4211   // Speculate ctlz only if we can directly use LZCNT.
4212   return Subtarget->hasLZCNT();
4213 }
4214
4215 /// Return true if every element in Mask, beginning
4216 /// from position Pos and ending in Pos+Size is undef.
4217 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4218   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4219     if (0 <= Mask[i])
4220       return false;
4221   return true;
4222 }
4223
4224 /// Return true if Val is undef or if its value falls within the
4225 /// specified range (L, H].
4226 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4227   return (Val < 0) || (Val >= Low && Val < Hi);
4228 }
4229
4230 /// Val is either less than zero (undef) or equal to the specified value.
4231 static bool isUndefOrEqual(int Val, int CmpVal) {
4232   return (Val < 0 || Val == CmpVal);
4233 }
4234
4235 /// Return true if every element in Mask, beginning
4236 /// from position Pos and ending in Pos+Size, falls within the specified
4237 /// sequential range (Low, Low+Size]. or is undef.
4238 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4239                                        unsigned Pos, unsigned Size, int Low) {
4240   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4241     if (!isUndefOrEqual(Mask[i], Low))
4242       return false;
4243   return true;
4244 }
4245
4246 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4247 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4248 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4249   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4250   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4251     return false;
4252
4253   // The index should be aligned on a vecWidth-bit boundary.
4254   uint64_t Index =
4255     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4256
4257   MVT VT = N->getSimpleValueType(0);
4258   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4259   bool Result = (Index * ElSize) % vecWidth == 0;
4260
4261   return Result;
4262 }
4263
4264 /// Return true if the specified INSERT_SUBVECTOR
4265 /// operand specifies a subvector insert that is suitable for input to
4266 /// insertion of 128 or 256-bit subvectors
4267 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4268   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4269   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4270     return false;
4271   // The index should be aligned on a vecWidth-bit boundary.
4272   uint64_t Index =
4273     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4274
4275   MVT VT = N->getSimpleValueType(0);
4276   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4277   bool Result = (Index * ElSize) % vecWidth == 0;
4278
4279   return Result;
4280 }
4281
4282 bool X86::isVINSERT128Index(SDNode *N) {
4283   return isVINSERTIndex(N, 128);
4284 }
4285
4286 bool X86::isVINSERT256Index(SDNode *N) {
4287   return isVINSERTIndex(N, 256);
4288 }
4289
4290 bool X86::isVEXTRACT128Index(SDNode *N) {
4291   return isVEXTRACTIndex(N, 128);
4292 }
4293
4294 bool X86::isVEXTRACT256Index(SDNode *N) {
4295   return isVEXTRACTIndex(N, 256);
4296 }
4297
4298 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4299   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4300   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4301          "Illegal extract subvector for VEXTRACT");
4302
4303   uint64_t Index =
4304     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4305
4306   MVT VecVT = N->getOperand(0).getSimpleValueType();
4307   MVT ElVT = VecVT.getVectorElementType();
4308
4309   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4310   return Index / NumElemsPerChunk;
4311 }
4312
4313 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4314   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4315   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4316          "Illegal insert subvector for VINSERT");
4317
4318   uint64_t Index =
4319     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4320
4321   MVT VecVT = N->getSimpleValueType(0);
4322   MVT ElVT = VecVT.getVectorElementType();
4323
4324   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4325   return Index / NumElemsPerChunk;
4326 }
4327
4328 /// Return the appropriate immediate to extract the specified
4329 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4330 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4331   return getExtractVEXTRACTImmediate(N, 128);
4332 }
4333
4334 /// Return the appropriate immediate to extract the specified
4335 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4336 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4337   return getExtractVEXTRACTImmediate(N, 256);
4338 }
4339
4340 /// Return the appropriate immediate to insert at the specified
4341 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4342 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4343   return getInsertVINSERTImmediate(N, 128);
4344 }
4345
4346 /// Return the appropriate immediate to insert at the specified
4347 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4348 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4349   return getInsertVINSERTImmediate(N, 256);
4350 }
4351
4352 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4353 bool X86::isZeroNode(SDValue Elt) {
4354   return isNullConstant(Elt) || isNullFPConstant(Elt);
4355 }
4356
4357 // Build a vector of constants
4358 // Use an UNDEF node if MaskElt == -1.
4359 // Spilt 64-bit constants in the 32-bit mode.
4360 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4361                               SelectionDAG &DAG,
4362                               SDLoc dl, bool IsMask = false) {
4363
4364   SmallVector<SDValue, 32>  Ops;
4365   bool Split = false;
4366
4367   MVT ConstVecVT = VT;
4368   unsigned NumElts = VT.getVectorNumElements();
4369   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4370   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4371     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4372     Split = true;
4373   }
4374
4375   MVT EltVT = ConstVecVT.getVectorElementType();
4376   for (unsigned i = 0; i < NumElts; ++i) {
4377     bool IsUndef = Values[i] < 0 && IsMask;
4378     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4379       DAG.getConstant(Values[i], dl, EltVT);
4380     Ops.push_back(OpNode);
4381     if (Split)
4382       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4383                     DAG.getConstant(0, dl, EltVT));
4384   }
4385   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4386   if (Split)
4387     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4388   return ConstsNode;
4389 }
4390
4391 /// Returns a vector of specified type with all zero elements.
4392 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4393                              SelectionDAG &DAG, SDLoc dl) {
4394   assert(VT.isVector() && "Expected a vector type");
4395
4396   // Always build SSE zero vectors as <4 x i32> bitcasted
4397   // to their dest type. This ensures they get CSE'd.
4398   SDValue Vec;
4399   if (VT.is128BitVector()) {  // SSE
4400     if (Subtarget->hasSSE2()) {  // SSE2
4401       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4402       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4403     } else { // SSE1
4404       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4405       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4406     }
4407   } else if (VT.is256BitVector()) { // AVX
4408     if (Subtarget->hasInt256()) { // AVX2
4409       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4410       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4411       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4412     } else {
4413       // 256-bit logic and arithmetic instructions in AVX are all
4414       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4415       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4416       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4417       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4418     }
4419   } else if (VT.is512BitVector()) { // AVX-512
4420       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4421       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4422                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4423       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4424   } else if (VT.getVectorElementType() == MVT::i1) {
4425
4426     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4427             && "Unexpected vector type");
4428     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4429             && "Unexpected vector type");
4430     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4431     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4432     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4433   } else
4434     llvm_unreachable("Unexpected vector type");
4435
4436   return DAG.getBitcast(VT, Vec);
4437 }
4438
4439 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4440                                 SelectionDAG &DAG, SDLoc dl,
4441                                 unsigned vectorWidth) {
4442   assert((vectorWidth == 128 || vectorWidth == 256) &&
4443          "Unsupported vector width");
4444   EVT VT = Vec.getValueType();
4445   EVT ElVT = VT.getVectorElementType();
4446   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4447   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4448                                   VT.getVectorNumElements()/Factor);
4449
4450   // Extract from UNDEF is UNDEF.
4451   if (Vec.getOpcode() == ISD::UNDEF)
4452     return DAG.getUNDEF(ResultVT);
4453
4454   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4455   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4456   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4457
4458   // This is the index of the first element of the vectorWidth-bit chunk
4459   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4460   IdxVal &= ~(ElemsPerChunk - 1);
4461
4462   // If the input is a buildvector just emit a smaller one.
4463   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4464     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4465                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4466
4467   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4468   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4469 }
4470
4471 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4472 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4473 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4474 /// instructions or a simple subregister reference. Idx is an index in the
4475 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4476 /// lowering EXTRACT_VECTOR_ELT operations easier.
4477 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4478                                    SelectionDAG &DAG, SDLoc dl) {
4479   assert((Vec.getValueType().is256BitVector() ||
4480           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4481   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4482 }
4483
4484 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4485 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4486                                    SelectionDAG &DAG, SDLoc dl) {
4487   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4488   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4489 }
4490
4491 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4492                                unsigned IdxVal, SelectionDAG &DAG,
4493                                SDLoc dl, unsigned vectorWidth) {
4494   assert((vectorWidth == 128 || vectorWidth == 256) &&
4495          "Unsupported vector width");
4496   // Inserting UNDEF is Result
4497   if (Vec.getOpcode() == ISD::UNDEF)
4498     return Result;
4499   EVT VT = Vec.getValueType();
4500   EVT ElVT = VT.getVectorElementType();
4501   EVT ResultVT = Result.getValueType();
4502
4503   // Insert the relevant vectorWidth bits.
4504   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4505   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4506
4507   // This is the index of the first element of the vectorWidth-bit chunk
4508   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4509   IdxVal &= ~(ElemsPerChunk - 1);
4510
4511   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4512   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4513 }
4514
4515 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4516 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4517 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4518 /// simple superregister reference.  Idx is an index in the 128 bits
4519 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4520 /// lowering INSERT_VECTOR_ELT operations easier.
4521 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4522                                   SelectionDAG &DAG, SDLoc dl) {
4523   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4524
4525   // For insertion into the zero index (low half) of a 256-bit vector, it is
4526   // more efficient to generate a blend with immediate instead of an insert*128.
4527   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4528   // extend the subvector to the size of the result vector. Make sure that
4529   // we are not recursing on that node by checking for undef here.
4530   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4531       Result.getOpcode() != ISD::UNDEF) {
4532     EVT ResultVT = Result.getValueType();
4533     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4534     SDValue Undef = DAG.getUNDEF(ResultVT);
4535     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4536                                  Vec, ZeroIndex);
4537
4538     // The blend instruction, and therefore its mask, depend on the data type.
4539     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4540     if (ScalarType.isFloatingPoint()) {
4541       // Choose either vblendps (float) or vblendpd (double).
4542       unsigned ScalarSize = ScalarType.getSizeInBits();
4543       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4544       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4545       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4546       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4547     }
4548
4549     const X86Subtarget &Subtarget =
4550     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4551
4552     // AVX2 is needed for 256-bit integer blend support.
4553     // Integers must be cast to 32-bit because there is only vpblendd;
4554     // vpblendw can't be used for this because it has a handicapped mask.
4555
4556     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4557     // is still more efficient than using the wrong domain vinsertf128 that
4558     // will be created by InsertSubVector().
4559     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4560
4561     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4562     Result = DAG.getBitcast(CastVT, Result);
4563     Vec256 = DAG.getBitcast(CastVT, Vec256);
4564     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4565     return DAG.getBitcast(ResultVT, Vec256);
4566   }
4567
4568   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4569 }
4570
4571 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4572                                   SelectionDAG &DAG, SDLoc dl) {
4573   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4574   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4575 }
4576
4577 /// Insert i1-subvector to i1-vector.
4578 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4579
4580   SDLoc dl(Op);
4581   SDValue Vec = Op.getOperand(0);
4582   SDValue SubVec = Op.getOperand(1);
4583   SDValue Idx = Op.getOperand(2);
4584
4585   if (!isa<ConstantSDNode>(Idx))
4586     return SDValue();
4587
4588   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4589   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4590     return Op;
4591
4592   MVT OpVT = Op.getSimpleValueType();
4593   MVT SubVecVT = SubVec.getSimpleValueType();
4594   unsigned NumElems = OpVT.getVectorNumElements();
4595   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4596
4597   assert(IdxVal + SubVecNumElems <= NumElems &&
4598          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4599          "Unexpected index value in INSERT_SUBVECTOR");
4600
4601   // There are 3 possible cases:
4602   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4603   // 2. Subvector should be inserted in the upper part
4604   //    (IdxVal + SubVecNumElems == NumElems)
4605   // 3. Subvector should be inserted in the middle (for example v2i1
4606   //    to v16i1, index 2)
4607
4608   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4609   SDValue Undef = DAG.getUNDEF(OpVT);
4610   SDValue WideSubVec =
4611     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4612   if (Vec.isUndef())
4613     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4614       DAG.getConstant(IdxVal, dl, MVT::i8));
4615
4616   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4617     unsigned ShiftLeft = NumElems - SubVecNumElems;
4618     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4619     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4620       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4621     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4622       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4623   }
4624
4625   if (IdxVal == 0) {
4626     // Zero lower bits of the Vec
4627     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4628     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4629     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4630     // Merge them together
4631     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4632   }
4633
4634   // Simple case when we put subvector in the upper part
4635   if (IdxVal + SubVecNumElems == NumElems) {
4636     // Zero upper bits of the Vec
4637     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4638                         DAG.getConstant(IdxVal, dl, MVT::i8));
4639     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4640     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4641     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4642     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4643   }
4644   // Subvector should be inserted in the middle - use shuffle
4645   SmallVector<int, 64> Mask;
4646   for (unsigned i = 0; i < NumElems; ++i)
4647     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4648                     i : i + NumElems);
4649   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4650 }
4651
4652 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4653 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4654 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4655 /// large BUILD_VECTORS.
4656 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4657                                    unsigned NumElems, SelectionDAG &DAG,
4658                                    SDLoc dl) {
4659   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4660   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4661 }
4662
4663 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4664                                    unsigned NumElems, SelectionDAG &DAG,
4665                                    SDLoc dl) {
4666   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4667   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4668 }
4669
4670 /// Returns a vector of specified type with all bits set.
4671 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4672 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4673 /// Then bitcast to their original type, ensuring they get CSE'd.
4674 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4675                              SelectionDAG &DAG, SDLoc dl) {
4676   assert(VT.isVector() && "Expected a vector type");
4677
4678   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4679   SDValue Vec;
4680   if (VT.is512BitVector()) {
4681     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4682                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4683     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4684   } else if (VT.is256BitVector()) {
4685     if (Subtarget->hasInt256()) { // AVX2
4686       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4687       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4688     } else { // AVX
4689       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4690       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4691     }
4692   } else if (VT.is128BitVector()) {
4693     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4694   } else
4695     llvm_unreachable("Unexpected vector type");
4696
4697   return DAG.getBitcast(VT, Vec);
4698 }
4699
4700 /// Returns a vector_shuffle node for an unpackl operation.
4701 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4702                           SDValue V2) {
4703   unsigned NumElems = VT.getVectorNumElements();
4704   SmallVector<int, 8> Mask;
4705   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4706     Mask.push_back(i);
4707     Mask.push_back(i + NumElems);
4708   }
4709   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4710 }
4711
4712 /// Returns a vector_shuffle node for an unpackh operation.
4713 static SDValue getUnpackh(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, Half = NumElems/2; i != Half; ++i) {
4718     Mask.push_back(i + Half);
4719     Mask.push_back(i + NumElems + Half);
4720   }
4721   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4722 }
4723
4724 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4725 /// This produces a shuffle where the low element of V2 is swizzled into the
4726 /// zero/undef vector, landing at element Idx.
4727 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4728 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4729                                            bool IsZero,
4730                                            const X86Subtarget *Subtarget,
4731                                            SelectionDAG &DAG) {
4732   MVT VT = V2.getSimpleValueType();
4733   SDValue V1 = IsZero
4734     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4735   unsigned NumElems = VT.getVectorNumElements();
4736   SmallVector<int, 16> MaskVec;
4737   for (unsigned i = 0; i != NumElems; ++i)
4738     // If this is the insertion idx, put the low elt of V2 here.
4739     MaskVec.push_back(i == Idx ? NumElems : i);
4740   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4741 }
4742
4743 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4744 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4745 /// uses one source. Note that this will set IsUnary for shuffles which use a
4746 /// single input multiple times, and in those cases it will
4747 /// adjust the mask to only have indices within that single input.
4748 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
4749                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4750   unsigned NumElems = VT.getVectorNumElements();
4751   SDValue ImmN;
4752
4753   IsUnary = false;
4754   bool IsFakeUnary = false;
4755   switch(N->getOpcode()) {
4756   case X86ISD::BLENDI:
4757     ImmN = N->getOperand(N->getNumOperands()-1);
4758     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4759     break;
4760   case X86ISD::SHUFP:
4761     ImmN = N->getOperand(N->getNumOperands()-1);
4762     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4763     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4764     break;
4765   case X86ISD::INSERTPS:
4766     ImmN = N->getOperand(N->getNumOperands()-1);
4767     DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4768     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4769     break;
4770   case X86ISD::UNPCKH:
4771     DecodeUNPCKHMask(VT, Mask);
4772     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4773     break;
4774   case X86ISD::UNPCKL:
4775     DecodeUNPCKLMask(VT, Mask);
4776     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4777     break;
4778   case X86ISD::MOVHLPS:
4779     DecodeMOVHLPSMask(NumElems, Mask);
4780     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4781     break;
4782   case X86ISD::MOVLHPS:
4783     DecodeMOVLHPSMask(NumElems, Mask);
4784     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4785     break;
4786   case X86ISD::PALIGNR:
4787     ImmN = N->getOperand(N->getNumOperands()-1);
4788     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4789     break;
4790   case X86ISD::PSHUFD:
4791   case X86ISD::VPERMILPI:
4792     ImmN = N->getOperand(N->getNumOperands()-1);
4793     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4794     IsUnary = true;
4795     break;
4796   case X86ISD::PSHUFHW:
4797     ImmN = N->getOperand(N->getNumOperands()-1);
4798     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4799     IsUnary = true;
4800     break;
4801   case X86ISD::PSHUFLW:
4802     ImmN = N->getOperand(N->getNumOperands()-1);
4803     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4804     IsUnary = true;
4805     break;
4806   case X86ISD::PSHUFB: {
4807     IsUnary = true;
4808     SDValue MaskNode = N->getOperand(1);
4809     while (MaskNode->getOpcode() == ISD::BITCAST)
4810       MaskNode = MaskNode->getOperand(0);
4811
4812     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4813       // If we have a build-vector, then things are easy.
4814       MVT VT = MaskNode.getSimpleValueType();
4815       assert(VT.isVector() &&
4816              "Can't produce a non-vector with a build_vector!");
4817       if (!VT.isInteger())
4818         return false;
4819
4820       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4821
4822       SmallVector<uint64_t, 32> RawMask;
4823       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4824         SDValue Op = MaskNode->getOperand(i);
4825         if (Op->getOpcode() == ISD::UNDEF) {
4826           RawMask.push_back((uint64_t)SM_SentinelUndef);
4827           continue;
4828         }
4829         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4830         if (!CN)
4831           return false;
4832         APInt MaskElement = CN->getAPIntValue();
4833
4834         // We now have to decode the element which could be any integer size and
4835         // extract each byte of it.
4836         for (int j = 0; j < NumBytesPerElement; ++j) {
4837           // Note that this is x86 and so always little endian: the low byte is
4838           // the first byte of the mask.
4839           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4840           MaskElement = MaskElement.lshr(8);
4841         }
4842       }
4843       DecodePSHUFBMask(RawMask, Mask);
4844       break;
4845     }
4846
4847     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4848     if (!MaskLoad)
4849       return false;
4850
4851     SDValue Ptr = MaskLoad->getBasePtr();
4852     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4853         Ptr->getOpcode() == X86ISD::WrapperRIP)
4854       Ptr = Ptr->getOperand(0);
4855
4856     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4857     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4858       return false;
4859
4860     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4861       DecodePSHUFBMask(C, Mask);
4862       break;
4863     }
4864
4865     return false;
4866   }
4867   case X86ISD::VPERMI:
4868     ImmN = N->getOperand(N->getNumOperands()-1);
4869     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4870     IsUnary = true;
4871     break;
4872   case X86ISD::MOVSS:
4873   case X86ISD::MOVSD:
4874     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4875     break;
4876   case X86ISD::VPERM2X128:
4877     ImmN = N->getOperand(N->getNumOperands()-1);
4878     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4879     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4880     break;
4881   case X86ISD::MOVSLDUP:
4882     DecodeMOVSLDUPMask(VT, Mask);
4883     IsUnary = true;
4884     break;
4885   case X86ISD::MOVSHDUP:
4886     DecodeMOVSHDUPMask(VT, Mask);
4887     IsUnary = true;
4888     break;
4889   case X86ISD::MOVDDUP:
4890     DecodeMOVDDUPMask(VT, Mask);
4891     IsUnary = true;
4892     break;
4893   case X86ISD::MOVLHPD:
4894   case X86ISD::MOVLPD:
4895   case X86ISD::MOVLPS:
4896     // Not yet implemented
4897     return false;
4898   case X86ISD::VPERMV: {
4899     IsUnary = true;
4900     SDValue MaskNode = N->getOperand(0);
4901     while (MaskNode->getOpcode() == ISD::BITCAST)
4902       MaskNode = MaskNode->getOperand(0);
4903
4904     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4905     SmallVector<uint64_t, 32> RawMask;
4906     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4907       // If we have a build-vector, then things are easy.
4908       assert(MaskNode.getSimpleValueType().isInteger() &&
4909              MaskNode.getSimpleValueType().getVectorNumElements() ==
4910              VT.getVectorNumElements());
4911
4912       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4913         SDValue Op = MaskNode->getOperand(i);
4914         if (Op->getOpcode() == ISD::UNDEF)
4915           RawMask.push_back((uint64_t)SM_SentinelUndef);
4916         else if (isa<ConstantSDNode>(Op)) {
4917           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4918           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4919         } else
4920           return false;
4921       }
4922       DecodeVPERMVMask(RawMask, Mask);
4923       break;
4924     }
4925     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4926       unsigned NumEltsInMask = MaskNode->getNumOperands();
4927       MaskNode = MaskNode->getOperand(0);
4928       if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4929         APInt MaskEltValue = CN->getAPIntValue();
4930         for (unsigned i = 0; i < NumEltsInMask; ++i)
4931           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4932         DecodeVPERMVMask(RawMask, Mask);
4933         break;
4934       }
4935       // It may be a scalar load
4936     }
4937
4938     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4939     if (!MaskLoad)
4940       return false;
4941
4942     SDValue Ptr = MaskLoad->getBasePtr();
4943     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4944         Ptr->getOpcode() == X86ISD::WrapperRIP)
4945       Ptr = Ptr->getOperand(0);
4946
4947     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4948     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4949       return false;
4950
4951     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4952       DecodeVPERMVMask(C, VT, Mask);
4953       break;
4954     }
4955     return false;
4956   }
4957   case X86ISD::VPERMV3: {
4958     IsUnary = false;
4959     SDValue MaskNode = N->getOperand(1);
4960     while (MaskNode->getOpcode() == ISD::BITCAST)
4961       MaskNode = MaskNode->getOperand(1);
4962
4963     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4964       // If we have a build-vector, then things are easy.
4965       assert(MaskNode.getSimpleValueType().isInteger() &&
4966              MaskNode.getSimpleValueType().getVectorNumElements() ==
4967              VT.getVectorNumElements());
4968
4969       SmallVector<uint64_t, 32> RawMask;
4970       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4971
4972       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4973         SDValue Op = MaskNode->getOperand(i);
4974         if (Op->getOpcode() == ISD::UNDEF)
4975           RawMask.push_back((uint64_t)SM_SentinelUndef);
4976         else {
4977           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4978           if (!CN)
4979             return false;
4980           APInt MaskElement = CN->getAPIntValue();
4981           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4982         }
4983       }
4984       DecodeVPERMV3Mask(RawMask, Mask);
4985       break;
4986     }
4987
4988     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4989     if (!MaskLoad)
4990       return false;
4991
4992     SDValue Ptr = MaskLoad->getBasePtr();
4993     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4994         Ptr->getOpcode() == X86ISD::WrapperRIP)
4995       Ptr = Ptr->getOperand(0);
4996
4997     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4998     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4999       return false;
5000
5001     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5002       DecodeVPERMV3Mask(C, VT, Mask);
5003       break;
5004     }
5005     return false;
5006   }
5007   default: llvm_unreachable("unknown target shuffle node");
5008   }
5009
5010   // Empty mask indicates the decode failed.
5011   if (Mask.empty())
5012     return false;
5013
5014   // Check if we're getting a shuffle mask with zero'd elements.
5015   if (!AllowSentinelZero)
5016     if (std::any_of(Mask.begin(), Mask.end(),
5017                     [](int M){ return M == SM_SentinelZero; }))
5018       return false;
5019
5020   // If we have a fake unary shuffle, the shuffle mask is spread across two
5021   // inputs that are actually the same node. Re-map the mask to always point
5022   // into the first input.
5023   if (IsFakeUnary)
5024     for (int &M : Mask)
5025       if (M >= (int)Mask.size())
5026         M -= Mask.size();
5027
5028   return true;
5029 }
5030
5031 /// Returns the scalar element that will make up the ith
5032 /// element of the result of the vector shuffle.
5033 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5034                                    unsigned Depth) {
5035   if (Depth == 6)
5036     return SDValue();  // Limit search depth.
5037
5038   SDValue V = SDValue(N, 0);
5039   EVT VT = V.getValueType();
5040   unsigned Opcode = V.getOpcode();
5041
5042   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5043   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5044     int Elt = SV->getMaskElt(Index);
5045
5046     if (Elt < 0)
5047       return DAG.getUNDEF(VT.getVectorElementType());
5048
5049     unsigned NumElems = VT.getVectorNumElements();
5050     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5051                                          : SV->getOperand(1);
5052     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5053   }
5054
5055   // Recurse into target specific vector shuffles to find scalars.
5056   if (isTargetShuffle(Opcode)) {
5057     MVT ShufVT = V.getSimpleValueType();
5058     int NumElems = (int)ShufVT.getVectorNumElements();
5059     SmallVector<int, 16> ShuffleMask;
5060     bool IsUnary;
5061
5062     if (!getTargetShuffleMask(N, ShufVT, false, ShuffleMask, IsUnary))
5063       return SDValue();
5064
5065     int Elt = ShuffleMask[Index];
5066     if (Elt == SM_SentinelUndef)
5067       return DAG.getUNDEF(ShufVT.getVectorElementType());
5068
5069     assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5070     SDValue NewV = (Elt < NumElems) ? N->getOperand(0) : N->getOperand(1);
5071     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5072                                Depth+1);
5073   }
5074
5075   // Actual nodes that may contain scalar elements
5076   if (Opcode == ISD::BITCAST) {
5077     V = V.getOperand(0);
5078     EVT SrcVT = V.getValueType();
5079     unsigned NumElems = VT.getVectorNumElements();
5080
5081     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5082       return SDValue();
5083   }
5084
5085   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5086     return (Index == 0) ? V.getOperand(0)
5087                         : DAG.getUNDEF(VT.getVectorElementType());
5088
5089   if (V.getOpcode() == ISD::BUILD_VECTOR)
5090     return V.getOperand(Index);
5091
5092   return SDValue();
5093 }
5094
5095 /// Custom lower build_vector of v16i8.
5096 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5097                                        unsigned NumNonZero, unsigned NumZero,
5098                                        SelectionDAG &DAG,
5099                                        const X86Subtarget* Subtarget,
5100                                        const TargetLowering &TLI) {
5101   if (NumNonZero > 8)
5102     return SDValue();
5103
5104   SDLoc dl(Op);
5105   SDValue V;
5106   bool First = true;
5107
5108   // SSE4.1 - use PINSRB to insert each byte directly.
5109   if (Subtarget->hasSSE41()) {
5110     for (unsigned i = 0; i < 16; ++i) {
5111       bool isNonZero = (NonZeros & (1 << i)) != 0;
5112       if (isNonZero) {
5113         if (First) {
5114           if (NumZero)
5115             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5116           else
5117             V = DAG.getUNDEF(MVT::v16i8);
5118           First = false;
5119         }
5120         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5121                         MVT::v16i8, V, Op.getOperand(i),
5122                         DAG.getIntPtrConstant(i, dl));
5123       }
5124     }
5125
5126     return V;
5127   }
5128
5129   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5130   for (unsigned i = 0; i < 16; ++i) {
5131     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5132     if (ThisIsNonZero && First) {
5133       if (NumZero)
5134         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5135       else
5136         V = DAG.getUNDEF(MVT::v8i16);
5137       First = false;
5138     }
5139
5140     if ((i & 1) != 0) {
5141       SDValue ThisElt, LastElt;
5142       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5143       if (LastIsNonZero) {
5144         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5145                               MVT::i16, Op.getOperand(i-1));
5146       }
5147       if (ThisIsNonZero) {
5148         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5149         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5150                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5151         if (LastIsNonZero)
5152           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5153       } else
5154         ThisElt = LastElt;
5155
5156       if (ThisElt.getNode())
5157         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5158                         DAG.getIntPtrConstant(i/2, dl));
5159     }
5160   }
5161
5162   return DAG.getBitcast(MVT::v16i8, V);
5163 }
5164
5165 /// Custom lower build_vector of v8i16.
5166 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5167                                      unsigned NumNonZero, unsigned NumZero,
5168                                      SelectionDAG &DAG,
5169                                      const X86Subtarget* Subtarget,
5170                                      const TargetLowering &TLI) {
5171   if (NumNonZero > 4)
5172     return SDValue();
5173
5174   SDLoc dl(Op);
5175   SDValue V;
5176   bool First = true;
5177   for (unsigned i = 0; i < 8; ++i) {
5178     bool isNonZero = (NonZeros & (1 << i)) != 0;
5179     if (isNonZero) {
5180       if (First) {
5181         if (NumZero)
5182           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5183         else
5184           V = DAG.getUNDEF(MVT::v8i16);
5185         First = false;
5186       }
5187       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5188                       MVT::v8i16, V, Op.getOperand(i),
5189                       DAG.getIntPtrConstant(i, dl));
5190     }
5191   }
5192
5193   return V;
5194 }
5195
5196 /// Custom lower build_vector of v4i32 or v4f32.
5197 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5198                                      const X86Subtarget *Subtarget,
5199                                      const TargetLowering &TLI) {
5200   // Find all zeroable elements.
5201   std::bitset<4> Zeroable;
5202   for (int i=0; i < 4; ++i) {
5203     SDValue Elt = Op->getOperand(i);
5204     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5205   }
5206   assert(Zeroable.size() - Zeroable.count() > 1 &&
5207          "We expect at least two non-zero elements!");
5208
5209   // We only know how to deal with build_vector nodes where elements are either
5210   // zeroable or extract_vector_elt with constant index.
5211   SDValue FirstNonZero;
5212   unsigned FirstNonZeroIdx;
5213   for (unsigned i=0; i < 4; ++i) {
5214     if (Zeroable[i])
5215       continue;
5216     SDValue Elt = Op->getOperand(i);
5217     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5218         !isa<ConstantSDNode>(Elt.getOperand(1)))
5219       return SDValue();
5220     // Make sure that this node is extracting from a 128-bit vector.
5221     MVT VT = Elt.getOperand(0).getSimpleValueType();
5222     if (!VT.is128BitVector())
5223       return SDValue();
5224     if (!FirstNonZero.getNode()) {
5225       FirstNonZero = Elt;
5226       FirstNonZeroIdx = i;
5227     }
5228   }
5229
5230   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5231   SDValue V1 = FirstNonZero.getOperand(0);
5232   MVT VT = V1.getSimpleValueType();
5233
5234   // See if this build_vector can be lowered as a blend with zero.
5235   SDValue Elt;
5236   unsigned EltMaskIdx, EltIdx;
5237   int Mask[4];
5238   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5239     if (Zeroable[EltIdx]) {
5240       // The zero vector will be on the right hand side.
5241       Mask[EltIdx] = EltIdx+4;
5242       continue;
5243     }
5244
5245     Elt = Op->getOperand(EltIdx);
5246     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5247     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5248     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5249       break;
5250     Mask[EltIdx] = EltIdx;
5251   }
5252
5253   if (EltIdx == 4) {
5254     // Let the shuffle legalizer deal with blend operations.
5255     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5256     if (V1.getSimpleValueType() != VT)
5257       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5258     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5259   }
5260
5261   // See if we can lower this build_vector to a INSERTPS.
5262   if (!Subtarget->hasSSE41())
5263     return SDValue();
5264
5265   SDValue V2 = Elt.getOperand(0);
5266   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5267     V1 = SDValue();
5268
5269   bool CanFold = true;
5270   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5271     if (Zeroable[i])
5272       continue;
5273
5274     SDValue Current = Op->getOperand(i);
5275     SDValue SrcVector = Current->getOperand(0);
5276     if (!V1.getNode())
5277       V1 = SrcVector;
5278     CanFold = SrcVector == V1 &&
5279       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5280   }
5281
5282   if (!CanFold)
5283     return SDValue();
5284
5285   assert(V1.getNode() && "Expected at least two non-zero elements!");
5286   if (V1.getSimpleValueType() != MVT::v4f32)
5287     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5288   if (V2.getSimpleValueType() != MVT::v4f32)
5289     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5290
5291   // Ok, we can emit an INSERTPS instruction.
5292   unsigned ZMask = Zeroable.to_ulong();
5293
5294   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5295   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5296   SDLoc DL(Op);
5297   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5298                                DAG.getIntPtrConstant(InsertPSMask, DL));
5299   return DAG.getBitcast(VT, Result);
5300 }
5301
5302 /// Return a vector logical shift node.
5303 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5304                          unsigned NumBits, SelectionDAG &DAG,
5305                          const TargetLowering &TLI, SDLoc dl) {
5306   assert(VT.is128BitVector() && "Unknown type for VShift");
5307   MVT ShVT = MVT::v2i64;
5308   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5309   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5310   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5311   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5312   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5313   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5314 }
5315
5316 static SDValue
5317 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5318
5319   // Check if the scalar load can be widened into a vector load. And if
5320   // the address is "base + cst" see if the cst can be "absorbed" into
5321   // the shuffle mask.
5322   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5323     SDValue Ptr = LD->getBasePtr();
5324     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5325       return SDValue();
5326     EVT PVT = LD->getValueType(0);
5327     if (PVT != MVT::i32 && PVT != MVT::f32)
5328       return SDValue();
5329
5330     int FI = -1;
5331     int64_t Offset = 0;
5332     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5333       FI = FINode->getIndex();
5334       Offset = 0;
5335     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5336                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5337       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5338       Offset = Ptr.getConstantOperandVal(1);
5339       Ptr = Ptr.getOperand(0);
5340     } else {
5341       return SDValue();
5342     }
5343
5344     // FIXME: 256-bit vector instructions don't require a strict alignment,
5345     // improve this code to support it better.
5346     unsigned RequiredAlign = VT.getSizeInBits()/8;
5347     SDValue Chain = LD->getChain();
5348     // Make sure the stack object alignment is at least 16 or 32.
5349     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5350     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5351       if (MFI->isFixedObjectIndex(FI)) {
5352         // Can't change the alignment. FIXME: It's possible to compute
5353         // the exact stack offset and reference FI + adjust offset instead.
5354         // If someone *really* cares about this. That's the way to implement it.
5355         return SDValue();
5356       } else {
5357         MFI->setObjectAlignment(FI, RequiredAlign);
5358       }
5359     }
5360
5361     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5362     // Ptr + (Offset & ~15).
5363     if (Offset < 0)
5364       return SDValue();
5365     if ((Offset % RequiredAlign) & 3)
5366       return SDValue();
5367     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5368     if (StartOffset) {
5369       SDLoc DL(Ptr);
5370       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5371                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5372     }
5373
5374     int EltNo = (Offset - StartOffset) >> 2;
5375     unsigned NumElems = VT.getVectorNumElements();
5376
5377     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5378     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5379                              LD->getPointerInfo().getWithOffset(StartOffset),
5380                              false, false, false, 0);
5381
5382     SmallVector<int, 8> Mask(NumElems, EltNo);
5383
5384     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5385   }
5386
5387   return SDValue();
5388 }
5389
5390 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5391 /// elements can be replaced by a single large load which has the same value as
5392 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5393 ///
5394 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5395 ///
5396 /// FIXME: we'd also like to handle the case where the last elements are zero
5397 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5398 /// There's even a handy isZeroNode for that purpose.
5399 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5400                                         SDLoc &DL, SelectionDAG &DAG,
5401                                         bool isAfterLegalize) {
5402   unsigned NumElems = Elts.size();
5403
5404   LoadSDNode *LDBase = nullptr;
5405   unsigned LastLoadedElt = -1U;
5406
5407   // For each element in the initializer, see if we've found a load or an undef.
5408   // If we don't find an initial load element, or later load elements are
5409   // non-consecutive, bail out.
5410   for (unsigned i = 0; i < NumElems; ++i) {
5411     SDValue Elt = Elts[i];
5412     // Look through a bitcast.
5413     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5414       Elt = Elt.getOperand(0);
5415     if (!Elt.getNode() ||
5416         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5417       return SDValue();
5418     if (!LDBase) {
5419       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5420         return SDValue();
5421       LDBase = cast<LoadSDNode>(Elt.getNode());
5422       LastLoadedElt = i;
5423       continue;
5424     }
5425     if (Elt.getOpcode() == ISD::UNDEF)
5426       continue;
5427
5428     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5429     EVT LdVT = Elt.getValueType();
5430     // Each loaded element must be the correct fractional portion of the
5431     // requested vector load.
5432     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5433       return SDValue();
5434     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5435       return SDValue();
5436     LastLoadedElt = i;
5437   }
5438
5439   // If we have found an entire vector of loads and undefs, then return a large
5440   // load of the entire vector width starting at the base pointer.  If we found
5441   // consecutive loads for the low half, generate a vzext_load node.
5442   if (LastLoadedElt == NumElems - 1) {
5443     assert(LDBase && "Did not find base load for merging consecutive loads");
5444     EVT EltVT = LDBase->getValueType(0);
5445     // Ensure that the input vector size for the merged loads matches the
5446     // cumulative size of the input elements.
5447     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5448       return SDValue();
5449
5450     if (isAfterLegalize &&
5451         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5452       return SDValue();
5453
5454     SDValue NewLd = SDValue();
5455
5456     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5457                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5458                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5459                         LDBase->getAlignment());
5460
5461     if (LDBase->hasAnyUseOfValue(1)) {
5462       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5463                                      SDValue(LDBase, 1),
5464                                      SDValue(NewLd.getNode(), 1));
5465       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5466       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5467                              SDValue(NewLd.getNode(), 1));
5468     }
5469
5470     return NewLd;
5471   }
5472
5473   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5474   //of a v4i32 / v4f32. It's probably worth generalizing.
5475   EVT EltVT = VT.getVectorElementType();
5476   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5477       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5478     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5479     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5480     SDValue ResNode =
5481         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5482                                 LDBase->getPointerInfo(),
5483                                 LDBase->getAlignment(),
5484                                 false/*isVolatile*/, true/*ReadMem*/,
5485                                 false/*WriteMem*/);
5486
5487     // Make sure the newly-created LOAD is in the same position as LDBase in
5488     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5489     // update uses of LDBase's output chain to use the TokenFactor.
5490     if (LDBase->hasAnyUseOfValue(1)) {
5491       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5492                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5493       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5494       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5495                              SDValue(ResNode.getNode(), 1));
5496     }
5497
5498     return DAG.getBitcast(VT, ResNode);
5499   }
5500   return SDValue();
5501 }
5502
5503 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5504 /// to generate a splat value for the following cases:
5505 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5506 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5507 /// a scalar load, or a constant.
5508 /// The VBROADCAST node is returned when a pattern is found,
5509 /// or SDValue() otherwise.
5510 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5511                                     SelectionDAG &DAG) {
5512   // VBROADCAST requires AVX.
5513   // TODO: Splats could be generated for non-AVX CPUs using SSE
5514   // instructions, but there's less potential gain for only 128-bit vectors.
5515   if (!Subtarget->hasAVX())
5516     return SDValue();
5517
5518   MVT VT = Op.getSimpleValueType();
5519   SDLoc dl(Op);
5520
5521   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5522          "Unsupported vector type for broadcast.");
5523
5524   SDValue Ld;
5525   bool ConstSplatVal;
5526
5527   switch (Op.getOpcode()) {
5528     default:
5529       // Unknown pattern found.
5530       return SDValue();
5531
5532     case ISD::BUILD_VECTOR: {
5533       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5534       BitVector UndefElements;
5535       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5536
5537       // We need a splat of a single value to use broadcast, and it doesn't
5538       // make any sense if the value is only in one element of the vector.
5539       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5540         return SDValue();
5541
5542       Ld = Splat;
5543       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5544                        Ld.getOpcode() == ISD::ConstantFP);
5545
5546       // Make sure that all of the users of a non-constant load are from the
5547       // BUILD_VECTOR node.
5548       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5549         return SDValue();
5550       break;
5551     }
5552
5553     case ISD::VECTOR_SHUFFLE: {
5554       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5555
5556       // Shuffles must have a splat mask where the first element is
5557       // broadcasted.
5558       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5559         return SDValue();
5560
5561       SDValue Sc = Op.getOperand(0);
5562       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5563           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5564
5565         if (!Subtarget->hasInt256())
5566           return SDValue();
5567
5568         // Use the register form of the broadcast instruction available on AVX2.
5569         if (VT.getSizeInBits() >= 256)
5570           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5571         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5572       }
5573
5574       Ld = Sc.getOperand(0);
5575       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5576                        Ld.getOpcode() == ISD::ConstantFP);
5577
5578       // The scalar_to_vector node and the suspected
5579       // load node must have exactly one user.
5580       // Constants may have multiple users.
5581
5582       // AVX-512 has register version of the broadcast
5583       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5584         Ld.getValueType().getSizeInBits() >= 32;
5585       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5586           !hasRegVer))
5587         return SDValue();
5588       break;
5589     }
5590   }
5591
5592   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5593   bool IsGE256 = (VT.getSizeInBits() >= 256);
5594
5595   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5596   // instruction to save 8 or more bytes of constant pool data.
5597   // TODO: If multiple splats are generated to load the same constant,
5598   // it may be detrimental to overall size. There needs to be a way to detect
5599   // that condition to know if this is truly a size win.
5600   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5601
5602   // Handle broadcasting a single constant scalar from the constant pool
5603   // into a vector.
5604   // On Sandybridge (no AVX2), it is still better to load a constant vector
5605   // from the constant pool and not to broadcast it from a scalar.
5606   // But override that restriction when optimizing for size.
5607   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5608   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5609     EVT CVT = Ld.getValueType();
5610     assert(!CVT.isVector() && "Must not broadcast a vector type");
5611
5612     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5613     // For size optimization, also splat v2f64 and v2i64, and for size opt
5614     // with AVX2, also splat i8 and i16.
5615     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5616     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5617         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5618       const Constant *C = nullptr;
5619       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5620         C = CI->getConstantIntValue();
5621       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5622         C = CF->getConstantFPValue();
5623
5624       assert(C && "Invalid constant type");
5625
5626       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5627       SDValue CP =
5628           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5629       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5630       Ld = DAG.getLoad(
5631           CVT, dl, DAG.getEntryNode(), CP,
5632           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5633           false, false, Alignment);
5634
5635       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5636     }
5637   }
5638
5639   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5640
5641   // Handle AVX2 in-register broadcasts.
5642   if (!IsLoad && Subtarget->hasInt256() &&
5643       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5644     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5645
5646   // The scalar source must be a normal load.
5647   if (!IsLoad)
5648     return SDValue();
5649
5650   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5651       (Subtarget->hasVLX() && ScalarSize == 64))
5652     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5653
5654   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5655   // double since there is no vbroadcastsd xmm
5656   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5657     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5658       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5659   }
5660
5661   // Unsupported broadcast.
5662   return SDValue();
5663 }
5664
5665 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5666 /// underlying vector and index.
5667 ///
5668 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5669 /// index.
5670 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5671                                          SDValue ExtIdx) {
5672   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5673   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5674     return Idx;
5675
5676   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5677   // lowered this:
5678   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5679   // to:
5680   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5681   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5682   //                           undef)
5683   //                       Constant<0>)
5684   // In this case the vector is the extract_subvector expression and the index
5685   // is 2, as specified by the shuffle.
5686   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5687   SDValue ShuffleVec = SVOp->getOperand(0);
5688   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5689   assert(ShuffleVecVT.getVectorElementType() ==
5690          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5691
5692   int ShuffleIdx = SVOp->getMaskElt(Idx);
5693   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5694     ExtractedFromVec = ShuffleVec;
5695     return ShuffleIdx;
5696   }
5697   return Idx;
5698 }
5699
5700 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5701   MVT VT = Op.getSimpleValueType();
5702
5703   // Skip if insert_vec_elt is not supported.
5704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5705   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5706     return SDValue();
5707
5708   SDLoc DL(Op);
5709   unsigned NumElems = Op.getNumOperands();
5710
5711   SDValue VecIn1;
5712   SDValue VecIn2;
5713   SmallVector<unsigned, 4> InsertIndices;
5714   SmallVector<int, 8> Mask(NumElems, -1);
5715
5716   for (unsigned i = 0; i != NumElems; ++i) {
5717     unsigned Opc = Op.getOperand(i).getOpcode();
5718
5719     if (Opc == ISD::UNDEF)
5720       continue;
5721
5722     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5723       // Quit if more than 1 elements need inserting.
5724       if (InsertIndices.size() > 1)
5725         return SDValue();
5726
5727       InsertIndices.push_back(i);
5728       continue;
5729     }
5730
5731     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5732     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5733     // Quit if non-constant index.
5734     if (!isa<ConstantSDNode>(ExtIdx))
5735       return SDValue();
5736     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5737
5738     // Quit if extracted from vector of different type.
5739     if (ExtractedFromVec.getValueType() != VT)
5740       return SDValue();
5741
5742     if (!VecIn1.getNode())
5743       VecIn1 = ExtractedFromVec;
5744     else if (VecIn1 != ExtractedFromVec) {
5745       if (!VecIn2.getNode())
5746         VecIn2 = ExtractedFromVec;
5747       else if (VecIn2 != ExtractedFromVec)
5748         // Quit if more than 2 vectors to shuffle
5749         return SDValue();
5750     }
5751
5752     if (ExtractedFromVec == VecIn1)
5753       Mask[i] = Idx;
5754     else if (ExtractedFromVec == VecIn2)
5755       Mask[i] = Idx + NumElems;
5756   }
5757
5758   if (!VecIn1.getNode())
5759     return SDValue();
5760
5761   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5762   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5763   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5764     unsigned Idx = InsertIndices[i];
5765     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5766                      DAG.getIntPtrConstant(Idx, DL));
5767   }
5768
5769   return NV;
5770 }
5771
5772 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5773   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5774          Op.getScalarValueSizeInBits() == 1 &&
5775          "Can not convert non-constant vector");
5776   uint64_t Immediate = 0;
5777   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5778     SDValue In = Op.getOperand(idx);
5779     if (In.getOpcode() != ISD::UNDEF)
5780       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5781   }
5782   SDLoc dl(Op);
5783   MVT VT =
5784    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5785   return DAG.getConstant(Immediate, dl, VT);
5786 }
5787 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5788 SDValue
5789 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5790
5791   MVT VT = Op.getSimpleValueType();
5792   assert((VT.getVectorElementType() == MVT::i1) &&
5793          "Unexpected type in LowerBUILD_VECTORvXi1!");
5794
5795   SDLoc dl(Op);
5796   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5797     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5798     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5799     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5800   }
5801
5802   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5803     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5804     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5805     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5806   }
5807
5808   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5809     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5810     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5811       return DAG.getBitcast(VT, Imm);
5812     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5813     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5814                         DAG.getIntPtrConstant(0, dl));
5815   }
5816
5817   // Vector has one or more non-const elements
5818   uint64_t Immediate = 0;
5819   SmallVector<unsigned, 16> NonConstIdx;
5820   bool IsSplat = true;
5821   bool HasConstElts = false;
5822   int SplatIdx = -1;
5823   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5824     SDValue In = Op.getOperand(idx);
5825     if (In.getOpcode() == ISD::UNDEF)
5826       continue;
5827     if (!isa<ConstantSDNode>(In))
5828       NonConstIdx.push_back(idx);
5829     else {
5830       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5831       HasConstElts = true;
5832     }
5833     if (SplatIdx == -1)
5834       SplatIdx = idx;
5835     else if (In != Op.getOperand(SplatIdx))
5836       IsSplat = false;
5837   }
5838
5839   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5840   if (IsSplat)
5841     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5842                        DAG.getConstant(1, dl, VT),
5843                        DAG.getConstant(0, dl, VT));
5844
5845   // insert elements one by one
5846   SDValue DstVec;
5847   SDValue Imm;
5848   if (Immediate) {
5849     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5850     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5851   }
5852   else if (HasConstElts)
5853     Imm = DAG.getConstant(0, dl, VT);
5854   else
5855     Imm = DAG.getUNDEF(VT);
5856   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5857     DstVec = DAG.getBitcast(VT, Imm);
5858   else {
5859     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5860     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5861                          DAG.getIntPtrConstant(0, dl));
5862   }
5863
5864   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5865     unsigned InsertIdx = NonConstIdx[i];
5866     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5867                          Op.getOperand(InsertIdx),
5868                          DAG.getIntPtrConstant(InsertIdx, dl));
5869   }
5870   return DstVec;
5871 }
5872
5873 /// \brief Return true if \p N implements a horizontal binop and return the
5874 /// operands for the horizontal binop into V0 and V1.
5875 ///
5876 /// This is a helper function of LowerToHorizontalOp().
5877 /// This function checks that the build_vector \p N in input implements a
5878 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5879 /// operation to match.
5880 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5881 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5882 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5883 /// arithmetic sub.
5884 ///
5885 /// This function only analyzes elements of \p N whose indices are
5886 /// in range [BaseIdx, LastIdx).
5887 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5888                               SelectionDAG &DAG,
5889                               unsigned BaseIdx, unsigned LastIdx,
5890                               SDValue &V0, SDValue &V1) {
5891   EVT VT = N->getValueType(0);
5892
5893   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5894   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5895          "Invalid Vector in input!");
5896
5897   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5898   bool CanFold = true;
5899   unsigned ExpectedVExtractIdx = BaseIdx;
5900   unsigned NumElts = LastIdx - BaseIdx;
5901   V0 = DAG.getUNDEF(VT);
5902   V1 = DAG.getUNDEF(VT);
5903
5904   // Check if N implements a horizontal binop.
5905   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5906     SDValue Op = N->getOperand(i + BaseIdx);
5907
5908     // Skip UNDEFs.
5909     if (Op->getOpcode() == ISD::UNDEF) {
5910       // Update the expected vector extract index.
5911       if (i * 2 == NumElts)
5912         ExpectedVExtractIdx = BaseIdx;
5913       ExpectedVExtractIdx += 2;
5914       continue;
5915     }
5916
5917     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5918
5919     if (!CanFold)
5920       break;
5921
5922     SDValue Op0 = Op.getOperand(0);
5923     SDValue Op1 = Op.getOperand(1);
5924
5925     // Try to match the following pattern:
5926     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5927     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5928         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5929         Op0.getOperand(0) == Op1.getOperand(0) &&
5930         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5931         isa<ConstantSDNode>(Op1.getOperand(1)));
5932     if (!CanFold)
5933       break;
5934
5935     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5936     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5937
5938     if (i * 2 < NumElts) {
5939       if (V0.getOpcode() == ISD::UNDEF) {
5940         V0 = Op0.getOperand(0);
5941         if (V0.getValueType() != VT)
5942           return false;
5943       }
5944     } else {
5945       if (V1.getOpcode() == ISD::UNDEF) {
5946         V1 = Op0.getOperand(0);
5947         if (V1.getValueType() != VT)
5948           return false;
5949       }
5950       if (i * 2 == NumElts)
5951         ExpectedVExtractIdx = BaseIdx;
5952     }
5953
5954     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5955     if (I0 == ExpectedVExtractIdx)
5956       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5957     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5958       // Try to match the following dag sequence:
5959       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5960       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5961     } else
5962       CanFold = false;
5963
5964     ExpectedVExtractIdx += 2;
5965   }
5966
5967   return CanFold;
5968 }
5969
5970 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5971 /// a concat_vector.
5972 ///
5973 /// This is a helper function of LowerToHorizontalOp().
5974 /// This function expects two 256-bit vectors called V0 and V1.
5975 /// At first, each vector is split into two separate 128-bit vectors.
5976 /// Then, the resulting 128-bit vectors are used to implement two
5977 /// horizontal binary operations.
5978 ///
5979 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5980 ///
5981 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5982 /// the two new horizontal binop.
5983 /// When Mode is set, the first horizontal binop dag node would take as input
5984 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5985 /// horizontal binop dag node would take as input the lower 128-bit of V1
5986 /// and the upper 128-bit of V1.
5987 ///   Example:
5988 ///     HADD V0_LO, V0_HI
5989 ///     HADD V1_LO, V1_HI
5990 ///
5991 /// Otherwise, the first horizontal binop dag node takes as input the lower
5992 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5993 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5994 ///   Example:
5995 ///     HADD V0_LO, V1_LO
5996 ///     HADD V0_HI, V1_HI
5997 ///
5998 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5999 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6000 /// the upper 128-bits of the result.
6001 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6002                                      SDLoc DL, SelectionDAG &DAG,
6003                                      unsigned X86Opcode, bool Mode,
6004                                      bool isUndefLO, bool isUndefHI) {
6005   EVT VT = V0.getValueType();
6006   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6007          "Invalid nodes in input!");
6008
6009   unsigned NumElts = VT.getVectorNumElements();
6010   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6011   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6012   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6013   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6014   EVT NewVT = V0_LO.getValueType();
6015
6016   SDValue LO = DAG.getUNDEF(NewVT);
6017   SDValue HI = DAG.getUNDEF(NewVT);
6018
6019   if (Mode) {
6020     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6021     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6022       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6023     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6024       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6025   } else {
6026     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6027     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6028                        V1_LO->getOpcode() != ISD::UNDEF))
6029       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6030
6031     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6032                        V1_HI->getOpcode() != ISD::UNDEF))
6033       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6034   }
6035
6036   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6037 }
6038
6039 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6040 /// node.
6041 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6042                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6043   MVT VT = BV->getSimpleValueType(0);
6044   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6045       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6046     return SDValue();
6047
6048   SDLoc DL(BV);
6049   unsigned NumElts = VT.getVectorNumElements();
6050   SDValue InVec0 = DAG.getUNDEF(VT);
6051   SDValue InVec1 = DAG.getUNDEF(VT);
6052
6053   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6054           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6055
6056   // Odd-numbered elements in the input build vector are obtained from
6057   // adding two integer/float elements.
6058   // Even-numbered elements in the input build vector are obtained from
6059   // subtracting two integer/float elements.
6060   unsigned ExpectedOpcode = ISD::FSUB;
6061   unsigned NextExpectedOpcode = ISD::FADD;
6062   bool AddFound = false;
6063   bool SubFound = false;
6064
6065   for (unsigned i = 0, e = NumElts; i != e; ++i) {
6066     SDValue Op = BV->getOperand(i);
6067
6068     // Skip 'undef' values.
6069     unsigned Opcode = Op.getOpcode();
6070     if (Opcode == ISD::UNDEF) {
6071       std::swap(ExpectedOpcode, NextExpectedOpcode);
6072       continue;
6073     }
6074
6075     // Early exit if we found an unexpected opcode.
6076     if (Opcode != ExpectedOpcode)
6077       return SDValue();
6078
6079     SDValue Op0 = Op.getOperand(0);
6080     SDValue Op1 = Op.getOperand(1);
6081
6082     // Try to match the following pattern:
6083     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6084     // Early exit if we cannot match that sequence.
6085     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6086         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6087         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6088         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6089         Op0.getOperand(1) != Op1.getOperand(1))
6090       return SDValue();
6091
6092     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6093     if (I0 != i)
6094       return SDValue();
6095
6096     // We found a valid add/sub node. Update the information accordingly.
6097     if (i & 1)
6098       AddFound = true;
6099     else
6100       SubFound = true;
6101
6102     // Update InVec0 and InVec1.
6103     if (InVec0.getOpcode() == ISD::UNDEF) {
6104       InVec0 = Op0.getOperand(0);
6105       if (InVec0.getSimpleValueType() != VT)
6106         return SDValue();
6107     }
6108     if (InVec1.getOpcode() == ISD::UNDEF) {
6109       InVec1 = Op1.getOperand(0);
6110       if (InVec1.getSimpleValueType() != VT)
6111         return SDValue();
6112     }
6113
6114     // Make sure that operands in input to each add/sub node always
6115     // come from a same pair of vectors.
6116     if (InVec0 != Op0.getOperand(0)) {
6117       if (ExpectedOpcode == ISD::FSUB)
6118         return SDValue();
6119
6120       // FADD is commutable. Try to commute the operands
6121       // and then test again.
6122       std::swap(Op0, Op1);
6123       if (InVec0 != Op0.getOperand(0))
6124         return SDValue();
6125     }
6126
6127     if (InVec1 != Op1.getOperand(0))
6128       return SDValue();
6129
6130     // Update the pair of expected opcodes.
6131     std::swap(ExpectedOpcode, NextExpectedOpcode);
6132   }
6133
6134   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6135   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6136       InVec1.getOpcode() != ISD::UNDEF)
6137     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6138
6139   return SDValue();
6140 }
6141
6142 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6143 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6144                                    const X86Subtarget *Subtarget,
6145                                    SelectionDAG &DAG) {
6146   MVT VT = BV->getSimpleValueType(0);
6147   unsigned NumElts = VT.getVectorNumElements();
6148   unsigned NumUndefsLO = 0;
6149   unsigned NumUndefsHI = 0;
6150   unsigned Half = NumElts/2;
6151
6152   // Count the number of UNDEF operands in the build_vector in input.
6153   for (unsigned i = 0, e = Half; i != e; ++i)
6154     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6155       NumUndefsLO++;
6156
6157   for (unsigned i = Half, e = NumElts; i != e; ++i)
6158     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6159       NumUndefsHI++;
6160
6161   // Early exit if this is either a build_vector of all UNDEFs or all the
6162   // operands but one are UNDEF.
6163   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6164     return SDValue();
6165
6166   SDLoc DL(BV);
6167   SDValue InVec0, InVec1;
6168   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6169     // Try to match an SSE3 float HADD/HSUB.
6170     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6171       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6172
6173     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6174       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6175   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6176     // Try to match an SSSE3 integer HADD/HSUB.
6177     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6178       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6179
6180     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6181       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6182   }
6183
6184   if (!Subtarget->hasAVX())
6185     return SDValue();
6186
6187   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6188     // Try to match an AVX horizontal add/sub of packed single/double
6189     // precision floating point values from 256-bit vectors.
6190     SDValue InVec2, InVec3;
6191     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6192         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6193         ((InVec0.getOpcode() == ISD::UNDEF ||
6194           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6195         ((InVec1.getOpcode() == ISD::UNDEF ||
6196           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6197       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6198
6199     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6200         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6201         ((InVec0.getOpcode() == ISD::UNDEF ||
6202           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6203         ((InVec1.getOpcode() == ISD::UNDEF ||
6204           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6205       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6206   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6207     // Try to match an AVX2 horizontal add/sub of signed integers.
6208     SDValue InVec2, InVec3;
6209     unsigned X86Opcode;
6210     bool CanFold = true;
6211
6212     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6213         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6214         ((InVec0.getOpcode() == ISD::UNDEF ||
6215           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6216         ((InVec1.getOpcode() == ISD::UNDEF ||
6217           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6218       X86Opcode = X86ISD::HADD;
6219     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6220         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6221         ((InVec0.getOpcode() == ISD::UNDEF ||
6222           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6223         ((InVec1.getOpcode() == ISD::UNDEF ||
6224           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6225       X86Opcode = X86ISD::HSUB;
6226     else
6227       CanFold = false;
6228
6229     if (CanFold) {
6230       // Fold this build_vector into a single horizontal add/sub.
6231       // Do this only if the target has AVX2.
6232       if (Subtarget->hasAVX2())
6233         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6234
6235       // Do not try to expand this build_vector into a pair of horizontal
6236       // add/sub if we can emit a pair of scalar add/sub.
6237       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6238         return SDValue();
6239
6240       // Convert this build_vector into a pair of horizontal binop followed by
6241       // a concat vector.
6242       bool isUndefLO = NumUndefsLO == Half;
6243       bool isUndefHI = NumUndefsHI == Half;
6244       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6245                                    isUndefLO, isUndefHI);
6246     }
6247   }
6248
6249   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6250        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6251     unsigned X86Opcode;
6252     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6253       X86Opcode = X86ISD::HADD;
6254     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6255       X86Opcode = X86ISD::HSUB;
6256     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6257       X86Opcode = X86ISD::FHADD;
6258     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6259       X86Opcode = X86ISD::FHSUB;
6260     else
6261       return SDValue();
6262
6263     // Don't try to expand this build_vector into a pair of horizontal add/sub
6264     // if we can simply emit a pair of scalar add/sub.
6265     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6266       return SDValue();
6267
6268     // Convert this build_vector into two horizontal add/sub followed by
6269     // a concat vector.
6270     bool isUndefLO = NumUndefsLO == Half;
6271     bool isUndefHI = NumUndefsHI == Half;
6272     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6273                                  isUndefLO, isUndefHI);
6274   }
6275
6276   return SDValue();
6277 }
6278
6279 SDValue
6280 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6281   SDLoc dl(Op);
6282
6283   MVT VT = Op.getSimpleValueType();
6284   MVT ExtVT = VT.getVectorElementType();
6285   unsigned NumElems = Op.getNumOperands();
6286
6287   // Generate vectors for predicate vectors.
6288   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6289     return LowerBUILD_VECTORvXi1(Op, DAG);
6290
6291   // Vectors containing all zeros can be matched by pxor and xorps later
6292   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6293     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6294     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6295     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6296       return Op;
6297
6298     return getZeroVector(VT, Subtarget, DAG, dl);
6299   }
6300
6301   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6302   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6303   // vpcmpeqd on 256-bit vectors.
6304   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6305     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6306       return Op;
6307
6308     if (!VT.is512BitVector())
6309       return getOnesVector(VT, Subtarget, DAG, dl);
6310   }
6311
6312   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6313   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6314     return AddSub;
6315   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6316     return HorizontalOp;
6317   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6318     return Broadcast;
6319
6320   unsigned EVTBits = ExtVT.getSizeInBits();
6321
6322   unsigned NumZero  = 0;
6323   unsigned NumNonZero = 0;
6324   uint64_t NonZeros = 0;
6325   bool IsAllConstants = true;
6326   SmallSet<SDValue, 8> Values;
6327   for (unsigned i = 0; i < NumElems; ++i) {
6328     SDValue Elt = Op.getOperand(i);
6329     if (Elt.getOpcode() == ISD::UNDEF)
6330       continue;
6331     Values.insert(Elt);
6332     if (Elt.getOpcode() != ISD::Constant &&
6333         Elt.getOpcode() != ISD::ConstantFP)
6334       IsAllConstants = false;
6335     if (X86::isZeroNode(Elt))
6336       NumZero++;
6337     else {
6338       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6339       NonZeros |= ((uint64_t)1 << i);
6340       NumNonZero++;
6341     }
6342   }
6343
6344   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6345   if (NumNonZero == 0)
6346     return DAG.getUNDEF(VT);
6347
6348   // Special case for single non-zero, non-undef, element.
6349   if (NumNonZero == 1) {
6350     unsigned Idx = countTrailingZeros(NonZeros);
6351     SDValue Item = Op.getOperand(Idx);
6352
6353     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6354     // the value are obviously zero, truncate the value to i32 and do the
6355     // insertion that way.  Only do this if the value is non-constant or if the
6356     // value is a constant being inserted into element 0.  It is cheaper to do
6357     // a constant pool load than it is to do a movd + shuffle.
6358     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6359         (!IsAllConstants || Idx == 0)) {
6360       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6361         // Handle SSE only.
6362         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6363         MVT VecVT = MVT::v4i32;
6364
6365         // Truncate the value (which may itself be a constant) to i32, and
6366         // convert it to a vector with movd (S2V+shuffle to zero extend).
6367         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6368         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6369         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6370                                       Item, Idx * 2, true, Subtarget, DAG));
6371       }
6372     }
6373
6374     // If we have a constant or non-constant insertion into the low element of
6375     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6376     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6377     // depending on what the source datatype is.
6378     if (Idx == 0) {
6379       if (NumZero == 0)
6380         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6381
6382       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6383           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6384         if (VT.is512BitVector()) {
6385           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6386           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6387                              Item, DAG.getIntPtrConstant(0, dl));
6388         }
6389         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6390                "Expected an SSE value type!");
6391         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6392         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6393         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6394       }
6395
6396       // We can't directly insert an i8 or i16 into a vector, so zero extend
6397       // it to i32 first.
6398       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6399         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6400         if (VT.is256BitVector()) {
6401           if (Subtarget->hasAVX()) {
6402             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6403             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6404           } else {
6405             // Without AVX, we need to extend to a 128-bit vector and then
6406             // insert into the 256-bit vector.
6407             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6408             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6409             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6410           }
6411         } else {
6412           assert(VT.is128BitVector() && "Expected an SSE value type!");
6413           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6414           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6415         }
6416         return DAG.getBitcast(VT, Item);
6417       }
6418     }
6419
6420     // Is it a vector logical left shift?
6421     if (NumElems == 2 && Idx == 1 &&
6422         X86::isZeroNode(Op.getOperand(0)) &&
6423         !X86::isZeroNode(Op.getOperand(1))) {
6424       unsigned NumBits = VT.getSizeInBits();
6425       return getVShift(true, VT,
6426                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6427                                    VT, Op.getOperand(1)),
6428                        NumBits/2, DAG, *this, dl);
6429     }
6430
6431     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6432       return SDValue();
6433
6434     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6435     // is a non-constant being inserted into an element other than the low one,
6436     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6437     // movd/movss) to move this into the low element, then shuffle it into
6438     // place.
6439     if (EVTBits == 32) {
6440       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6441       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6442     }
6443   }
6444
6445   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6446   if (Values.size() == 1) {
6447     if (EVTBits == 32) {
6448       // Instead of a shuffle like this:
6449       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6450       // Check if it's possible to issue this instead.
6451       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6452       unsigned Idx = countTrailingZeros(NonZeros);
6453       SDValue Item = Op.getOperand(Idx);
6454       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6455         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6456     }
6457     return SDValue();
6458   }
6459
6460   // A vector full of immediates; various special cases are already
6461   // handled, so this is best done with a single constant-pool load.
6462   if (IsAllConstants)
6463     return SDValue();
6464
6465   // For AVX-length vectors, see if we can use a vector load to get all of the
6466   // elements, otherwise build the individual 128-bit pieces and use
6467   // shuffles to put them in place.
6468   if (VT.is256BitVector() || VT.is512BitVector()) {
6469     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6470
6471     // Check for a build vector of consecutive loads.
6472     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6473       return LD;
6474
6475     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6476
6477     // Build both the lower and upper subvector.
6478     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6479                                 makeArrayRef(&V[0], NumElems/2));
6480     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6481                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6482
6483     // Recreate the wider vector with the lower and upper part.
6484     if (VT.is256BitVector())
6485       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6486     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6487   }
6488
6489   // Let legalizer expand 2-wide build_vectors.
6490   if (EVTBits == 64) {
6491     if (NumNonZero == 1) {
6492       // One half is zero or undef.
6493       unsigned Idx = countTrailingZeros(NonZeros);
6494       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6495                                Op.getOperand(Idx));
6496       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6497     }
6498     return SDValue();
6499   }
6500
6501   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6502   if (EVTBits == 8 && NumElems == 16)
6503     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6504                                           DAG, Subtarget, *this))
6505       return V;
6506
6507   if (EVTBits == 16 && NumElems == 8)
6508     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6509                                           DAG, Subtarget, *this))
6510       return V;
6511
6512   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6513   if (EVTBits == 32 && NumElems == 4)
6514     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6515       return V;
6516
6517   // If element VT is == 32 bits, turn it into a number of shuffles.
6518   SmallVector<SDValue, 8> V(NumElems);
6519   if (NumElems == 4 && NumZero > 0) {
6520     for (unsigned i = 0; i < 4; ++i) {
6521       bool isZero = !(NonZeros & (1ULL << i));
6522       if (isZero)
6523         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6524       else
6525         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6526     }
6527
6528     for (unsigned i = 0; i < 2; ++i) {
6529       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6530         default: break;
6531         case 0:
6532           V[i] = V[i*2];  // Must be a zero vector.
6533           break;
6534         case 1:
6535           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6536           break;
6537         case 2:
6538           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6539           break;
6540         case 3:
6541           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6542           break;
6543       }
6544     }
6545
6546     bool Reverse1 = (NonZeros & 0x3) == 2;
6547     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6548     int MaskVec[] = {
6549       Reverse1 ? 1 : 0,
6550       Reverse1 ? 0 : 1,
6551       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6552       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6553     };
6554     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6555   }
6556
6557   if (Values.size() > 1 && VT.is128BitVector()) {
6558     // Check for a build vector of consecutive loads.
6559     for (unsigned i = 0; i < NumElems; ++i)
6560       V[i] = Op.getOperand(i);
6561
6562     // Check for elements which are consecutive loads.
6563     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6564       return LD;
6565
6566     // Check for a build vector from mostly shuffle plus few inserting.
6567     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6568       return Sh;
6569
6570     // For SSE 4.1, use insertps to put the high elements into the low element.
6571     if (Subtarget->hasSSE41()) {
6572       SDValue Result;
6573       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6574         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6575       else
6576         Result = DAG.getUNDEF(VT);
6577
6578       for (unsigned i = 1; i < NumElems; ++i) {
6579         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6580         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6581                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6582       }
6583       return Result;
6584     }
6585
6586     // Otherwise, expand into a number of unpckl*, start by extending each of
6587     // our (non-undef) elements to the full vector width with the element in the
6588     // bottom slot of the vector (which generates no code for SSE).
6589     for (unsigned i = 0; i < NumElems; ++i) {
6590       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6591         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6592       else
6593         V[i] = DAG.getUNDEF(VT);
6594     }
6595
6596     // Next, we iteratively mix elements, e.g. for v4f32:
6597     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6598     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6599     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6600     unsigned EltStride = NumElems >> 1;
6601     while (EltStride != 0) {
6602       for (unsigned i = 0; i < EltStride; ++i) {
6603         // If V[i+EltStride] is undef and this is the first round of mixing,
6604         // then it is safe to just drop this shuffle: V[i] is already in the
6605         // right place, the one element (since it's the first round) being
6606         // inserted as undef can be dropped.  This isn't safe for successive
6607         // rounds because they will permute elements within both vectors.
6608         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6609             EltStride == NumElems/2)
6610           continue;
6611
6612         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6613       }
6614       EltStride >>= 1;
6615     }
6616     return V[0];
6617   }
6618   return SDValue();
6619 }
6620
6621 // 256-bit AVX can use the vinsertf128 instruction
6622 // to create 256-bit vectors from two other 128-bit ones.
6623 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6624   SDLoc dl(Op);
6625   MVT ResVT = Op.getSimpleValueType();
6626
6627   assert((ResVT.is256BitVector() ||
6628           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6629
6630   SDValue V1 = Op.getOperand(0);
6631   SDValue V2 = Op.getOperand(1);
6632   unsigned NumElems = ResVT.getVectorNumElements();
6633   if (ResVT.is256BitVector())
6634     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6635
6636   if (Op.getNumOperands() == 4) {
6637     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6638                                   ResVT.getVectorNumElements()/2);
6639     SDValue V3 = Op.getOperand(2);
6640     SDValue V4 = Op.getOperand(3);
6641     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6642       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6643   }
6644   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6645 }
6646
6647 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6648                                        const X86Subtarget *Subtarget,
6649                                        SelectionDAG & DAG) {
6650   SDLoc dl(Op);
6651   MVT ResVT = Op.getSimpleValueType();
6652   unsigned NumOfOperands = Op.getNumOperands();
6653
6654   assert(isPowerOf2_32(NumOfOperands) &&
6655          "Unexpected number of operands in CONCAT_VECTORS");
6656
6657   SDValue Undef = DAG.getUNDEF(ResVT);
6658   if (NumOfOperands > 2) {
6659     // Specialize the cases when all, or all but one, of the operands are undef.
6660     unsigned NumOfDefinedOps = 0;
6661     unsigned OpIdx = 0;
6662     for (unsigned i = 0; i < NumOfOperands; i++)
6663       if (!Op.getOperand(i).isUndef()) {
6664         NumOfDefinedOps++;
6665         OpIdx = i;
6666       }
6667     if (NumOfDefinedOps == 0)
6668       return Undef;
6669     if (NumOfDefinedOps == 1) {
6670       unsigned SubVecNumElts =
6671         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6672       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6673       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6674                          Op.getOperand(OpIdx), IdxVal);
6675     }
6676
6677     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6678                                   ResVT.getVectorNumElements()/2);
6679     SmallVector<SDValue, 2> Ops;
6680     for (unsigned i = 0; i < NumOfOperands/2; i++)
6681       Ops.push_back(Op.getOperand(i));
6682     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6683     Ops.clear();
6684     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6685       Ops.push_back(Op.getOperand(i));
6686     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6687     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6688   }
6689
6690   // 2 operands
6691   SDValue V1 = Op.getOperand(0);
6692   SDValue V2 = Op.getOperand(1);
6693   unsigned NumElems = ResVT.getVectorNumElements();
6694   assert(V1.getValueType() == V2.getValueType() &&
6695          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6696          "Unexpected operands in CONCAT_VECTORS");
6697
6698   if (ResVT.getSizeInBits() >= 16)
6699     return Op; // The operation is legal with KUNPCK
6700
6701   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6702   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6703   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6704   if (IsZeroV1 && IsZeroV2)
6705     return ZeroVec;
6706
6707   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6708   if (V2.isUndef())
6709     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6710   if (IsZeroV2)
6711     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6712
6713   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6714   if (V1.isUndef())
6715     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6716
6717   if (IsZeroV1)
6718     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6719
6720   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6721   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6722 }
6723
6724 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6725                                    const X86Subtarget *Subtarget,
6726                                    SelectionDAG &DAG) {
6727   MVT VT = Op.getSimpleValueType();
6728   if (VT.getVectorElementType() == MVT::i1)
6729     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6730
6731   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6732          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6733           Op.getNumOperands() == 4)));
6734
6735   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6736   // from two other 128-bit ones.
6737
6738   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6739   return LowerAVXCONCAT_VECTORS(Op, DAG);
6740 }
6741
6742 //===----------------------------------------------------------------------===//
6743 // Vector shuffle lowering
6744 //
6745 // This is an experimental code path for lowering vector shuffles on x86. It is
6746 // designed to handle arbitrary vector shuffles and blends, gracefully
6747 // degrading performance as necessary. It works hard to recognize idiomatic
6748 // shuffles and lower them to optimal instruction patterns without leaving
6749 // a framework that allows reasonably efficient handling of all vector shuffle
6750 // patterns.
6751 //===----------------------------------------------------------------------===//
6752
6753 /// \brief Tiny helper function to identify a no-op mask.
6754 ///
6755 /// This is a somewhat boring predicate function. It checks whether the mask
6756 /// array input, which is assumed to be a single-input shuffle mask of the kind
6757 /// used by the X86 shuffle instructions (not a fully general
6758 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6759 /// in-place shuffle are 'no-op's.
6760 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6761   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6762     if (Mask[i] != -1 && Mask[i] != i)
6763       return false;
6764   return true;
6765 }
6766
6767 /// \brief Helper function to classify a mask as a single-input mask.
6768 ///
6769 /// This isn't a generic single-input test because in the vector shuffle
6770 /// lowering we canonicalize single inputs to be the first input operand. This
6771 /// means we can more quickly test for a single input by only checking whether
6772 /// an input from the second operand exists. We also assume that the size of
6773 /// mask corresponds to the size of the input vectors which isn't true in the
6774 /// fully general case.
6775 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6776   for (int M : Mask)
6777     if (M >= (int)Mask.size())
6778       return false;
6779   return true;
6780 }
6781
6782 /// \brief Test whether there are elements crossing 128-bit lanes in this
6783 /// shuffle mask.
6784 ///
6785 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6786 /// and we routinely test for these.
6787 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6788   int LaneSize = 128 / VT.getScalarSizeInBits();
6789   int Size = Mask.size();
6790   for (int i = 0; i < Size; ++i)
6791     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6792       return true;
6793   return false;
6794 }
6795
6796 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6797 ///
6798 /// This checks a shuffle mask to see if it is performing the same
6799 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6800 /// that it is also not lane-crossing. It may however involve a blend from the
6801 /// same lane of a second vector.
6802 ///
6803 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6804 /// non-trivial to compute in the face of undef lanes. The representation is
6805 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6806 /// entries from both V1 and V2 inputs to the wider mask.
6807 static bool
6808 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6809                                 SmallVectorImpl<int> &RepeatedMask) {
6810   int LaneSize = 128 / VT.getScalarSizeInBits();
6811   RepeatedMask.resize(LaneSize, -1);
6812   int Size = Mask.size();
6813   for (int i = 0; i < Size; ++i) {
6814     if (Mask[i] < 0)
6815       continue;
6816     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6817       // This entry crosses lanes, so there is no way to model this shuffle.
6818       return false;
6819
6820     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6821     if (RepeatedMask[i % LaneSize] == -1)
6822       // This is the first non-undef entry in this slot of a 128-bit lane.
6823       RepeatedMask[i % LaneSize] =
6824           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6825     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6826       // Found a mismatch with the repeated mask.
6827       return false;
6828   }
6829   return true;
6830 }
6831
6832 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6833 /// arguments.
6834 ///
6835 /// This is a fast way to test a shuffle mask against a fixed pattern:
6836 ///
6837 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6838 ///
6839 /// It returns true if the mask is exactly as wide as the argument list, and
6840 /// each element of the mask is either -1 (signifying undef) or the value given
6841 /// in the argument.
6842 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6843                                 ArrayRef<int> ExpectedMask) {
6844   if (Mask.size() != ExpectedMask.size())
6845     return false;
6846
6847   int Size = Mask.size();
6848
6849   // If the values are build vectors, we can look through them to find
6850   // equivalent inputs that make the shuffles equivalent.
6851   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6852   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6853
6854   for (int i = 0; i < Size; ++i)
6855     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6856       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6857       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6858       if (!MaskBV || !ExpectedBV ||
6859           MaskBV->getOperand(Mask[i] % Size) !=
6860               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6861         return false;
6862     }
6863
6864   return true;
6865 }
6866
6867 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6868 ///
6869 /// This helper function produces an 8-bit shuffle immediate corresponding to
6870 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6871 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6872 /// example.
6873 ///
6874 /// NB: We rely heavily on "undef" masks preserving the input lane.
6875 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6876                                           SelectionDAG &DAG) {
6877   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6878   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6879   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6880   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6881   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6882
6883   unsigned Imm = 0;
6884   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6885   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6886   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6887   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6888   return DAG.getConstant(Imm, DL, MVT::i8);
6889 }
6890
6891 /// \brief Compute whether each element of a shuffle is zeroable.
6892 ///
6893 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6894 /// Either it is an undef element in the shuffle mask, the element of the input
6895 /// referenced is undef, or the element of the input referenced is known to be
6896 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6897 /// as many lanes with this technique as possible to simplify the remaining
6898 /// shuffle.
6899 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6900                                                      SDValue V1, SDValue V2) {
6901   SmallBitVector Zeroable(Mask.size(), false);
6902
6903   while (V1.getOpcode() == ISD::BITCAST)
6904     V1 = V1->getOperand(0);
6905   while (V2.getOpcode() == ISD::BITCAST)
6906     V2 = V2->getOperand(0);
6907
6908   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6909   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6910
6911   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6912     int M = Mask[i];
6913     // Handle the easy cases.
6914     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6915       Zeroable[i] = true;
6916       continue;
6917     }
6918
6919     // If this is an index into a build_vector node (which has the same number
6920     // of elements), dig out the input value and use it.
6921     SDValue V = M < Size ? V1 : V2;
6922     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6923       continue;
6924
6925     SDValue Input = V.getOperand(M % Size);
6926     // The UNDEF opcode check really should be dead code here, but not quite
6927     // worth asserting on (it isn't invalid, just unexpected).
6928     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6929       Zeroable[i] = true;
6930   }
6931
6932   return Zeroable;
6933 }
6934
6935 // X86 has dedicated unpack instructions that can handle specific blend
6936 // operations: UNPCKH and UNPCKL.
6937 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6938                                            SDValue V1, SDValue V2,
6939                                            SelectionDAG &DAG) {
6940   int NumElts = VT.getVectorNumElements();
6941   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6942   SmallVector<int, 8> Unpckl;
6943   SmallVector<int, 8> Unpckh;
6944
6945   for (int i = 0; i < NumElts; ++i) {
6946     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6947     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6948     int HiPos = LoPos + NumEltsInLane / 2;
6949     Unpckl.push_back(LoPos);
6950     Unpckh.push_back(HiPos);
6951   }
6952
6953   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6954     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6955   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6956     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6957
6958   // Commute and try again.
6959   ShuffleVectorSDNode::commuteMask(Unpckl);
6960   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6961     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6962
6963   ShuffleVectorSDNode::commuteMask(Unpckh);
6964   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6965     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6966
6967   return SDValue();
6968 }
6969
6970 /// \brief Try to emit a bitmask instruction for a shuffle.
6971 ///
6972 /// This handles cases where we can model a blend exactly as a bitmask due to
6973 /// one of the inputs being zeroable.
6974 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6975                                            SDValue V2, ArrayRef<int> Mask,
6976                                            SelectionDAG &DAG) {
6977   MVT EltVT = VT.getVectorElementType();
6978   int NumEltBits = EltVT.getSizeInBits();
6979   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6980   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6981   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6982                                     IntEltVT);
6983   if (EltVT.isFloatingPoint()) {
6984     Zero = DAG.getBitcast(EltVT, Zero);
6985     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6986   }
6987   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6988   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6989   SDValue V;
6990   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6991     if (Zeroable[i])
6992       continue;
6993     if (Mask[i] % Size != i)
6994       return SDValue(); // Not a blend.
6995     if (!V)
6996       V = Mask[i] < Size ? V1 : V2;
6997     else if (V != (Mask[i] < Size ? V1 : V2))
6998       return SDValue(); // Can only let one input through the mask.
6999
7000     VMaskOps[i] = AllOnes;
7001   }
7002   if (!V)
7003     return SDValue(); // No non-zeroable elements!
7004
7005   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7006   V = DAG.getNode(VT.isFloatingPoint()
7007                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7008                   DL, VT, V, VMask);
7009   return V;
7010 }
7011
7012 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7013 ///
7014 /// This is used as a fallback approach when first class blend instructions are
7015 /// unavailable. Currently it is only suitable for integer vectors, but could
7016 /// be generalized for floating point vectors if desirable.
7017 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7018                                             SDValue V2, ArrayRef<int> Mask,
7019                                             SelectionDAG &DAG) {
7020   assert(VT.isInteger() && "Only supports integer vector types!");
7021   MVT EltVT = VT.getVectorElementType();
7022   int NumEltBits = EltVT.getSizeInBits();
7023   SDValue Zero = DAG.getConstant(0, DL, EltVT);
7024   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7025                                     EltVT);
7026   SmallVector<SDValue, 16> MaskOps;
7027   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7028     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7029       return SDValue(); // Shuffled input!
7030     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7031   }
7032
7033   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7034   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7035   // We have to cast V2 around.
7036   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7037   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7038                                       DAG.getBitcast(MaskVT, V1Mask),
7039                                       DAG.getBitcast(MaskVT, V2)));
7040   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7041 }
7042
7043 /// \brief Try to emit a blend instruction for a shuffle.
7044 ///
7045 /// This doesn't do any checks for the availability of instructions for blending
7046 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7047 /// be matched in the backend with the type given. What it does check for is
7048 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7049 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7050                                          SDValue V2, ArrayRef<int> Original,
7051                                          const X86Subtarget *Subtarget,
7052                                          SelectionDAG &DAG) {
7053   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7054   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7055   SmallVector<int, 8> Mask(Original.begin(), Original.end());
7056   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7057   bool ForceV1Zero = false, ForceV2Zero = false;
7058
7059   // Attempt to generate the binary blend mask. If an input is zero then
7060   // we can use any lane.
7061   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7062   unsigned BlendMask = 0;
7063   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7064     int M = Mask[i];
7065     if (M < 0)
7066       continue;
7067     if (M == i)
7068       continue;
7069     if (M == i + Size) {
7070       BlendMask |= 1u << i;
7071       continue;
7072     }
7073     if (Zeroable[i]) {
7074       if (V1IsZero) {
7075         ForceV1Zero = true;
7076         Mask[i] = i;
7077         continue;
7078       }
7079       if (V2IsZero) {
7080         ForceV2Zero = true;
7081         BlendMask |= 1u << i;
7082         Mask[i] = i + Size;
7083         continue;
7084       }
7085     }
7086     return SDValue(); // Shuffled input!
7087   }
7088
7089   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7090   if (ForceV1Zero)
7091     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7092   if (ForceV2Zero)
7093     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7094
7095   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7096     unsigned ScaledMask = 0;
7097     for (int i = 0; i != Size; ++i)
7098       if (BlendMask & (1u << i))
7099         for (int j = 0; j != Scale; ++j)
7100           ScaledMask |= 1u << (i * Scale + j);
7101     return ScaledMask;
7102   };
7103
7104   switch (VT.SimpleTy) {
7105   case MVT::v2f64:
7106   case MVT::v4f32:
7107   case MVT::v4f64:
7108   case MVT::v8f32:
7109     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7110                        DAG.getConstant(BlendMask, DL, MVT::i8));
7111
7112   case MVT::v4i64:
7113   case MVT::v8i32:
7114     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7115     // FALLTHROUGH
7116   case MVT::v2i64:
7117   case MVT::v4i32:
7118     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7119     // that instruction.
7120     if (Subtarget->hasAVX2()) {
7121       // Scale the blend by the number of 32-bit dwords per element.
7122       int Scale =  VT.getScalarSizeInBits() / 32;
7123       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7124       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7125       V1 = DAG.getBitcast(BlendVT, V1);
7126       V2 = DAG.getBitcast(BlendVT, V2);
7127       return DAG.getBitcast(
7128           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7129                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7130     }
7131     // FALLTHROUGH
7132   case MVT::v8i16: {
7133     // For integer shuffles we need to expand the mask and cast the inputs to
7134     // v8i16s prior to blending.
7135     int Scale = 8 / VT.getVectorNumElements();
7136     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7137     V1 = DAG.getBitcast(MVT::v8i16, V1);
7138     V2 = DAG.getBitcast(MVT::v8i16, V2);
7139     return DAG.getBitcast(VT,
7140                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7141                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7142   }
7143
7144   case MVT::v16i16: {
7145     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7146     SmallVector<int, 8> RepeatedMask;
7147     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7148       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7149       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7150       BlendMask = 0;
7151       for (int i = 0; i < 8; ++i)
7152         if (RepeatedMask[i] >= 16)
7153           BlendMask |= 1u << i;
7154       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7155                          DAG.getConstant(BlendMask, DL, MVT::i8));
7156     }
7157   }
7158     // FALLTHROUGH
7159   case MVT::v16i8:
7160   case MVT::v32i8: {
7161     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7162            "256-bit byte-blends require AVX2 support!");
7163
7164     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7165     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7166       return Masked;
7167
7168     // Scale the blend by the number of bytes per element.
7169     int Scale = VT.getScalarSizeInBits() / 8;
7170
7171     // This form of blend is always done on bytes. Compute the byte vector
7172     // type.
7173     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7174
7175     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7176     // mix of LLVM's code generator and the x86 backend. We tell the code
7177     // generator that boolean values in the elements of an x86 vector register
7178     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7179     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7180     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7181     // of the element (the remaining are ignored) and 0 in that high bit would
7182     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7183     // the LLVM model for boolean values in vector elements gets the relevant
7184     // bit set, it is set backwards and over constrained relative to x86's
7185     // actual model.
7186     SmallVector<SDValue, 32> VSELECTMask;
7187     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7188       for (int j = 0; j < Scale; ++j)
7189         VSELECTMask.push_back(
7190             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7191                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7192                                           MVT::i8));
7193
7194     V1 = DAG.getBitcast(BlendVT, V1);
7195     V2 = DAG.getBitcast(BlendVT, V2);
7196     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7197                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7198                                                       BlendVT, VSELECTMask),
7199                                           V1, V2));
7200   }
7201
7202   default:
7203     llvm_unreachable("Not a supported integer vector type!");
7204   }
7205 }
7206
7207 /// \brief Try to lower as a blend of elements from two inputs followed by
7208 /// a single-input permutation.
7209 ///
7210 /// This matches the pattern where we can blend elements from two inputs and
7211 /// then reduce the shuffle to a single-input permutation.
7212 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7213                                                    SDValue V2,
7214                                                    ArrayRef<int> Mask,
7215                                                    SelectionDAG &DAG) {
7216   // We build up the blend mask while checking whether a blend is a viable way
7217   // to reduce the shuffle.
7218   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7219   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7220
7221   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7222     if (Mask[i] < 0)
7223       continue;
7224
7225     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7226
7227     if (BlendMask[Mask[i] % Size] == -1)
7228       BlendMask[Mask[i] % Size] = Mask[i];
7229     else if (BlendMask[Mask[i] % Size] != Mask[i])
7230       return SDValue(); // Can't blend in the needed input!
7231
7232     PermuteMask[i] = Mask[i] % Size;
7233   }
7234
7235   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7236   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7237 }
7238
7239 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7240 /// blends and permutes.
7241 ///
7242 /// This matches the extremely common pattern for handling combined
7243 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7244 /// operations. It will try to pick the best arrangement of shuffles and
7245 /// blends.
7246 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7247                                                           SDValue V1,
7248                                                           SDValue V2,
7249                                                           ArrayRef<int> Mask,
7250                                                           SelectionDAG &DAG) {
7251   // Shuffle the input elements into the desired positions in V1 and V2 and
7252   // blend them together.
7253   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7254   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7255   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7256   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7257     if (Mask[i] >= 0 && Mask[i] < Size) {
7258       V1Mask[i] = Mask[i];
7259       BlendMask[i] = i;
7260     } else if (Mask[i] >= Size) {
7261       V2Mask[i] = Mask[i] - Size;
7262       BlendMask[i] = i + Size;
7263     }
7264
7265   // Try to lower with the simpler initial blend strategy unless one of the
7266   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7267   // shuffle may be able to fold with a load or other benefit. However, when
7268   // we'll have to do 2x as many shuffles in order to achieve this, blending
7269   // first is a better strategy.
7270   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7271     if (SDValue BlendPerm =
7272             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7273       return BlendPerm;
7274
7275   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7276   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7277   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7278 }
7279
7280 /// \brief Try to lower a vector shuffle as a byte rotation.
7281 ///
7282 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7283 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7284 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7285 /// try to generically lower a vector shuffle through such an pattern. It
7286 /// does not check for the profitability of lowering either as PALIGNR or
7287 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7288 /// This matches shuffle vectors that look like:
7289 ///
7290 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7291 ///
7292 /// Essentially it concatenates V1 and V2, shifts right by some number of
7293 /// elements, and takes the low elements as the result. Note that while this is
7294 /// specified as a *right shift* because x86 is little-endian, it is a *left
7295 /// rotate* of the vector lanes.
7296 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7297                                               SDValue V2,
7298                                               ArrayRef<int> Mask,
7299                                               const X86Subtarget *Subtarget,
7300                                               SelectionDAG &DAG) {
7301   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7302
7303   int NumElts = Mask.size();
7304   int NumLanes = VT.getSizeInBits() / 128;
7305   int NumLaneElts = NumElts / NumLanes;
7306
7307   // We need to detect various ways of spelling a rotation:
7308   //   [11, 12, 13, 14, 15,  0,  1,  2]
7309   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7310   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7311   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7312   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7313   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7314   int Rotation = 0;
7315   SDValue Lo, Hi;
7316   for (int l = 0; l < NumElts; l += NumLaneElts) {
7317     for (int i = 0; i < NumLaneElts; ++i) {
7318       if (Mask[l + i] == -1)
7319         continue;
7320       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7321
7322       // Get the mod-Size index and lane correct it.
7323       int LaneIdx = (Mask[l + i] % NumElts) - l;
7324       // Make sure it was in this lane.
7325       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7326         return SDValue();
7327
7328       // Determine where a rotated vector would have started.
7329       int StartIdx = i - LaneIdx;
7330       if (StartIdx == 0)
7331         // The identity rotation isn't interesting, stop.
7332         return SDValue();
7333
7334       // If we found the tail of a vector the rotation must be the missing
7335       // front. If we found the head of a vector, it must be how much of the
7336       // head.
7337       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7338
7339       if (Rotation == 0)
7340         Rotation = CandidateRotation;
7341       else if (Rotation != CandidateRotation)
7342         // The rotations don't match, so we can't match this mask.
7343         return SDValue();
7344
7345       // Compute which value this mask is pointing at.
7346       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7347
7348       // Compute which of the two target values this index should be assigned
7349       // to. This reflects whether the high elements are remaining or the low
7350       // elements are remaining.
7351       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7352
7353       // Either set up this value if we've not encountered it before, or check
7354       // that it remains consistent.
7355       if (!TargetV)
7356         TargetV = MaskV;
7357       else if (TargetV != MaskV)
7358         // This may be a rotation, but it pulls from the inputs in some
7359         // unsupported interleaving.
7360         return SDValue();
7361     }
7362   }
7363
7364   // Check that we successfully analyzed the mask, and normalize the results.
7365   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7366   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7367   if (!Lo)
7368     Lo = Hi;
7369   else if (!Hi)
7370     Hi = Lo;
7371
7372   // The actual rotate instruction rotates bytes, so we need to scale the
7373   // rotation based on how many bytes are in the vector lane.
7374   int Scale = 16 / NumLaneElts;
7375
7376   // SSSE3 targets can use the palignr instruction.
7377   if (Subtarget->hasSSSE3()) {
7378     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7379     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7380     Lo = DAG.getBitcast(AlignVT, Lo);
7381     Hi = DAG.getBitcast(AlignVT, Hi);
7382
7383     return DAG.getBitcast(
7384         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7385                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7386   }
7387
7388   assert(VT.is128BitVector() &&
7389          "Rotate-based lowering only supports 128-bit lowering!");
7390   assert(Mask.size() <= 16 &&
7391          "Can shuffle at most 16 bytes in a 128-bit vector!");
7392
7393   // Default SSE2 implementation
7394   int LoByteShift = 16 - Rotation * Scale;
7395   int HiByteShift = Rotation * Scale;
7396
7397   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7398   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7399   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7400
7401   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7402                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7403   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7404                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7405   return DAG.getBitcast(VT,
7406                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7407 }
7408
7409 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7410 ///
7411 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7412 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7413 /// matches elements from one of the input vectors shuffled to the left or
7414 /// right with zeroable elements 'shifted in'. It handles both the strictly
7415 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7416 /// quad word lane.
7417 ///
7418 /// PSHL : (little-endian) left bit shift.
7419 /// [ zz, 0, zz,  2 ]
7420 /// [ -1, 4, zz, -1 ]
7421 /// PSRL : (little-endian) right bit shift.
7422 /// [  1, zz,  3, zz]
7423 /// [ -1, -1,  7, zz]
7424 /// PSLLDQ : (little-endian) left byte shift
7425 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7426 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7427 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7428 /// PSRLDQ : (little-endian) right byte shift
7429 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7430 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7431 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7432 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7433                                          SDValue V2, ArrayRef<int> Mask,
7434                                          SelectionDAG &DAG) {
7435   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7436
7437   int Size = Mask.size();
7438   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7439
7440   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7441     for (int i = 0; i < Size; i += Scale)
7442       for (int j = 0; j < Shift; ++j)
7443         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7444           return false;
7445
7446     return true;
7447   };
7448
7449   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7450     for (int i = 0; i != Size; i += Scale) {
7451       unsigned Pos = Left ? i + Shift : i;
7452       unsigned Low = Left ? i : i + Shift;
7453       unsigned Len = Scale - Shift;
7454       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7455                                       Low + (V == V1 ? 0 : Size)))
7456         return SDValue();
7457     }
7458
7459     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7460     bool ByteShift = ShiftEltBits > 64;
7461     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7462                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7463     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7464
7465     // Normalize the scale for byte shifts to still produce an i64 element
7466     // type.
7467     Scale = ByteShift ? Scale / 2 : Scale;
7468
7469     // We need to round trip through the appropriate type for the shift.
7470     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7471     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7472     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7473            "Illegal integer vector type");
7474     V = DAG.getBitcast(ShiftVT, V);
7475
7476     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7477                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7478     return DAG.getBitcast(VT, V);
7479   };
7480
7481   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7482   // keep doubling the size of the integer elements up to that. We can
7483   // then shift the elements of the integer vector by whole multiples of
7484   // their width within the elements of the larger integer vector. Test each
7485   // multiple to see if we can find a match with the moved element indices
7486   // and that the shifted in elements are all zeroable.
7487   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7488     for (int Shift = 1; Shift != Scale; ++Shift)
7489       for (bool Left : {true, false})
7490         if (CheckZeros(Shift, Scale, Left))
7491           for (SDValue V : {V1, V2})
7492             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7493               return Match;
7494
7495   // no match
7496   return SDValue();
7497 }
7498
7499 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7500 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7501                                            SDValue V2, ArrayRef<int> Mask,
7502                                            SelectionDAG &DAG) {
7503   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7504   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7505
7506   int Size = Mask.size();
7507   int HalfSize = Size / 2;
7508   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7509
7510   // Upper half must be undefined.
7511   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7512     return SDValue();
7513
7514   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7515   // Remainder of lower half result is zero and upper half is all undef.
7516   auto LowerAsEXTRQ = [&]() {
7517     // Determine the extraction length from the part of the
7518     // lower half that isn't zeroable.
7519     int Len = HalfSize;
7520     for (; Len > 0; --Len)
7521       if (!Zeroable[Len - 1])
7522         break;
7523     assert(Len > 0 && "Zeroable shuffle mask");
7524
7525     // Attempt to match first Len sequential elements from the lower half.
7526     SDValue Src;
7527     int Idx = -1;
7528     for (int i = 0; i != Len; ++i) {
7529       int M = Mask[i];
7530       if (M < 0)
7531         continue;
7532       SDValue &V = (M < Size ? V1 : V2);
7533       M = M % Size;
7534
7535       // The extracted elements must start at a valid index and all mask
7536       // elements must be in the lower half.
7537       if (i > M || M >= HalfSize)
7538         return SDValue();
7539
7540       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7541         Src = V;
7542         Idx = M - i;
7543         continue;
7544       }
7545       return SDValue();
7546     }
7547
7548     if (Idx < 0)
7549       return SDValue();
7550
7551     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7552     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7553     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7554     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7555                        DAG.getConstant(BitLen, DL, MVT::i8),
7556                        DAG.getConstant(BitIdx, DL, MVT::i8));
7557   };
7558
7559   if (SDValue ExtrQ = LowerAsEXTRQ())
7560     return ExtrQ;
7561
7562   // INSERTQ: Extract lowest Len elements from lower half of second source and
7563   // insert over first source, starting at Idx.
7564   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7565   auto LowerAsInsertQ = [&]() {
7566     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7567       SDValue Base;
7568
7569       // Attempt to match first source from mask before insertion point.
7570       if (isUndefInRange(Mask, 0, Idx)) {
7571         /* EMPTY */
7572       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7573         Base = V1;
7574       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7575         Base = V2;
7576       } else {
7577         continue;
7578       }
7579
7580       // Extend the extraction length looking to match both the insertion of
7581       // the second source and the remaining elements of the first.
7582       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7583         SDValue Insert;
7584         int Len = Hi - Idx;
7585
7586         // Match insertion.
7587         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7588           Insert = V1;
7589         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7590           Insert = V2;
7591         } else {
7592           continue;
7593         }
7594
7595         // Match the remaining elements of the lower half.
7596         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7597           /* EMPTY */
7598         } else if ((!Base || (Base == V1)) &&
7599                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7600           Base = V1;
7601         } else if ((!Base || (Base == V2)) &&
7602                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7603                                               Size + Hi)) {
7604           Base = V2;
7605         } else {
7606           continue;
7607         }
7608
7609         // We may not have a base (first source) - this can safely be undefined.
7610         if (!Base)
7611           Base = DAG.getUNDEF(VT);
7612
7613         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7614         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7615         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7616                            DAG.getConstant(BitLen, DL, MVT::i8),
7617                            DAG.getConstant(BitIdx, DL, MVT::i8));
7618       }
7619     }
7620
7621     return SDValue();
7622   };
7623
7624   if (SDValue InsertQ = LowerAsInsertQ())
7625     return InsertQ;
7626
7627   return SDValue();
7628 }
7629
7630 /// \brief Lower a vector shuffle as a zero or any extension.
7631 ///
7632 /// Given a specific number of elements, element bit width, and extension
7633 /// stride, produce either a zero or any extension based on the available
7634 /// features of the subtarget. The extended elements are consecutive and
7635 /// begin and can start from an offseted element index in the input; to
7636 /// avoid excess shuffling the offset must either being in the bottom lane
7637 /// or at the start of a higher lane. All extended elements must be from
7638 /// the same lane.
7639 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7640     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7641     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7642   assert(Scale > 1 && "Need a scale to extend.");
7643   int EltBits = VT.getScalarSizeInBits();
7644   int NumElements = VT.getVectorNumElements();
7645   int NumEltsPerLane = 128 / EltBits;
7646   int OffsetLane = Offset / NumEltsPerLane;
7647   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7648          "Only 8, 16, and 32 bit elements can be extended.");
7649   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7650   assert(0 <= Offset && "Extension offset must be positive.");
7651   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7652          "Extension offset must be in the first lane or start an upper lane.");
7653
7654   // Check that an index is in same lane as the base offset.
7655   auto SafeOffset = [&](int Idx) {
7656     return OffsetLane == (Idx / NumEltsPerLane);
7657   };
7658
7659   // Shift along an input so that the offset base moves to the first element.
7660   auto ShuffleOffset = [&](SDValue V) {
7661     if (!Offset)
7662       return V;
7663
7664     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7665     for (int i = 0; i * Scale < NumElements; ++i) {
7666       int SrcIdx = i + Offset;
7667       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7668     }
7669     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7670   };
7671
7672   // Found a valid zext mask! Try various lowering strategies based on the
7673   // input type and available ISA extensions.
7674   if (Subtarget->hasSSE41()) {
7675     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7676     // PUNPCK will catch this in a later shuffle match.
7677     if (Offset && Scale == 2 && VT.is128BitVector())
7678       return SDValue();
7679     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7680                                  NumElements / Scale);
7681     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7682     return DAG.getBitcast(VT, InputV);
7683   }
7684
7685   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7686
7687   // For any extends we can cheat for larger element sizes and use shuffle
7688   // instructions that can fold with a load and/or copy.
7689   if (AnyExt && EltBits == 32) {
7690     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7691                          -1};
7692     return DAG.getBitcast(
7693         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7694                         DAG.getBitcast(MVT::v4i32, InputV),
7695                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7696   }
7697   if (AnyExt && EltBits == 16 && Scale > 2) {
7698     int PSHUFDMask[4] = {Offset / 2, -1,
7699                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7700     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7701                          DAG.getBitcast(MVT::v4i32, InputV),
7702                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7703     int PSHUFWMask[4] = {1, -1, -1, -1};
7704     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7705     return DAG.getBitcast(
7706         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7707                         DAG.getBitcast(MVT::v8i16, InputV),
7708                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7709   }
7710
7711   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7712   // to 64-bits.
7713   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7714     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7715     assert(VT.is128BitVector() && "Unexpected vector width!");
7716
7717     int LoIdx = Offset * EltBits;
7718     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7719                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7720                                          DAG.getConstant(EltBits, DL, MVT::i8),
7721                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7722
7723     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7724         !SafeOffset(Offset + 1))
7725       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7726
7727     int HiIdx = (Offset + 1) * EltBits;
7728     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7729                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7730                                          DAG.getConstant(EltBits, DL, MVT::i8),
7731                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7732     return DAG.getNode(ISD::BITCAST, DL, VT,
7733                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7734   }
7735
7736   // If this would require more than 2 unpack instructions to expand, use
7737   // pshufb when available. We can only use more than 2 unpack instructions
7738   // when zero extending i8 elements which also makes it easier to use pshufb.
7739   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7740     assert(NumElements == 16 && "Unexpected byte vector width!");
7741     SDValue PSHUFBMask[16];
7742     for (int i = 0; i < 16; ++i) {
7743       int Idx = Offset + (i / Scale);
7744       PSHUFBMask[i] = DAG.getConstant(
7745           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7746     }
7747     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7748     return DAG.getBitcast(VT,
7749                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7750                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7751                                                   MVT::v16i8, PSHUFBMask)));
7752   }
7753
7754   // If we are extending from an offset, ensure we start on a boundary that
7755   // we can unpack from.
7756   int AlignToUnpack = Offset % (NumElements / Scale);
7757   if (AlignToUnpack) {
7758     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7759     for (int i = AlignToUnpack; i < NumElements; ++i)
7760       ShMask[i - AlignToUnpack] = i;
7761     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7762     Offset -= AlignToUnpack;
7763   }
7764
7765   // Otherwise emit a sequence of unpacks.
7766   do {
7767     unsigned UnpackLoHi = X86ISD::UNPCKL;
7768     if (Offset >= (NumElements / 2)) {
7769       UnpackLoHi = X86ISD::UNPCKH;
7770       Offset -= (NumElements / 2);
7771     }
7772
7773     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7774     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7775                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7776     InputV = DAG.getBitcast(InputVT, InputV);
7777     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7778     Scale /= 2;
7779     EltBits *= 2;
7780     NumElements /= 2;
7781   } while (Scale > 1);
7782   return DAG.getBitcast(VT, InputV);
7783 }
7784
7785 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7786 ///
7787 /// This routine will try to do everything in its power to cleverly lower
7788 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7789 /// check for the profitability of this lowering,  it tries to aggressively
7790 /// match this pattern. It will use all of the micro-architectural details it
7791 /// can to emit an efficient lowering. It handles both blends with all-zero
7792 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7793 /// masking out later).
7794 ///
7795 /// The reason we have dedicated lowering for zext-style shuffles is that they
7796 /// are both incredibly common and often quite performance sensitive.
7797 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7798     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7799     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7800   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7801
7802   int Bits = VT.getSizeInBits();
7803   int NumLanes = Bits / 128;
7804   int NumElements = VT.getVectorNumElements();
7805   int NumEltsPerLane = NumElements / NumLanes;
7806   assert(VT.getScalarSizeInBits() <= 32 &&
7807          "Exceeds 32-bit integer zero extension limit");
7808   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7809
7810   // Define a helper function to check a particular ext-scale and lower to it if
7811   // valid.
7812   auto Lower = [&](int Scale) -> SDValue {
7813     SDValue InputV;
7814     bool AnyExt = true;
7815     int Offset = 0;
7816     int Matches = 0;
7817     for (int i = 0; i < NumElements; ++i) {
7818       int M = Mask[i];
7819       if (M == -1)
7820         continue; // Valid anywhere but doesn't tell us anything.
7821       if (i % Scale != 0) {
7822         // Each of the extended elements need to be zeroable.
7823         if (!Zeroable[i])
7824           return SDValue();
7825
7826         // We no longer are in the anyext case.
7827         AnyExt = false;
7828         continue;
7829       }
7830
7831       // Each of the base elements needs to be consecutive indices into the
7832       // same input vector.
7833       SDValue V = M < NumElements ? V1 : V2;
7834       M = M % NumElements;
7835       if (!InputV) {
7836         InputV = V;
7837         Offset = M - (i / Scale);
7838       } else if (InputV != V)
7839         return SDValue(); // Flip-flopping inputs.
7840
7841       // Offset must start in the lowest 128-bit lane or at the start of an
7842       // upper lane.
7843       // FIXME: Is it ever worth allowing a negative base offset?
7844       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7845             (Offset % NumEltsPerLane) == 0))
7846         return SDValue();
7847
7848       // If we are offsetting, all referenced entries must come from the same
7849       // lane.
7850       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7851         return SDValue();
7852
7853       if ((M % NumElements) != (Offset + (i / Scale)))
7854         return SDValue(); // Non-consecutive strided elements.
7855       Matches++;
7856     }
7857
7858     // If we fail to find an input, we have a zero-shuffle which should always
7859     // have already been handled.
7860     // FIXME: Maybe handle this here in case during blending we end up with one?
7861     if (!InputV)
7862       return SDValue();
7863
7864     // If we are offsetting, don't extend if we only match a single input, we
7865     // can always do better by using a basic PSHUF or PUNPCK.
7866     if (Offset != 0 && Matches < 2)
7867       return SDValue();
7868
7869     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7870         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7871   };
7872
7873   // The widest scale possible for extending is to a 64-bit integer.
7874   assert(Bits % 64 == 0 &&
7875          "The number of bits in a vector must be divisible by 64 on x86!");
7876   int NumExtElements = Bits / 64;
7877
7878   // Each iteration, try extending the elements half as much, but into twice as
7879   // many elements.
7880   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7881     assert(NumElements % NumExtElements == 0 &&
7882            "The input vector size must be divisible by the extended size.");
7883     if (SDValue V = Lower(NumElements / NumExtElements))
7884       return V;
7885   }
7886
7887   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7888   if (Bits != 128)
7889     return SDValue();
7890
7891   // Returns one of the source operands if the shuffle can be reduced to a
7892   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7893   auto CanZExtLowHalf = [&]() {
7894     for (int i = NumElements / 2; i != NumElements; ++i)
7895       if (!Zeroable[i])
7896         return SDValue();
7897     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7898       return V1;
7899     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7900       return V2;
7901     return SDValue();
7902   };
7903
7904   if (SDValue V = CanZExtLowHalf()) {
7905     V = DAG.getBitcast(MVT::v2i64, V);
7906     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7907     return DAG.getBitcast(VT, V);
7908   }
7909
7910   // No viable ext lowering found.
7911   return SDValue();
7912 }
7913
7914 /// \brief Try to get a scalar value for a specific element of a vector.
7915 ///
7916 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7917 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7918                                               SelectionDAG &DAG) {
7919   MVT VT = V.getSimpleValueType();
7920   MVT EltVT = VT.getVectorElementType();
7921   while (V.getOpcode() == ISD::BITCAST)
7922     V = V.getOperand(0);
7923   // If the bitcasts shift the element size, we can't extract an equivalent
7924   // element from it.
7925   MVT NewVT = V.getSimpleValueType();
7926   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7927     return SDValue();
7928
7929   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7930       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7931     // Ensure the scalar operand is the same size as the destination.
7932     // FIXME: Add support for scalar truncation where possible.
7933     SDValue S = V.getOperand(Idx);
7934     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7935       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7936   }
7937
7938   return SDValue();
7939 }
7940
7941 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7942 ///
7943 /// This is particularly important because the set of instructions varies
7944 /// significantly based on whether the operand is a load or not.
7945 static bool isShuffleFoldableLoad(SDValue V) {
7946   while (V.getOpcode() == ISD::BITCAST)
7947     V = V.getOperand(0);
7948
7949   return ISD::isNON_EXTLoad(V.getNode());
7950 }
7951
7952 /// \brief Try to lower insertion of a single element into a zero vector.
7953 ///
7954 /// This is a common pattern that we have especially efficient patterns to lower
7955 /// across all subtarget feature sets.
7956 static SDValue lowerVectorShuffleAsElementInsertion(
7957     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7958     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7959   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7960   MVT ExtVT = VT;
7961   MVT EltVT = VT.getVectorElementType();
7962
7963   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7964                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7965                 Mask.begin();
7966   bool IsV1Zeroable = true;
7967   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7968     if (i != V2Index && !Zeroable[i]) {
7969       IsV1Zeroable = false;
7970       break;
7971     }
7972
7973   // Check for a single input from a SCALAR_TO_VECTOR node.
7974   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7975   // all the smarts here sunk into that routine. However, the current
7976   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7977   // vector shuffle lowering is dead.
7978   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7979                                                DAG);
7980   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7981     // We need to zext the scalar if it is smaller than an i32.
7982     V2S = DAG.getBitcast(EltVT, V2S);
7983     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7984       // Using zext to expand a narrow element won't work for non-zero
7985       // insertions.
7986       if (!IsV1Zeroable)
7987         return SDValue();
7988
7989       // Zero-extend directly to i32.
7990       ExtVT = MVT::v4i32;
7991       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7992     }
7993     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7994   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7995              EltVT == MVT::i16) {
7996     // Either not inserting from the low element of the input or the input
7997     // element size is too small to use VZEXT_MOVL to clear the high bits.
7998     return SDValue();
7999   }
8000
8001   if (!IsV1Zeroable) {
8002     // If V1 can't be treated as a zero vector we have fewer options to lower
8003     // this. We can't support integer vectors or non-zero targets cheaply, and
8004     // the V1 elements can't be permuted in any way.
8005     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8006     if (!VT.isFloatingPoint() || V2Index != 0)
8007       return SDValue();
8008     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8009     V1Mask[V2Index] = -1;
8010     if (!isNoopShuffleMask(V1Mask))
8011       return SDValue();
8012     // This is essentially a special case blend operation, but if we have
8013     // general purpose blend operations, they are always faster. Bail and let
8014     // the rest of the lowering handle these as blends.
8015     if (Subtarget->hasSSE41())
8016       return SDValue();
8017
8018     // Otherwise, use MOVSD or MOVSS.
8019     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8020            "Only two types of floating point element types to handle!");
8021     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8022                        ExtVT, V1, V2);
8023   }
8024
8025   // This lowering only works for the low element with floating point vectors.
8026   if (VT.isFloatingPoint() && V2Index != 0)
8027     return SDValue();
8028
8029   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8030   if (ExtVT != VT)
8031     V2 = DAG.getBitcast(VT, V2);
8032
8033   if (V2Index != 0) {
8034     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8035     // the desired position. Otherwise it is more efficient to do a vector
8036     // shift left. We know that we can do a vector shift left because all
8037     // the inputs are zero.
8038     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8039       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8040       V2Shuffle[V2Index] = 0;
8041       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8042     } else {
8043       V2 = DAG.getBitcast(MVT::v2i64, V2);
8044       V2 = DAG.getNode(
8045           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8046           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8047                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8048                               DAG.getDataLayout(), VT)));
8049       V2 = DAG.getBitcast(VT, V2);
8050     }
8051   }
8052   return V2;
8053 }
8054
8055 /// \brief Try to lower broadcast of a single - truncated - integer element,
8056 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8057 ///
8058 /// This assumes we have AVX2.
8059 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8060                                                   int BroadcastIdx,
8061                                                   const X86Subtarget *Subtarget,
8062                                                   SelectionDAG &DAG) {
8063   assert(Subtarget->hasAVX2() &&
8064          "We can only lower integer broadcasts with AVX2!");
8065
8066   EVT EltVT = VT.getVectorElementType();
8067   EVT V0VT = V0.getValueType();
8068
8069   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8070   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8071
8072   EVT V0EltVT = V0VT.getVectorElementType();
8073   if (!V0EltVT.isInteger())
8074     return SDValue();
8075
8076   const unsigned EltSize = EltVT.getSizeInBits();
8077   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8078
8079   // This is only a truncation if the original element type is larger.
8080   if (V0EltSize <= EltSize)
8081     return SDValue();
8082
8083   assert(((V0EltSize % EltSize) == 0) &&
8084          "Scalar type sizes must all be powers of 2 on x86!");
8085
8086   const unsigned V0Opc = V0.getOpcode();
8087   const unsigned Scale = V0EltSize / EltSize;
8088   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8089
8090   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8091       V0Opc != ISD::BUILD_VECTOR)
8092     return SDValue();
8093
8094   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8095
8096   // If we're extracting non-least-significant bits, shift so we can truncate.
8097   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8098   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8099   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8100   if (const int OffsetIdx = BroadcastIdx % Scale)
8101     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8102             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8103
8104   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8105                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8106 }
8107
8108 /// \brief Try to lower broadcast of a single element.
8109 ///
8110 /// For convenience, this code also bundles all of the subtarget feature set
8111 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8112 /// a convenient way to factor it out.
8113 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8114 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8115                                              ArrayRef<int> Mask,
8116                                              const X86Subtarget *Subtarget,
8117                                              SelectionDAG &DAG) {
8118   if (!Subtarget->hasAVX())
8119     return SDValue();
8120   if (VT.isInteger() && !Subtarget->hasAVX2())
8121     return SDValue();
8122
8123   // Check that the mask is a broadcast.
8124   int BroadcastIdx = -1;
8125   for (int M : Mask)
8126     if (M >= 0 && BroadcastIdx == -1)
8127       BroadcastIdx = M;
8128     else if (M >= 0 && M != BroadcastIdx)
8129       return SDValue();
8130
8131   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8132                                             "a sorted mask where the broadcast "
8133                                             "comes from V1.");
8134
8135   // Go up the chain of (vector) values to find a scalar load that we can
8136   // combine with the broadcast.
8137   for (;;) {
8138     switch (V.getOpcode()) {
8139     case ISD::CONCAT_VECTORS: {
8140       int OperandSize = Mask.size() / V.getNumOperands();
8141       V = V.getOperand(BroadcastIdx / OperandSize);
8142       BroadcastIdx %= OperandSize;
8143       continue;
8144     }
8145
8146     case ISD::INSERT_SUBVECTOR: {
8147       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8148       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8149       if (!ConstantIdx)
8150         break;
8151
8152       int BeginIdx = (int)ConstantIdx->getZExtValue();
8153       int EndIdx =
8154           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8155       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8156         BroadcastIdx -= BeginIdx;
8157         V = VInner;
8158       } else {
8159         V = VOuter;
8160       }
8161       continue;
8162     }
8163     }
8164     break;
8165   }
8166
8167   // Check if this is a broadcast of a scalar. We special case lowering
8168   // for scalars so that we can more effectively fold with loads.
8169   // First, look through bitcast: if the original value has a larger element
8170   // type than the shuffle, the broadcast element is in essence truncated.
8171   // Make that explicit to ease folding.
8172   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8173     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8174             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8175       return TruncBroadcast;
8176
8177   MVT BroadcastVT = VT;
8178
8179   // Peek through any bitcast (only useful for loads).
8180   SDValue BC = V;
8181   while (BC.getOpcode() == ISD::BITCAST)
8182     BC = BC.getOperand(0);
8183
8184   // Also check the simpler case, where we can directly reuse the scalar.
8185   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8186       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8187     V = V.getOperand(BroadcastIdx);
8188
8189     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8190     // Only AVX2 has register broadcasts.
8191     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8192       return SDValue();
8193   } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
8194     // 32-bit targets need to load i64 as a f64 and then bitcast the result.
8195     if (!Subtarget->is64Bit() && VT.getScalarType() == MVT::i64)
8196       BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
8197
8198     // If we are broadcasting a load that is only used by the shuffle
8199     // then we can reduce the vector load to the broadcasted scalar load.
8200     LoadSDNode *Ld = cast<LoadSDNode>(BC);
8201     SDValue BaseAddr = Ld->getOperand(1);
8202     EVT AddrVT = BaseAddr.getValueType();
8203     EVT SVT = BroadcastVT.getScalarType();
8204     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8205     SDValue NewAddr = DAG.getNode(
8206         ISD::ADD, DL, AddrVT, BaseAddr,
8207         DAG.getConstant(Offset, DL, AddrVT));
8208     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8209                     DAG.getMachineFunction().getMachineMemOperand(
8210                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8211   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8212     // We can't broadcast from a vector register without AVX2, and we can only
8213     // broadcast from the zero-element of a vector register.
8214     return SDValue();
8215   }
8216
8217   V = DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, V);
8218   return DAG.getBitcast(VT, V);
8219 }
8220
8221 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8222 // INSERTPS when the V1 elements are already in the correct locations
8223 // because otherwise we can just always use two SHUFPS instructions which
8224 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8225 // perform INSERTPS if a single V1 element is out of place and all V2
8226 // elements are zeroable.
8227 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8228                                             ArrayRef<int> Mask,
8229                                             SelectionDAG &DAG) {
8230   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8231   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8232   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8233   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8234
8235   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8236
8237   unsigned ZMask = 0;
8238   int V1DstIndex = -1;
8239   int V2DstIndex = -1;
8240   bool V1UsedInPlace = false;
8241
8242   for (int i = 0; i < 4; ++i) {
8243     // Synthesize a zero mask from the zeroable elements (includes undefs).
8244     if (Zeroable[i]) {
8245       ZMask |= 1 << i;
8246       continue;
8247     }
8248
8249     // Flag if we use any V1 inputs in place.
8250     if (i == Mask[i]) {
8251       V1UsedInPlace = true;
8252       continue;
8253     }
8254
8255     // We can only insert a single non-zeroable element.
8256     if (V1DstIndex != -1 || V2DstIndex != -1)
8257       return SDValue();
8258
8259     if (Mask[i] < 4) {
8260       // V1 input out of place for insertion.
8261       V1DstIndex = i;
8262     } else {
8263       // V2 input for insertion.
8264       V2DstIndex = i;
8265     }
8266   }
8267
8268   // Don't bother if we have no (non-zeroable) element for insertion.
8269   if (V1DstIndex == -1 && V2DstIndex == -1)
8270     return SDValue();
8271
8272   // Determine element insertion src/dst indices. The src index is from the
8273   // start of the inserted vector, not the start of the concatenated vector.
8274   unsigned V2SrcIndex = 0;
8275   if (V1DstIndex != -1) {
8276     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8277     // and don't use the original V2 at all.
8278     V2SrcIndex = Mask[V1DstIndex];
8279     V2DstIndex = V1DstIndex;
8280     V2 = V1;
8281   } else {
8282     V2SrcIndex = Mask[V2DstIndex] - 4;
8283   }
8284
8285   // If no V1 inputs are used in place, then the result is created only from
8286   // the zero mask and the V2 insertion - so remove V1 dependency.
8287   if (!V1UsedInPlace)
8288     V1 = DAG.getUNDEF(MVT::v4f32);
8289
8290   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8291   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8292
8293   // Insert the V2 element into the desired position.
8294   SDLoc DL(Op);
8295   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8296                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8297 }
8298
8299 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8300 /// UNPCK instruction.
8301 ///
8302 /// This specifically targets cases where we end up with alternating between
8303 /// the two inputs, and so can permute them into something that feeds a single
8304 /// UNPCK instruction. Note that this routine only targets integer vectors
8305 /// because for floating point vectors we have a generalized SHUFPS lowering
8306 /// strategy that handles everything that doesn't *exactly* match an unpack,
8307 /// making this clever lowering unnecessary.
8308 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8309                                                     SDValue V1, SDValue V2,
8310                                                     ArrayRef<int> Mask,
8311                                                     SelectionDAG &DAG) {
8312   assert(!VT.isFloatingPoint() &&
8313          "This routine only supports integer vectors.");
8314   assert(!isSingleInputShuffleMask(Mask) &&
8315          "This routine should only be used when blending two inputs.");
8316   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8317
8318   int Size = Mask.size();
8319
8320   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8321     return M >= 0 && M % Size < Size / 2;
8322   });
8323   int NumHiInputs = std::count_if(
8324       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8325
8326   bool UnpackLo = NumLoInputs >= NumHiInputs;
8327
8328   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8329     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8330     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8331
8332     for (int i = 0; i < Size; ++i) {
8333       if (Mask[i] < 0)
8334         continue;
8335
8336       // Each element of the unpack contains Scale elements from this mask.
8337       int UnpackIdx = i / Scale;
8338
8339       // We only handle the case where V1 feeds the first slots of the unpack.
8340       // We rely on canonicalization to ensure this is the case.
8341       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8342         return SDValue();
8343
8344       // Setup the mask for this input. The indexing is tricky as we have to
8345       // handle the unpack stride.
8346       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8347       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8348           Mask[i] % Size;
8349     }
8350
8351     // If we will have to shuffle both inputs to use the unpack, check whether
8352     // we can just unpack first and shuffle the result. If so, skip this unpack.
8353     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8354         !isNoopShuffleMask(V2Mask))
8355       return SDValue();
8356
8357     // Shuffle the inputs into place.
8358     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8359     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8360
8361     // Cast the inputs to the type we will use to unpack them.
8362     V1 = DAG.getBitcast(UnpackVT, V1);
8363     V2 = DAG.getBitcast(UnpackVT, V2);
8364
8365     // Unpack the inputs and cast the result back to the desired type.
8366     return DAG.getBitcast(
8367         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8368                         UnpackVT, V1, V2));
8369   };
8370
8371   // We try each unpack from the largest to the smallest to try and find one
8372   // that fits this mask.
8373   int OrigNumElements = VT.getVectorNumElements();
8374   int OrigScalarSize = VT.getScalarSizeInBits();
8375   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8376     int Scale = ScalarSize / OrigScalarSize;
8377     int NumElements = OrigNumElements / Scale;
8378     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8379     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8380       return Unpack;
8381   }
8382
8383   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8384   // initial unpack.
8385   if (NumLoInputs == 0 || NumHiInputs == 0) {
8386     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8387            "We have to have *some* inputs!");
8388     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8389
8390     // FIXME: We could consider the total complexity of the permute of each
8391     // possible unpacking. Or at the least we should consider how many
8392     // half-crossings are created.
8393     // FIXME: We could consider commuting the unpacks.
8394
8395     SmallVector<int, 32> PermMask;
8396     PermMask.assign(Size, -1);
8397     for (int i = 0; i < Size; ++i) {
8398       if (Mask[i] < 0)
8399         continue;
8400
8401       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8402
8403       PermMask[i] =
8404           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8405     }
8406     return DAG.getVectorShuffle(
8407         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8408                             DL, VT, V1, V2),
8409         DAG.getUNDEF(VT), PermMask);
8410   }
8411
8412   return SDValue();
8413 }
8414
8415 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8416 ///
8417 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8418 /// support for floating point shuffles but not integer shuffles. These
8419 /// instructions will incur a domain crossing penalty on some chips though so
8420 /// it is better to avoid lowering through this for integer vectors where
8421 /// possible.
8422 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8423                                        const X86Subtarget *Subtarget,
8424                                        SelectionDAG &DAG) {
8425   SDLoc DL(Op);
8426   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8427   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8428   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8429   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8430   ArrayRef<int> Mask = SVOp->getMask();
8431   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8432
8433   if (isSingleInputShuffleMask(Mask)) {
8434     // Use low duplicate instructions for masks that match their pattern.
8435     if (Subtarget->hasSSE3())
8436       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8437         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8438
8439     // Straight shuffle of a single input vector. Simulate this by using the
8440     // single input as both of the "inputs" to this instruction..
8441     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8442
8443     if (Subtarget->hasAVX()) {
8444       // If we have AVX, we can use VPERMILPS which will allow folding a load
8445       // into the shuffle.
8446       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8447                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8448     }
8449
8450     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8451                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8452   }
8453   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8454   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8455
8456   // If we have a single input, insert that into V1 if we can do so cheaply.
8457   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8458     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8459             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8460       return Insertion;
8461     // Try inverting the insertion since for v2 masks it is easy to do and we
8462     // can't reliably sort the mask one way or the other.
8463     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8464                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8465     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8466             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8467       return Insertion;
8468   }
8469
8470   // Try to use one of the special instruction patterns to handle two common
8471   // blend patterns if a zero-blend above didn't work.
8472   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8473       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8474     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8475       // We can either use a special instruction to load over the low double or
8476       // to move just the low double.
8477       return DAG.getNode(
8478           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8479           DL, MVT::v2f64, V2,
8480           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8481
8482   if (Subtarget->hasSSE41())
8483     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8484                                                   Subtarget, DAG))
8485       return Blend;
8486
8487   // Use dedicated unpack instructions for masks that match their pattern.
8488   if (SDValue V =
8489           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8490     return V;
8491
8492   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8493   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8494                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8495 }
8496
8497 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8498 ///
8499 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8500 /// the integer unit to minimize domain crossing penalties. However, for blends
8501 /// it falls back to the floating point shuffle operation with appropriate bit
8502 /// casting.
8503 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8504                                        const X86Subtarget *Subtarget,
8505                                        SelectionDAG &DAG) {
8506   SDLoc DL(Op);
8507   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8508   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8509   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8510   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8511   ArrayRef<int> Mask = SVOp->getMask();
8512   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8513
8514   if (isSingleInputShuffleMask(Mask)) {
8515     // Check for being able to broadcast a single element.
8516     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8517                                                           Mask, Subtarget, DAG))
8518       return Broadcast;
8519
8520     // Straight shuffle of a single input vector. For everything from SSE2
8521     // onward this has a single fast instruction with no scary immediates.
8522     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8523     V1 = DAG.getBitcast(MVT::v4i32, V1);
8524     int WidenedMask[4] = {
8525         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8526         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8527     return DAG.getBitcast(
8528         MVT::v2i64,
8529         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8530                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8531   }
8532   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8533   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8534   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8535   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8536
8537   // If we have a blend of two PACKUS operations an the blend aligns with the
8538   // low and half halves, we can just merge the PACKUS operations. This is
8539   // particularly important as it lets us merge shuffles that this routine itself
8540   // creates.
8541   auto GetPackNode = [](SDValue V) {
8542     while (V.getOpcode() == ISD::BITCAST)
8543       V = V.getOperand(0);
8544
8545     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8546   };
8547   if (SDValue V1Pack = GetPackNode(V1))
8548     if (SDValue V2Pack = GetPackNode(V2))
8549       return DAG.getBitcast(MVT::v2i64,
8550                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8551                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8552                                                      : V1Pack.getOperand(1),
8553                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8554                                                      : V2Pack.getOperand(1)));
8555
8556   // Try to use shift instructions.
8557   if (SDValue Shift =
8558           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8559     return Shift;
8560
8561   // When loading a scalar and then shuffling it into a vector we can often do
8562   // the insertion cheaply.
8563   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8564           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8565     return Insertion;
8566   // Try inverting the insertion since for v2 masks it is easy to do and we
8567   // can't reliably sort the mask one way or the other.
8568   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8569   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8570           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8571     return Insertion;
8572
8573   // We have different paths for blend lowering, but they all must use the
8574   // *exact* same predicate.
8575   bool IsBlendSupported = Subtarget->hasSSE41();
8576   if (IsBlendSupported)
8577     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8578                                                   Subtarget, DAG))
8579       return Blend;
8580
8581   // Use dedicated unpack instructions for masks that match their pattern.
8582   if (SDValue V =
8583           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8584     return V;
8585
8586   // Try to use byte rotation instructions.
8587   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8588   if (Subtarget->hasSSSE3())
8589     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8590             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8591       return Rotate;
8592
8593   // If we have direct support for blends, we should lower by decomposing into
8594   // a permute. That will be faster than the domain cross.
8595   if (IsBlendSupported)
8596     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8597                                                       Mask, DAG);
8598
8599   // We implement this with SHUFPD which is pretty lame because it will likely
8600   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8601   // However, all the alternatives are still more cycles and newer chips don't
8602   // have this problem. It would be really nice if x86 had better shuffles here.
8603   V1 = DAG.getBitcast(MVT::v2f64, V1);
8604   V2 = DAG.getBitcast(MVT::v2f64, V2);
8605   return DAG.getBitcast(MVT::v2i64,
8606                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8607 }
8608
8609 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8610 ///
8611 /// This is used to disable more specialized lowerings when the shufps lowering
8612 /// will happen to be efficient.
8613 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8614   // This routine only handles 128-bit shufps.
8615   assert(Mask.size() == 4 && "Unsupported mask size!");
8616
8617   // To lower with a single SHUFPS we need to have the low half and high half
8618   // each requiring a single input.
8619   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8620     return false;
8621   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8622     return false;
8623
8624   return true;
8625 }
8626
8627 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8628 ///
8629 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8630 /// It makes no assumptions about whether this is the *best* lowering, it simply
8631 /// uses it.
8632 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8633                                             ArrayRef<int> Mask, SDValue V1,
8634                                             SDValue V2, SelectionDAG &DAG) {
8635   SDValue LowV = V1, HighV = V2;
8636   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8637
8638   int NumV2Elements =
8639       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8640
8641   if (NumV2Elements == 1) {
8642     int V2Index =
8643         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8644         Mask.begin();
8645
8646     // Compute the index adjacent to V2Index and in the same half by toggling
8647     // the low bit.
8648     int V2AdjIndex = V2Index ^ 1;
8649
8650     if (Mask[V2AdjIndex] == -1) {
8651       // Handles all the cases where we have a single V2 element and an undef.
8652       // This will only ever happen in the high lanes because we commute the
8653       // vector otherwise.
8654       if (V2Index < 2)
8655         std::swap(LowV, HighV);
8656       NewMask[V2Index] -= 4;
8657     } else {
8658       // Handle the case where the V2 element ends up adjacent to a V1 element.
8659       // To make this work, blend them together as the first step.
8660       int V1Index = V2AdjIndex;
8661       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8662       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8663                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8664
8665       // Now proceed to reconstruct the final blend as we have the necessary
8666       // high or low half formed.
8667       if (V2Index < 2) {
8668         LowV = V2;
8669         HighV = V1;
8670       } else {
8671         HighV = V2;
8672       }
8673       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8674       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8675     }
8676   } else if (NumV2Elements == 2) {
8677     if (Mask[0] < 4 && Mask[1] < 4) {
8678       // Handle the easy case where we have V1 in the low lanes and V2 in the
8679       // high lanes.
8680       NewMask[2] -= 4;
8681       NewMask[3] -= 4;
8682     } else if (Mask[2] < 4 && Mask[3] < 4) {
8683       // We also handle the reversed case because this utility may get called
8684       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8685       // arrange things in the right direction.
8686       NewMask[0] -= 4;
8687       NewMask[1] -= 4;
8688       HighV = V1;
8689       LowV = V2;
8690     } else {
8691       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8692       // trying to place elements directly, just blend them and set up the final
8693       // shuffle to place them.
8694
8695       // The first two blend mask elements are for V1, the second two are for
8696       // V2.
8697       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8698                           Mask[2] < 4 ? Mask[2] : Mask[3],
8699                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8700                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8701       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8702                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8703
8704       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8705       // a blend.
8706       LowV = HighV = V1;
8707       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8708       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8709       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8710       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8711     }
8712   }
8713   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8714                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8715 }
8716
8717 /// \brief Lower 4-lane 32-bit floating point shuffles.
8718 ///
8719 /// Uses instructions exclusively from the floating point unit to minimize
8720 /// domain crossing penalties, as these are sufficient to implement all v4f32
8721 /// shuffles.
8722 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8723                                        const X86Subtarget *Subtarget,
8724                                        SelectionDAG &DAG) {
8725   SDLoc DL(Op);
8726   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8727   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8728   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8729   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8730   ArrayRef<int> Mask = SVOp->getMask();
8731   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8732
8733   int NumV2Elements =
8734       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8735
8736   if (NumV2Elements == 0) {
8737     // Check for being able to broadcast a single element.
8738     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8739                                                           Mask, Subtarget, DAG))
8740       return Broadcast;
8741
8742     // Use even/odd duplicate instructions for masks that match their pattern.
8743     if (Subtarget->hasSSE3()) {
8744       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8745         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8746       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8747         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8748     }
8749
8750     if (Subtarget->hasAVX()) {
8751       // If we have AVX, we can use VPERMILPS which will allow folding a load
8752       // into the shuffle.
8753       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8754                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8755     }
8756
8757     // Otherwise, use a straight shuffle of a single input vector. We pass the
8758     // input vector to both operands to simulate this with a SHUFPS.
8759     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8760                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8761   }
8762
8763   // There are special ways we can lower some single-element blends. However, we
8764   // have custom ways we can lower more complex single-element blends below that
8765   // we defer to if both this and BLENDPS fail to match, so restrict this to
8766   // when the V2 input is targeting element 0 of the mask -- that is the fast
8767   // case here.
8768   if (NumV2Elements == 1 && Mask[0] >= 4)
8769     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8770                                                          Mask, Subtarget, DAG))
8771       return V;
8772
8773   if (Subtarget->hasSSE41()) {
8774     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8775                                                   Subtarget, DAG))
8776       return Blend;
8777
8778     // Use INSERTPS if we can complete the shuffle efficiently.
8779     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8780       return V;
8781
8782     if (!isSingleSHUFPSMask(Mask))
8783       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8784               DL, MVT::v4f32, V1, V2, Mask, DAG))
8785         return BlendPerm;
8786   }
8787
8788   // Use dedicated unpack instructions for masks that match their pattern.
8789   if (SDValue V =
8790           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8791     return V;
8792
8793   // Otherwise fall back to a SHUFPS lowering strategy.
8794   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8795 }
8796
8797 /// \brief Lower 4-lane i32 vector shuffles.
8798 ///
8799 /// We try to handle these with integer-domain shuffles where we can, but for
8800 /// blends we use the floating point domain blend instructions.
8801 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8802                                        const X86Subtarget *Subtarget,
8803                                        SelectionDAG &DAG) {
8804   SDLoc DL(Op);
8805   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8806   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8807   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8808   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8809   ArrayRef<int> Mask = SVOp->getMask();
8810   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8811
8812   // Whenever we can lower this as a zext, that instruction is strictly faster
8813   // than any alternative. It also allows us to fold memory operands into the
8814   // shuffle in many cases.
8815   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8816                                                          Mask, Subtarget, DAG))
8817     return ZExt;
8818
8819   int NumV2Elements =
8820       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8821
8822   if (NumV2Elements == 0) {
8823     // Check for being able to broadcast a single element.
8824     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8825                                                           Mask, Subtarget, DAG))
8826       return Broadcast;
8827
8828     // Straight shuffle of a single input vector. For everything from SSE2
8829     // onward this has a single fast instruction with no scary immediates.
8830     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8831     // but we aren't actually going to use the UNPCK instruction because doing
8832     // so prevents folding a load into this instruction or making a copy.
8833     const int UnpackLoMask[] = {0, 0, 1, 1};
8834     const int UnpackHiMask[] = {2, 2, 3, 3};
8835     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8836       Mask = UnpackLoMask;
8837     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8838       Mask = UnpackHiMask;
8839
8840     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8841                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8842   }
8843
8844   // Try to use shift instructions.
8845   if (SDValue Shift =
8846           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8847     return Shift;
8848
8849   // There are special ways we can lower some single-element blends.
8850   if (NumV2Elements == 1)
8851     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8852                                                          Mask, Subtarget, DAG))
8853       return V;
8854
8855   // We have different paths for blend lowering, but they all must use the
8856   // *exact* same predicate.
8857   bool IsBlendSupported = Subtarget->hasSSE41();
8858   if (IsBlendSupported)
8859     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8860                                                   Subtarget, DAG))
8861       return Blend;
8862
8863   if (SDValue Masked =
8864           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8865     return Masked;
8866
8867   // Use dedicated unpack instructions for masks that match their pattern.
8868   if (SDValue V =
8869           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8870     return V;
8871
8872   // Try to use byte rotation instructions.
8873   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8874   if (Subtarget->hasSSSE3())
8875     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8876             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8877       return Rotate;
8878
8879   // If we have direct support for blends, we should lower by decomposing into
8880   // a permute. That will be faster than the domain cross.
8881   if (IsBlendSupported)
8882     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8883                                                       Mask, DAG);
8884
8885   // Try to lower by permuting the inputs into an unpack instruction.
8886   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8887                                                             V2, Mask, DAG))
8888     return Unpack;
8889
8890   // We implement this with SHUFPS because it can blend from two vectors.
8891   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8892   // up the inputs, bypassing domain shift penalties that we would encur if we
8893   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8894   // relevant.
8895   return DAG.getBitcast(
8896       MVT::v4i32,
8897       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8898                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8899 }
8900
8901 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8902 /// shuffle lowering, and the most complex part.
8903 ///
8904 /// The lowering strategy is to try to form pairs of input lanes which are
8905 /// targeted at the same half of the final vector, and then use a dword shuffle
8906 /// to place them onto the right half, and finally unpack the paired lanes into
8907 /// their final position.
8908 ///
8909 /// The exact breakdown of how to form these dword pairs and align them on the
8910 /// correct sides is really tricky. See the comments within the function for
8911 /// more of the details.
8912 ///
8913 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8914 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8915 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8916 /// vector, form the analogous 128-bit 8-element Mask.
8917 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8918     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8919     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8920   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8921   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8922
8923   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8924   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8925   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8926
8927   SmallVector<int, 4> LoInputs;
8928   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8929                [](int M) { return M >= 0; });
8930   std::sort(LoInputs.begin(), LoInputs.end());
8931   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8932   SmallVector<int, 4> HiInputs;
8933   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8934                [](int M) { return M >= 0; });
8935   std::sort(HiInputs.begin(), HiInputs.end());
8936   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8937   int NumLToL =
8938       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8939   int NumHToL = LoInputs.size() - NumLToL;
8940   int NumLToH =
8941       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8942   int NumHToH = HiInputs.size() - NumLToH;
8943   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8944   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8945   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8946   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8947
8948   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8949   // such inputs we can swap two of the dwords across the half mark and end up
8950   // with <=2 inputs to each half in each half. Once there, we can fall through
8951   // to the generic code below. For example:
8952   //
8953   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8954   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8955   //
8956   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8957   // and an existing 2-into-2 on the other half. In this case we may have to
8958   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8959   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8960   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8961   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8962   // half than the one we target for fixing) will be fixed when we re-enter this
8963   // path. We will also combine away any sequence of PSHUFD instructions that
8964   // result into a single instruction. Here is an example of the tricky case:
8965   //
8966   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8967   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8968   //
8969   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8970   //
8971   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8972   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8973   //
8974   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8975   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8976   //
8977   // The result is fine to be handled by the generic logic.
8978   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8979                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8980                           int AOffset, int BOffset) {
8981     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8982            "Must call this with A having 3 or 1 inputs from the A half.");
8983     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8984            "Must call this with B having 1 or 3 inputs from the B half.");
8985     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8986            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8987
8988     bool ThreeAInputs = AToAInputs.size() == 3;
8989
8990     // Compute the index of dword with only one word among the three inputs in
8991     // a half by taking the sum of the half with three inputs and subtracting
8992     // the sum of the actual three inputs. The difference is the remaining
8993     // slot.
8994     int ADWord, BDWord;
8995     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8996     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8997     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8998     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8999     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
9000     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
9001     int TripleNonInputIdx =
9002         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
9003     TripleDWord = TripleNonInputIdx / 2;
9004
9005     // We use xor with one to compute the adjacent DWord to whichever one the
9006     // OneInput is in.
9007     OneInputDWord = (OneInput / 2) ^ 1;
9008
9009     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9010     // and BToA inputs. If there is also such a problem with the BToB and AToB
9011     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9012     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9013     // is essential that we don't *create* a 3<-1 as then we might oscillate.
9014     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9015       // Compute how many inputs will be flipped by swapping these DWords. We
9016       // need
9017       // to balance this to ensure we don't form a 3-1 shuffle in the other
9018       // half.
9019       int NumFlippedAToBInputs =
9020           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9021           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9022       int NumFlippedBToBInputs =
9023           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9024           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9025       if ((NumFlippedAToBInputs == 1 &&
9026            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9027           (NumFlippedBToBInputs == 1 &&
9028            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9029         // We choose whether to fix the A half or B half based on whether that
9030         // half has zero flipped inputs. At zero, we may not be able to fix it
9031         // with that half. We also bias towards fixing the B half because that
9032         // will more commonly be the high half, and we have to bias one way.
9033         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9034                                                        ArrayRef<int> Inputs) {
9035           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9036           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9037                                          PinnedIdx ^ 1) != Inputs.end();
9038           // Determine whether the free index is in the flipped dword or the
9039           // unflipped dword based on where the pinned index is. We use this bit
9040           // in an xor to conditionally select the adjacent dword.
9041           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9042           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9043                                              FixFreeIdx) != Inputs.end();
9044           if (IsFixIdxInput == IsFixFreeIdxInput)
9045             FixFreeIdx += 1;
9046           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9047                                         FixFreeIdx) != Inputs.end();
9048           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9049                  "We need to be changing the number of flipped inputs!");
9050           int PSHUFHalfMask[] = {0, 1, 2, 3};
9051           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9052           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9053                           MVT::v8i16, V,
9054                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9055
9056           for (int &M : Mask)
9057             if (M != -1 && M == FixIdx)
9058               M = FixFreeIdx;
9059             else if (M != -1 && M == FixFreeIdx)
9060               M = FixIdx;
9061         };
9062         if (NumFlippedBToBInputs != 0) {
9063           int BPinnedIdx =
9064               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9065           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9066         } else {
9067           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9068           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9069           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9070         }
9071       }
9072     }
9073
9074     int PSHUFDMask[] = {0, 1, 2, 3};
9075     PSHUFDMask[ADWord] = BDWord;
9076     PSHUFDMask[BDWord] = ADWord;
9077     V = DAG.getBitcast(
9078         VT,
9079         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9080                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9081
9082     // Adjust the mask to match the new locations of A and B.
9083     for (int &M : Mask)
9084       if (M != -1 && M/2 == ADWord)
9085         M = 2 * BDWord + M % 2;
9086       else if (M != -1 && M/2 == BDWord)
9087         M = 2 * ADWord + M % 2;
9088
9089     // Recurse back into this routine to re-compute state now that this isn't
9090     // a 3 and 1 problem.
9091     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9092                                                      DAG);
9093   };
9094   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9095     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9096   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9097     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9098
9099   // At this point there are at most two inputs to the low and high halves from
9100   // each half. That means the inputs can always be grouped into dwords and
9101   // those dwords can then be moved to the correct half with a dword shuffle.
9102   // We use at most one low and one high word shuffle to collect these paired
9103   // inputs into dwords, and finally a dword shuffle to place them.
9104   int PSHUFLMask[4] = {-1, -1, -1, -1};
9105   int PSHUFHMask[4] = {-1, -1, -1, -1};
9106   int PSHUFDMask[4] = {-1, -1, -1, -1};
9107
9108   // First fix the masks for all the inputs that are staying in their
9109   // original halves. This will then dictate the targets of the cross-half
9110   // shuffles.
9111   auto fixInPlaceInputs =
9112       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9113                     MutableArrayRef<int> SourceHalfMask,
9114                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9115     if (InPlaceInputs.empty())
9116       return;
9117     if (InPlaceInputs.size() == 1) {
9118       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9119           InPlaceInputs[0] - HalfOffset;
9120       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9121       return;
9122     }
9123     if (IncomingInputs.empty()) {
9124       // Just fix all of the in place inputs.
9125       for (int Input : InPlaceInputs) {
9126         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9127         PSHUFDMask[Input / 2] = Input / 2;
9128       }
9129       return;
9130     }
9131
9132     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9133     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9134         InPlaceInputs[0] - HalfOffset;
9135     // Put the second input next to the first so that they are packed into
9136     // a dword. We find the adjacent index by toggling the low bit.
9137     int AdjIndex = InPlaceInputs[0] ^ 1;
9138     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9139     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9140     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9141   };
9142   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9143   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9144
9145   // Now gather the cross-half inputs and place them into a free dword of
9146   // their target half.
9147   // FIXME: This operation could almost certainly be simplified dramatically to
9148   // look more like the 3-1 fixing operation.
9149   auto moveInputsToRightHalf = [&PSHUFDMask](
9150       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9151       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9152       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9153       int DestOffset) {
9154     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9155       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9156     };
9157     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9158                                                int Word) {
9159       int LowWord = Word & ~1;
9160       int HighWord = Word | 1;
9161       return isWordClobbered(SourceHalfMask, LowWord) ||
9162              isWordClobbered(SourceHalfMask, HighWord);
9163     };
9164
9165     if (IncomingInputs.empty())
9166       return;
9167
9168     if (ExistingInputs.empty()) {
9169       // Map any dwords with inputs from them into the right half.
9170       for (int Input : IncomingInputs) {
9171         // If the source half mask maps over the inputs, turn those into
9172         // swaps and use the swapped lane.
9173         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9174           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9175             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9176                 Input - SourceOffset;
9177             // We have to swap the uses in our half mask in one sweep.
9178             for (int &M : HalfMask)
9179               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9180                 M = Input;
9181               else if (M == Input)
9182                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9183           } else {
9184             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9185                        Input - SourceOffset &&
9186                    "Previous placement doesn't match!");
9187           }
9188           // Note that this correctly re-maps both when we do a swap and when
9189           // we observe the other side of the swap above. We rely on that to
9190           // avoid swapping the members of the input list directly.
9191           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9192         }
9193
9194         // Map the input's dword into the correct half.
9195         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9196           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9197         else
9198           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9199                      Input / 2 &&
9200                  "Previous placement doesn't match!");
9201       }
9202
9203       // And just directly shift any other-half mask elements to be same-half
9204       // as we will have mirrored the dword containing the element into the
9205       // same position within that half.
9206       for (int &M : HalfMask)
9207         if (M >= SourceOffset && M < SourceOffset + 4) {
9208           M = M - SourceOffset + DestOffset;
9209           assert(M >= 0 && "This should never wrap below zero!");
9210         }
9211       return;
9212     }
9213
9214     // Ensure we have the input in a viable dword of its current half. This
9215     // is particularly tricky because the original position may be clobbered
9216     // by inputs being moved and *staying* in that half.
9217     if (IncomingInputs.size() == 1) {
9218       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9219         int InputFixed = std::find(std::begin(SourceHalfMask),
9220                                    std::end(SourceHalfMask), -1) -
9221                          std::begin(SourceHalfMask) + SourceOffset;
9222         SourceHalfMask[InputFixed - SourceOffset] =
9223             IncomingInputs[0] - SourceOffset;
9224         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9225                      InputFixed);
9226         IncomingInputs[0] = InputFixed;
9227       }
9228     } else if (IncomingInputs.size() == 2) {
9229       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9230           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9231         // We have two non-adjacent or clobbered inputs we need to extract from
9232         // the source half. To do this, we need to map them into some adjacent
9233         // dword slot in the source mask.
9234         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9235                               IncomingInputs[1] - SourceOffset};
9236
9237         // If there is a free slot in the source half mask adjacent to one of
9238         // the inputs, place the other input in it. We use (Index XOR 1) to
9239         // compute an adjacent index.
9240         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9241             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9242           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9243           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9244           InputsFixed[1] = InputsFixed[0] ^ 1;
9245         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9246                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9247           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9248           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9249           InputsFixed[0] = InputsFixed[1] ^ 1;
9250         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9251                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9252           // The two inputs are in the same DWord but it is clobbered and the
9253           // adjacent DWord isn't used at all. Move both inputs to the free
9254           // slot.
9255           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9256           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9257           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9258           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9259         } else {
9260           // The only way we hit this point is if there is no clobbering
9261           // (because there are no off-half inputs to this half) and there is no
9262           // free slot adjacent to one of the inputs. In this case, we have to
9263           // swap an input with a non-input.
9264           for (int i = 0; i < 4; ++i)
9265             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9266                    "We can't handle any clobbers here!");
9267           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9268                  "Cannot have adjacent inputs here!");
9269
9270           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9271           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9272
9273           // We also have to update the final source mask in this case because
9274           // it may need to undo the above swap.
9275           for (int &M : FinalSourceHalfMask)
9276             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9277               M = InputsFixed[1] + SourceOffset;
9278             else if (M == InputsFixed[1] + SourceOffset)
9279               M = (InputsFixed[0] ^ 1) + SourceOffset;
9280
9281           InputsFixed[1] = InputsFixed[0] ^ 1;
9282         }
9283
9284         // Point everything at the fixed inputs.
9285         for (int &M : HalfMask)
9286           if (M == IncomingInputs[0])
9287             M = InputsFixed[0] + SourceOffset;
9288           else if (M == IncomingInputs[1])
9289             M = InputsFixed[1] + SourceOffset;
9290
9291         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9292         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9293       }
9294     } else {
9295       llvm_unreachable("Unhandled input size!");
9296     }
9297
9298     // Now hoist the DWord down to the right half.
9299     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9300     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9301     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9302     for (int &M : HalfMask)
9303       for (int Input : IncomingInputs)
9304         if (M == Input)
9305           M = FreeDWord * 2 + Input % 2;
9306   };
9307   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9308                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9309   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9310                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9311
9312   // Now enact all the shuffles we've computed to move the inputs into their
9313   // target half.
9314   if (!isNoopShuffleMask(PSHUFLMask))
9315     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9316                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9317   if (!isNoopShuffleMask(PSHUFHMask))
9318     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9319                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9320   if (!isNoopShuffleMask(PSHUFDMask))
9321     V = DAG.getBitcast(
9322         VT,
9323         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9324                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9325
9326   // At this point, each half should contain all its inputs, and we can then
9327   // just shuffle them into their final position.
9328   assert(std::count_if(LoMask.begin(), LoMask.end(),
9329                        [](int M) { return M >= 4; }) == 0 &&
9330          "Failed to lift all the high half inputs to the low mask!");
9331   assert(std::count_if(HiMask.begin(), HiMask.end(),
9332                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9333          "Failed to lift all the low half inputs to the high mask!");
9334
9335   // Do a half shuffle for the low mask.
9336   if (!isNoopShuffleMask(LoMask))
9337     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9338                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9339
9340   // Do a half shuffle with the high mask after shifting its values down.
9341   for (int &M : HiMask)
9342     if (M >= 0)
9343       M -= 4;
9344   if (!isNoopShuffleMask(HiMask))
9345     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9346                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9347
9348   return V;
9349 }
9350
9351 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9352 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9353                                           SDValue V2, ArrayRef<int> Mask,
9354                                           SelectionDAG &DAG, bool &V1InUse,
9355                                           bool &V2InUse) {
9356   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9357   SDValue V1Mask[16];
9358   SDValue V2Mask[16];
9359   V1InUse = false;
9360   V2InUse = false;
9361
9362   int Size = Mask.size();
9363   int Scale = 16 / Size;
9364   for (int i = 0; i < 16; ++i) {
9365     if (Mask[i / Scale] == -1) {
9366       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9367     } else {
9368       const int ZeroMask = 0x80;
9369       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9370                                           : ZeroMask;
9371       int V2Idx = Mask[i / Scale] < Size
9372                       ? ZeroMask
9373                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9374       if (Zeroable[i / Scale])
9375         V1Idx = V2Idx = ZeroMask;
9376       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9377       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9378       V1InUse |= (ZeroMask != V1Idx);
9379       V2InUse |= (ZeroMask != V2Idx);
9380     }
9381   }
9382
9383   if (V1InUse)
9384     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9385                      DAG.getBitcast(MVT::v16i8, V1),
9386                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9387   if (V2InUse)
9388     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9389                      DAG.getBitcast(MVT::v16i8, V2),
9390                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9391
9392   // If we need shuffled inputs from both, blend the two.
9393   SDValue V;
9394   if (V1InUse && V2InUse)
9395     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9396   else
9397     V = V1InUse ? V1 : V2;
9398
9399   // Cast the result back to the correct type.
9400   return DAG.getBitcast(VT, V);
9401 }
9402
9403 /// \brief Generic lowering of 8-lane i16 shuffles.
9404 ///
9405 /// This handles both single-input shuffles and combined shuffle/blends with
9406 /// two inputs. The single input shuffles are immediately delegated to
9407 /// a dedicated lowering routine.
9408 ///
9409 /// The blends are lowered in one of three fundamental ways. If there are few
9410 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9411 /// of the input is significantly cheaper when lowered as an interleaving of
9412 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9413 /// halves of the inputs separately (making them have relatively few inputs)
9414 /// and then concatenate them.
9415 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9416                                        const X86Subtarget *Subtarget,
9417                                        SelectionDAG &DAG) {
9418   SDLoc DL(Op);
9419   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9420   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9421   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9422   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9423   ArrayRef<int> OrigMask = SVOp->getMask();
9424   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9425                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9426   MutableArrayRef<int> Mask(MaskStorage);
9427
9428   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9429
9430   // Whenever we can lower this as a zext, that instruction is strictly faster
9431   // than any alternative.
9432   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9433           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9434     return ZExt;
9435
9436   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9437   (void)isV1;
9438   auto isV2 = [](int M) { return M >= 8; };
9439
9440   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9441
9442   if (NumV2Inputs == 0) {
9443     // Check for being able to broadcast a single element.
9444     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9445                                                           Mask, Subtarget, DAG))
9446       return Broadcast;
9447
9448     // Try to use shift instructions.
9449     if (SDValue Shift =
9450             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9451       return Shift;
9452
9453     // Use dedicated unpack instructions for masks that match their pattern.
9454     if (SDValue V =
9455             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9456       return V;
9457
9458     // Try to use byte rotation instructions.
9459     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9460                                                         Mask, Subtarget, DAG))
9461       return Rotate;
9462
9463     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9464                                                      Subtarget, DAG);
9465   }
9466
9467   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9468          "All single-input shuffles should be canonicalized to be V1-input "
9469          "shuffles.");
9470
9471   // Try to use shift instructions.
9472   if (SDValue Shift =
9473           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9474     return Shift;
9475
9476   // See if we can use SSE4A Extraction / Insertion.
9477   if (Subtarget->hasSSE4A())
9478     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9479       return V;
9480
9481   // There are special ways we can lower some single-element blends.
9482   if (NumV2Inputs == 1)
9483     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9484                                                          Mask, Subtarget, DAG))
9485       return V;
9486
9487   // We have different paths for blend lowering, but they all must use the
9488   // *exact* same predicate.
9489   bool IsBlendSupported = Subtarget->hasSSE41();
9490   if (IsBlendSupported)
9491     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9492                                                   Subtarget, DAG))
9493       return Blend;
9494
9495   if (SDValue Masked =
9496           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9497     return Masked;
9498
9499   // Use dedicated unpack instructions for masks that match their pattern.
9500   if (SDValue V =
9501           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9502     return V;
9503
9504   // Try to use byte rotation instructions.
9505   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9506           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9507     return Rotate;
9508
9509   if (SDValue BitBlend =
9510           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9511     return BitBlend;
9512
9513   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9514                                                             V2, Mask, DAG))
9515     return Unpack;
9516
9517   // If we can't directly blend but can use PSHUFB, that will be better as it
9518   // can both shuffle and set up the inefficient blend.
9519   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9520     bool V1InUse, V2InUse;
9521     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9522                                       V1InUse, V2InUse);
9523   }
9524
9525   // We can always bit-blend if we have to so the fallback strategy is to
9526   // decompose into single-input permutes and blends.
9527   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9528                                                       Mask, DAG);
9529 }
9530
9531 /// \brief Check whether a compaction lowering can be done by dropping even
9532 /// elements and compute how many times even elements must be dropped.
9533 ///
9534 /// This handles shuffles which take every Nth element where N is a power of
9535 /// two. Example shuffle masks:
9536 ///
9537 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9538 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9539 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9540 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9541 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9542 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9543 ///
9544 /// Any of these lanes can of course be undef.
9545 ///
9546 /// This routine only supports N <= 3.
9547 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9548 /// for larger N.
9549 ///
9550 /// \returns N above, or the number of times even elements must be dropped if
9551 /// there is such a number. Otherwise returns zero.
9552 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9553   // Figure out whether we're looping over two inputs or just one.
9554   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9555
9556   // The modulus for the shuffle vector entries is based on whether this is
9557   // a single input or not.
9558   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9559   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9560          "We should only be called with masks with a power-of-2 size!");
9561
9562   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9563
9564   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9565   // and 2^3 simultaneously. This is because we may have ambiguity with
9566   // partially undef inputs.
9567   bool ViableForN[3] = {true, true, true};
9568
9569   for (int i = 0, e = Mask.size(); i < e; ++i) {
9570     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9571     // want.
9572     if (Mask[i] == -1)
9573       continue;
9574
9575     bool IsAnyViable = false;
9576     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9577       if (ViableForN[j]) {
9578         uint64_t N = j + 1;
9579
9580         // The shuffle mask must be equal to (i * 2^N) % M.
9581         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9582           IsAnyViable = true;
9583         else
9584           ViableForN[j] = false;
9585       }
9586     // Early exit if we exhaust the possible powers of two.
9587     if (!IsAnyViable)
9588       break;
9589   }
9590
9591   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9592     if (ViableForN[j])
9593       return j + 1;
9594
9595   // Return 0 as there is no viable power of two.
9596   return 0;
9597 }
9598
9599 /// \brief Generic lowering of v16i8 shuffles.
9600 ///
9601 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9602 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9603 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9604 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9605 /// back together.
9606 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9607                                        const X86Subtarget *Subtarget,
9608                                        SelectionDAG &DAG) {
9609   SDLoc DL(Op);
9610   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9611   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9612   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9613   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9614   ArrayRef<int> Mask = SVOp->getMask();
9615   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9616
9617   // Try to use shift instructions.
9618   if (SDValue Shift =
9619           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9620     return Shift;
9621
9622   // Try to use byte rotation instructions.
9623   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9624           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9625     return Rotate;
9626
9627   // Try to use a zext lowering.
9628   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9629           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9630     return ZExt;
9631
9632   // See if we can use SSE4A Extraction / Insertion.
9633   if (Subtarget->hasSSE4A())
9634     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9635       return V;
9636
9637   int NumV2Elements =
9638       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9639
9640   // For single-input shuffles, there are some nicer lowering tricks we can use.
9641   if (NumV2Elements == 0) {
9642     // Check for being able to broadcast a single element.
9643     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9644                                                           Mask, Subtarget, DAG))
9645       return Broadcast;
9646
9647     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9648     // Notably, this handles splat and partial-splat shuffles more efficiently.
9649     // However, it only makes sense if the pre-duplication shuffle simplifies
9650     // things significantly. Currently, this means we need to be able to
9651     // express the pre-duplication shuffle as an i16 shuffle.
9652     //
9653     // FIXME: We should check for other patterns which can be widened into an
9654     // i16 shuffle as well.
9655     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9656       for (int i = 0; i < 16; i += 2)
9657         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9658           return false;
9659
9660       return true;
9661     };
9662     auto tryToWidenViaDuplication = [&]() -> SDValue {
9663       if (!canWidenViaDuplication(Mask))
9664         return SDValue();
9665       SmallVector<int, 4> LoInputs;
9666       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9667                    [](int M) { return M >= 0 && M < 8; });
9668       std::sort(LoInputs.begin(), LoInputs.end());
9669       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9670                      LoInputs.end());
9671       SmallVector<int, 4> HiInputs;
9672       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9673                    [](int M) { return M >= 8; });
9674       std::sort(HiInputs.begin(), HiInputs.end());
9675       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9676                      HiInputs.end());
9677
9678       bool TargetLo = LoInputs.size() >= HiInputs.size();
9679       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9680       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9681
9682       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9683       SmallDenseMap<int, int, 8> LaneMap;
9684       for (int I : InPlaceInputs) {
9685         PreDupI16Shuffle[I/2] = I/2;
9686         LaneMap[I] = I;
9687       }
9688       int j = TargetLo ? 0 : 4, je = j + 4;
9689       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9690         // Check if j is already a shuffle of this input. This happens when
9691         // there are two adjacent bytes after we move the low one.
9692         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9693           // If we haven't yet mapped the input, search for a slot into which
9694           // we can map it.
9695           while (j < je && PreDupI16Shuffle[j] != -1)
9696             ++j;
9697
9698           if (j == je)
9699             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9700             return SDValue();
9701
9702           // Map this input with the i16 shuffle.
9703           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9704         }
9705
9706         // Update the lane map based on the mapping we ended up with.
9707         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9708       }
9709       V1 = DAG.getBitcast(
9710           MVT::v16i8,
9711           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9712                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9713
9714       // Unpack the bytes to form the i16s that will be shuffled into place.
9715       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9716                        MVT::v16i8, V1, V1);
9717
9718       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9719       for (int i = 0; i < 16; ++i)
9720         if (Mask[i] != -1) {
9721           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9722           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9723           if (PostDupI16Shuffle[i / 2] == -1)
9724             PostDupI16Shuffle[i / 2] = MappedMask;
9725           else
9726             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9727                    "Conflicting entrties in the original shuffle!");
9728         }
9729       return DAG.getBitcast(
9730           MVT::v16i8,
9731           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9732                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9733     };
9734     if (SDValue V = tryToWidenViaDuplication())
9735       return V;
9736   }
9737
9738   if (SDValue Masked =
9739           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9740     return Masked;
9741
9742   // Use dedicated unpack instructions for masks that match their pattern.
9743   if (SDValue V =
9744           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9745     return V;
9746
9747   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9748   // with PSHUFB. It is important to do this before we attempt to generate any
9749   // blends but after all of the single-input lowerings. If the single input
9750   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9751   // want to preserve that and we can DAG combine any longer sequences into
9752   // a PSHUFB in the end. But once we start blending from multiple inputs,
9753   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9754   // and there are *very* few patterns that would actually be faster than the
9755   // PSHUFB approach because of its ability to zero lanes.
9756   //
9757   // FIXME: The only exceptions to the above are blends which are exact
9758   // interleavings with direct instructions supporting them. We currently don't
9759   // handle those well here.
9760   if (Subtarget->hasSSSE3()) {
9761     bool V1InUse = false;
9762     bool V2InUse = false;
9763
9764     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9765                                                 DAG, V1InUse, V2InUse);
9766
9767     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9768     // do so. This avoids using them to handle blends-with-zero which is
9769     // important as a single pshufb is significantly faster for that.
9770     if (V1InUse && V2InUse) {
9771       if (Subtarget->hasSSE41())
9772         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9773                                                       Mask, Subtarget, DAG))
9774           return Blend;
9775
9776       // We can use an unpack to do the blending rather than an or in some
9777       // cases. Even though the or may be (very minorly) more efficient, we
9778       // preference this lowering because there are common cases where part of
9779       // the complexity of the shuffles goes away when we do the final blend as
9780       // an unpack.
9781       // FIXME: It might be worth trying to detect if the unpack-feeding
9782       // shuffles will both be pshufb, in which case we shouldn't bother with
9783       // this.
9784       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9785               DL, MVT::v16i8, V1, V2, Mask, DAG))
9786         return Unpack;
9787     }
9788
9789     return PSHUFB;
9790   }
9791
9792   // There are special ways we can lower some single-element blends.
9793   if (NumV2Elements == 1)
9794     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9795                                                          Mask, Subtarget, DAG))
9796       return V;
9797
9798   if (SDValue BitBlend =
9799           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9800     return BitBlend;
9801
9802   // Check whether a compaction lowering can be done. This handles shuffles
9803   // which take every Nth element for some even N. See the helper function for
9804   // details.
9805   //
9806   // We special case these as they can be particularly efficiently handled with
9807   // the PACKUSB instruction on x86 and they show up in common patterns of
9808   // rearranging bytes to truncate wide elements.
9809   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9810     // NumEvenDrops is the power of two stride of the elements. Another way of
9811     // thinking about it is that we need to drop the even elements this many
9812     // times to get the original input.
9813     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9814
9815     // First we need to zero all the dropped bytes.
9816     assert(NumEvenDrops <= 3 &&
9817            "No support for dropping even elements more than 3 times.");
9818     // We use the mask type to pick which bytes are preserved based on how many
9819     // elements are dropped.
9820     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9821     SDValue ByteClearMask = DAG.getBitcast(
9822         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9823     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9824     if (!IsSingleInput)
9825       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9826
9827     // Now pack things back together.
9828     V1 = DAG.getBitcast(MVT::v8i16, V1);
9829     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9830     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9831     for (int i = 1; i < NumEvenDrops; ++i) {
9832       Result = DAG.getBitcast(MVT::v8i16, Result);
9833       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9834     }
9835
9836     return Result;
9837   }
9838
9839   // Handle multi-input cases by blending single-input shuffles.
9840   if (NumV2Elements > 0)
9841     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9842                                                       Mask, DAG);
9843
9844   // The fallback path for single-input shuffles widens this into two v8i16
9845   // vectors with unpacks, shuffles those, and then pulls them back together
9846   // with a pack.
9847   SDValue V = V1;
9848
9849   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9850   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9851   for (int i = 0; i < 16; ++i)
9852     if (Mask[i] >= 0)
9853       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9854
9855   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9856
9857   SDValue VLoHalf, VHiHalf;
9858   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9859   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9860   // i16s.
9861   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9862                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9863       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9864                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9865     // Use a mask to drop the high bytes.
9866     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9867     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9868                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9869
9870     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9871     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9872
9873     // Squash the masks to point directly into VLoHalf.
9874     for (int &M : LoBlendMask)
9875       if (M >= 0)
9876         M /= 2;
9877     for (int &M : HiBlendMask)
9878       if (M >= 0)
9879         M /= 2;
9880   } else {
9881     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9882     // VHiHalf so that we can blend them as i16s.
9883     VLoHalf = DAG.getBitcast(
9884         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9885     VHiHalf = DAG.getBitcast(
9886         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9887   }
9888
9889   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9890   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9891
9892   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9893 }
9894
9895 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9896 ///
9897 /// This routine breaks down the specific type of 128-bit shuffle and
9898 /// dispatches to the lowering routines accordingly.
9899 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9900                                         MVT VT, const X86Subtarget *Subtarget,
9901                                         SelectionDAG &DAG) {
9902   switch (VT.SimpleTy) {
9903   case MVT::v2i64:
9904     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9905   case MVT::v2f64:
9906     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9907   case MVT::v4i32:
9908     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9909   case MVT::v4f32:
9910     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9911   case MVT::v8i16:
9912     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9913   case MVT::v16i8:
9914     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9915
9916   default:
9917     llvm_unreachable("Unimplemented!");
9918   }
9919 }
9920
9921 /// \brief Helper function to test whether a shuffle mask could be
9922 /// simplified by widening the elements being shuffled.
9923 ///
9924 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9925 /// leaves it in an unspecified state.
9926 ///
9927 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9928 /// shuffle masks. The latter have the special property of a '-2' representing
9929 /// a zero-ed lane of a vector.
9930 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9931                                     SmallVectorImpl<int> &WidenedMask) {
9932   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9933     // If both elements are undef, its trivial.
9934     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9935       WidenedMask.push_back(SM_SentinelUndef);
9936       continue;
9937     }
9938
9939     // Check for an undef mask and a mask value properly aligned to fit with
9940     // a pair of values. If we find such a case, use the non-undef mask's value.
9941     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9942       WidenedMask.push_back(Mask[i + 1] / 2);
9943       continue;
9944     }
9945     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9946       WidenedMask.push_back(Mask[i] / 2);
9947       continue;
9948     }
9949
9950     // When zeroing, we need to spread the zeroing across both lanes to widen.
9951     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9952       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9953           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9954         WidenedMask.push_back(SM_SentinelZero);
9955         continue;
9956       }
9957       return false;
9958     }
9959
9960     // Finally check if the two mask values are adjacent and aligned with
9961     // a pair.
9962     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9963       WidenedMask.push_back(Mask[i] / 2);
9964       continue;
9965     }
9966
9967     // Otherwise we can't safely widen the elements used in this shuffle.
9968     return false;
9969   }
9970   assert(WidenedMask.size() == Mask.size() / 2 &&
9971          "Incorrect size of mask after widening the elements!");
9972
9973   return true;
9974 }
9975
9976 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9977 ///
9978 /// This routine just extracts two subvectors, shuffles them independently, and
9979 /// then concatenates them back together. This should work effectively with all
9980 /// AVX vector shuffle types.
9981 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9982                                           SDValue V2, ArrayRef<int> Mask,
9983                                           SelectionDAG &DAG) {
9984   assert(VT.getSizeInBits() >= 256 &&
9985          "Only for 256-bit or wider vector shuffles!");
9986   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9987   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9988
9989   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9990   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9991
9992   int NumElements = VT.getVectorNumElements();
9993   int SplitNumElements = NumElements / 2;
9994   MVT ScalarVT = VT.getVectorElementType();
9995   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9996
9997   // Rather than splitting build-vectors, just build two narrower build
9998   // vectors. This helps shuffling with splats and zeros.
9999   auto SplitVector = [&](SDValue V) {
10000     while (V.getOpcode() == ISD::BITCAST)
10001       V = V->getOperand(0);
10002
10003     MVT OrigVT = V.getSimpleValueType();
10004     int OrigNumElements = OrigVT.getVectorNumElements();
10005     int OrigSplitNumElements = OrigNumElements / 2;
10006     MVT OrigScalarVT = OrigVT.getVectorElementType();
10007     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10008
10009     SDValue LoV, HiV;
10010
10011     auto *BV = dyn_cast<BuildVectorSDNode>(V);
10012     if (!BV) {
10013       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10014                         DAG.getIntPtrConstant(0, DL));
10015       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10016                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10017     } else {
10018
10019       SmallVector<SDValue, 16> LoOps, HiOps;
10020       for (int i = 0; i < OrigSplitNumElements; ++i) {
10021         LoOps.push_back(BV->getOperand(i));
10022         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10023       }
10024       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10025       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10026     }
10027     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10028                           DAG.getBitcast(SplitVT, HiV));
10029   };
10030
10031   SDValue LoV1, HiV1, LoV2, HiV2;
10032   std::tie(LoV1, HiV1) = SplitVector(V1);
10033   std::tie(LoV2, HiV2) = SplitVector(V2);
10034
10035   // Now create two 4-way blends of these half-width vectors.
10036   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10037     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10038     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10039     for (int i = 0; i < SplitNumElements; ++i) {
10040       int M = HalfMask[i];
10041       if (M >= NumElements) {
10042         if (M >= NumElements + SplitNumElements)
10043           UseHiV2 = true;
10044         else
10045           UseLoV2 = true;
10046         V2BlendMask.push_back(M - NumElements);
10047         V1BlendMask.push_back(-1);
10048         BlendMask.push_back(SplitNumElements + i);
10049       } else if (M >= 0) {
10050         if (M >= SplitNumElements)
10051           UseHiV1 = true;
10052         else
10053           UseLoV1 = true;
10054         V2BlendMask.push_back(-1);
10055         V1BlendMask.push_back(M);
10056         BlendMask.push_back(i);
10057       } else {
10058         V2BlendMask.push_back(-1);
10059         V1BlendMask.push_back(-1);
10060         BlendMask.push_back(-1);
10061       }
10062     }
10063
10064     // Because the lowering happens after all combining takes place, we need to
10065     // manually combine these blend masks as much as possible so that we create
10066     // a minimal number of high-level vector shuffle nodes.
10067
10068     // First try just blending the halves of V1 or V2.
10069     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10070       return DAG.getUNDEF(SplitVT);
10071     if (!UseLoV2 && !UseHiV2)
10072       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10073     if (!UseLoV1 && !UseHiV1)
10074       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10075
10076     SDValue V1Blend, V2Blend;
10077     if (UseLoV1 && UseHiV1) {
10078       V1Blend =
10079         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10080     } else {
10081       // We only use half of V1 so map the usage down into the final blend mask.
10082       V1Blend = UseLoV1 ? LoV1 : HiV1;
10083       for (int i = 0; i < SplitNumElements; ++i)
10084         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10085           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10086     }
10087     if (UseLoV2 && UseHiV2) {
10088       V2Blend =
10089         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10090     } else {
10091       // We only use half of V2 so map the usage down into the final blend mask.
10092       V2Blend = UseLoV2 ? LoV2 : HiV2;
10093       for (int i = 0; i < SplitNumElements; ++i)
10094         if (BlendMask[i] >= SplitNumElements)
10095           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10096     }
10097     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10098   };
10099   SDValue Lo = HalfBlend(LoMask);
10100   SDValue Hi = HalfBlend(HiMask);
10101   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10102 }
10103
10104 /// \brief Either split a vector in halves or decompose the shuffles and the
10105 /// blend.
10106 ///
10107 /// This is provided as a good fallback for many lowerings of non-single-input
10108 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10109 /// between splitting the shuffle into 128-bit components and stitching those
10110 /// back together vs. extracting the single-input shuffles and blending those
10111 /// results.
10112 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10113                                                 SDValue V2, ArrayRef<int> Mask,
10114                                                 SelectionDAG &DAG) {
10115   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10116                                             "lower single-input shuffles as it "
10117                                             "could then recurse on itself.");
10118   int Size = Mask.size();
10119
10120   // If this can be modeled as a broadcast of two elements followed by a blend,
10121   // prefer that lowering. This is especially important because broadcasts can
10122   // often fold with memory operands.
10123   auto DoBothBroadcast = [&] {
10124     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10125     for (int M : Mask)
10126       if (M >= Size) {
10127         if (V2BroadcastIdx == -1)
10128           V2BroadcastIdx = M - Size;
10129         else if (M - Size != V2BroadcastIdx)
10130           return false;
10131       } else if (M >= 0) {
10132         if (V1BroadcastIdx == -1)
10133           V1BroadcastIdx = M;
10134         else if (M != V1BroadcastIdx)
10135           return false;
10136       }
10137     return true;
10138   };
10139   if (DoBothBroadcast())
10140     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10141                                                       DAG);
10142
10143   // If the inputs all stem from a single 128-bit lane of each input, then we
10144   // split them rather than blending because the split will decompose to
10145   // unusually few instructions.
10146   int LaneCount = VT.getSizeInBits() / 128;
10147   int LaneSize = Size / LaneCount;
10148   SmallBitVector LaneInputs[2];
10149   LaneInputs[0].resize(LaneCount, false);
10150   LaneInputs[1].resize(LaneCount, false);
10151   for (int i = 0; i < Size; ++i)
10152     if (Mask[i] >= 0)
10153       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10154   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10155     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10156
10157   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10158   // that the decomposed single-input shuffles don't end up here.
10159   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10160 }
10161
10162 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10163 /// a permutation and blend of those lanes.
10164 ///
10165 /// This essentially blends the out-of-lane inputs to each lane into the lane
10166 /// from a permuted copy of the vector. This lowering strategy results in four
10167 /// instructions in the worst case for a single-input cross lane shuffle which
10168 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10169 /// of. Special cases for each particular shuffle pattern should be handled
10170 /// prior to trying this lowering.
10171 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10172                                                        SDValue V1, SDValue V2,
10173                                                        ArrayRef<int> Mask,
10174                                                        SelectionDAG &DAG) {
10175   // FIXME: This should probably be generalized for 512-bit vectors as well.
10176   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10177   int LaneSize = Mask.size() / 2;
10178
10179   // If there are only inputs from one 128-bit lane, splitting will in fact be
10180   // less expensive. The flags track whether the given lane contains an element
10181   // that crosses to another lane.
10182   bool LaneCrossing[2] = {false, false};
10183   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10184     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10185       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10186   if (!LaneCrossing[0] || !LaneCrossing[1])
10187     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10188
10189   if (isSingleInputShuffleMask(Mask)) {
10190     SmallVector<int, 32> FlippedBlendMask;
10191     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10192       FlippedBlendMask.push_back(
10193           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10194                                   ? Mask[i]
10195                                   : Mask[i] % LaneSize +
10196                                         (i / LaneSize) * LaneSize + Size));
10197
10198     // Flip the vector, and blend the results which should now be in-lane. The
10199     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10200     // 5 for the high source. The value 3 selects the high half of source 2 and
10201     // the value 2 selects the low half of source 2. We only use source 2 to
10202     // allow folding it into a memory operand.
10203     unsigned PERMMask = 3 | 2 << 4;
10204     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10205                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10206     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10207   }
10208
10209   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10210   // will be handled by the above logic and a blend of the results, much like
10211   // other patterns in AVX.
10212   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10213 }
10214
10215 /// \brief Handle lowering 2-lane 128-bit shuffles.
10216 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10217                                         SDValue V2, ArrayRef<int> Mask,
10218                                         const X86Subtarget *Subtarget,
10219                                         SelectionDAG &DAG) {
10220   // TODO: If minimizing size and one of the inputs is a zero vector and the
10221   // the zero vector has only one use, we could use a VPERM2X128 to save the
10222   // instruction bytes needed to explicitly generate the zero vector.
10223
10224   // Blends are faster and handle all the non-lane-crossing cases.
10225   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10226                                                 Subtarget, DAG))
10227     return Blend;
10228
10229   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10230   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10231
10232   // If either input operand is a zero vector, use VPERM2X128 because its mask
10233   // allows us to replace the zero input with an implicit zero.
10234   if (!IsV1Zero && !IsV2Zero) {
10235     // Check for patterns which can be matched with a single insert of a 128-bit
10236     // subvector.
10237     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10238     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10239       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10240                                    VT.getVectorNumElements() / 2);
10241       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10242                                 DAG.getIntPtrConstant(0, DL));
10243       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10244                                 OnlyUsesV1 ? V1 : V2,
10245                                 DAG.getIntPtrConstant(0, DL));
10246       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10247     }
10248   }
10249
10250   // Otherwise form a 128-bit permutation. After accounting for undefs,
10251   // convert the 64-bit shuffle mask selection values into 128-bit
10252   // selection bits by dividing the indexes by 2 and shifting into positions
10253   // defined by a vperm2*128 instruction's immediate control byte.
10254
10255   // The immediate permute control byte looks like this:
10256   //    [1:0] - select 128 bits from sources for low half of destination
10257   //    [2]   - ignore
10258   //    [3]   - zero low half of destination
10259   //    [5:4] - select 128 bits from sources for high half of destination
10260   //    [6]   - ignore
10261   //    [7]   - zero high half of destination
10262
10263   int MaskLO = Mask[0];
10264   if (MaskLO == SM_SentinelUndef)
10265     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10266
10267   int MaskHI = Mask[2];
10268   if (MaskHI == SM_SentinelUndef)
10269     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10270
10271   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10272
10273   // If either input is a zero vector, replace it with an undef input.
10274   // Shuffle mask values <  4 are selecting elements of V1.
10275   // Shuffle mask values >= 4 are selecting elements of V2.
10276   // Adjust each half of the permute mask by clearing the half that was
10277   // selecting the zero vector and setting the zero mask bit.
10278   if (IsV1Zero) {
10279     V1 = DAG.getUNDEF(VT);
10280     if (MaskLO < 4)
10281       PermMask = (PermMask & 0xf0) | 0x08;
10282     if (MaskHI < 4)
10283       PermMask = (PermMask & 0x0f) | 0x80;
10284   }
10285   if (IsV2Zero) {
10286     V2 = DAG.getUNDEF(VT);
10287     if (MaskLO >= 4)
10288       PermMask = (PermMask & 0xf0) | 0x08;
10289     if (MaskHI >= 4)
10290       PermMask = (PermMask & 0x0f) | 0x80;
10291   }
10292
10293   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10294                      DAG.getConstant(PermMask, DL, MVT::i8));
10295 }
10296
10297 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10298 /// shuffling each lane.
10299 ///
10300 /// This will only succeed when the result of fixing the 128-bit lanes results
10301 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10302 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10303 /// the lane crosses early and then use simpler shuffles within each lane.
10304 ///
10305 /// FIXME: It might be worthwhile at some point to support this without
10306 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10307 /// in x86 only floating point has interesting non-repeating shuffles, and even
10308 /// those are still *marginally* more expensive.
10309 static SDValue lowerVectorShuffleByMerging128BitLanes(
10310     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10311     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10312   assert(!isSingleInputShuffleMask(Mask) &&
10313          "This is only useful with multiple inputs.");
10314
10315   int Size = Mask.size();
10316   int LaneSize = 128 / VT.getScalarSizeInBits();
10317   int NumLanes = Size / LaneSize;
10318   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10319
10320   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10321   // check whether the in-128-bit lane shuffles share a repeating pattern.
10322   SmallVector<int, 4> Lanes;
10323   Lanes.resize(NumLanes, -1);
10324   SmallVector<int, 4> InLaneMask;
10325   InLaneMask.resize(LaneSize, -1);
10326   for (int i = 0; i < Size; ++i) {
10327     if (Mask[i] < 0)
10328       continue;
10329
10330     int j = i / LaneSize;
10331
10332     if (Lanes[j] < 0) {
10333       // First entry we've seen for this lane.
10334       Lanes[j] = Mask[i] / LaneSize;
10335     } else if (Lanes[j] != Mask[i] / LaneSize) {
10336       // This doesn't match the lane selected previously!
10337       return SDValue();
10338     }
10339
10340     // Check that within each lane we have a consistent shuffle mask.
10341     int k = i % LaneSize;
10342     if (InLaneMask[k] < 0) {
10343       InLaneMask[k] = Mask[i] % LaneSize;
10344     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10345       // This doesn't fit a repeating in-lane mask.
10346       return SDValue();
10347     }
10348   }
10349
10350   // First shuffle the lanes into place.
10351   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10352                                 VT.getSizeInBits() / 64);
10353   SmallVector<int, 8> LaneMask;
10354   LaneMask.resize(NumLanes * 2, -1);
10355   for (int i = 0; i < NumLanes; ++i)
10356     if (Lanes[i] >= 0) {
10357       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10358       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10359     }
10360
10361   V1 = DAG.getBitcast(LaneVT, V1);
10362   V2 = DAG.getBitcast(LaneVT, V2);
10363   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10364
10365   // Cast it back to the type we actually want.
10366   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10367
10368   // Now do a simple shuffle that isn't lane crossing.
10369   SmallVector<int, 8> NewMask;
10370   NewMask.resize(Size, -1);
10371   for (int i = 0; i < Size; ++i)
10372     if (Mask[i] >= 0)
10373       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10374   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10375          "Must not introduce lane crosses at this point!");
10376
10377   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10378 }
10379
10380 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10381 /// This allows for fast cases such as subvector extraction/insertion
10382 /// or shuffling smaller vector types which can lower more efficiently.
10383 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10384                                                SDValue V2, ArrayRef<int> Mask,
10385                                                const X86Subtarget *Subtarget,
10386                                                SelectionDAG &DAG) {
10387   assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10388
10389   unsigned NumElts = VT.getVectorNumElements();
10390   unsigned HalfNumElts = NumElts / 2;
10391   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10392
10393   bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10394   bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10395   if (!UndefLower && !UndefUpper)
10396     return SDValue();
10397
10398   // Upper half is undef and lower half is whole upper subvector.
10399   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10400   if (UndefUpper &&
10401       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10402     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10403                              DAG.getIntPtrConstant(HalfNumElts, DL));
10404     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10405                        DAG.getIntPtrConstant(0, DL));
10406   }
10407
10408   // Lower half is undef and upper half is whole lower subvector.
10409   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10410   if (UndefLower &&
10411       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10412     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10413                              DAG.getIntPtrConstant(0, DL));
10414     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10415                        DAG.getIntPtrConstant(HalfNumElts, DL));
10416   }
10417
10418   // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10419   if (UndefLower && Subtarget->hasAVX2() &&
10420       (VT == MVT::v4f64 || VT == MVT::v4i64))
10421     return SDValue();
10422
10423   // If the shuffle only uses the lower halves of the input operands,
10424   // then extract them and perform the 'half' shuffle at half width.
10425   // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10426   int HalfIdx1 = -1, HalfIdx2 = -1;
10427   SmallVector<int, 8> HalfMask;
10428   unsigned Offset = UndefLower ? HalfNumElts : 0;
10429   for (unsigned i = 0; i != HalfNumElts; ++i) {
10430     int M = Mask[i + Offset];
10431     if (M < 0) {
10432       HalfMask.push_back(M);
10433       continue;
10434     }
10435
10436     // Determine which of the 4 half vectors this element is from.
10437     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10438     int HalfIdx = M / HalfNumElts;
10439
10440     // Only shuffle using the lower halves of the inputs.
10441     // TODO: Investigate usefulness of shuffling with upper halves.
10442     if (HalfIdx != 0 && HalfIdx != 2)
10443       return SDValue();
10444
10445     // Determine the element index into its half vector source.
10446     int HalfElt = M % HalfNumElts;
10447
10448     // We can shuffle with up to 2 half vectors, set the new 'half'
10449     // shuffle mask accordingly.
10450     if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10451       HalfMask.push_back(HalfElt);
10452       HalfIdx1 = HalfIdx;
10453       continue;
10454     }
10455     if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10456       HalfMask.push_back(HalfElt + HalfNumElts);
10457       HalfIdx2 = HalfIdx;
10458       continue;
10459     }
10460
10461     // Too many half vectors referenced.
10462     return SDValue();
10463   }
10464   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10465
10466   auto GetHalfVector = [&](int HalfIdx) {
10467     if (HalfIdx < 0)
10468       return DAG.getUNDEF(HalfVT);
10469     SDValue V = (HalfIdx < 2 ? V1 : V2);
10470     HalfIdx = (HalfIdx % 2) * HalfNumElts;
10471     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10472                        DAG.getIntPtrConstant(HalfIdx, DL));
10473   };
10474
10475   SDValue Half1 = GetHalfVector(HalfIdx1);
10476   SDValue Half2 = GetHalfVector(HalfIdx2);
10477   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10478   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10479                      DAG.getIntPtrConstant(Offset, DL));
10480 }
10481
10482 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10483 /// given mask.
10484 ///
10485 /// This returns true if the elements from a particular input are already in the
10486 /// slot required by the given mask and require no permutation.
10487 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10488   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10489   int Size = Mask.size();
10490   for (int i = 0; i < Size; ++i)
10491     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10492       return false;
10493
10494   return true;
10495 }
10496
10497 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10498                                             ArrayRef<int> Mask, SDValue V1,
10499                                             SDValue V2, SelectionDAG &DAG) {
10500
10501   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10502   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10503   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10504   int NumElts = VT.getVectorNumElements();
10505   bool ShufpdMask = true;
10506   bool CommutableMask = true;
10507   unsigned Immediate = 0;
10508   for (int i = 0; i < NumElts; ++i) {
10509     if (Mask[i] < 0)
10510       continue;
10511     int Val = (i & 6) + NumElts * (i & 1);
10512     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10513     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10514       ShufpdMask = false;
10515     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10516       CommutableMask = false;
10517     Immediate |= (Mask[i] % 2) << i;
10518   }
10519   if (ShufpdMask)
10520     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10521                        DAG.getConstant(Immediate, DL, MVT::i8));
10522   if (CommutableMask)
10523     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10524                        DAG.getConstant(Immediate, DL, MVT::i8));
10525   return SDValue();
10526 }
10527
10528 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10529 ///
10530 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10531 /// isn't available.
10532 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10533                                        const X86Subtarget *Subtarget,
10534                                        SelectionDAG &DAG) {
10535   SDLoc DL(Op);
10536   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10537   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10538   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10539   ArrayRef<int> Mask = SVOp->getMask();
10540   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10541
10542   SmallVector<int, 4> WidenedMask;
10543   if (canWidenShuffleElements(Mask, WidenedMask))
10544     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10545                                     DAG);
10546
10547   if (isSingleInputShuffleMask(Mask)) {
10548     // Check for being able to broadcast a single element.
10549     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10550                                                           Mask, Subtarget, DAG))
10551       return Broadcast;
10552
10553     // Use low duplicate instructions for masks that match their pattern.
10554     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10555       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10556
10557     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10558       // Non-half-crossing single input shuffles can be lowerid with an
10559       // interleaved permutation.
10560       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10561                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10562       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10563                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10564     }
10565
10566     // With AVX2 we have direct support for this permutation.
10567     if (Subtarget->hasAVX2())
10568       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10569                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10570
10571     // Otherwise, fall back.
10572     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10573                                                    DAG);
10574   }
10575
10576   // Use dedicated unpack instructions for masks that match their pattern.
10577   if (SDValue V =
10578           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10579     return V;
10580
10581   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10582                                                 Subtarget, DAG))
10583     return Blend;
10584
10585   // Check if the blend happens to exactly fit that of SHUFPD.
10586   if (SDValue Op =
10587       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10588     return Op;
10589
10590   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10591   // shuffle. However, if we have AVX2 and either inputs are already in place,
10592   // we will be able to shuffle even across lanes the other input in a single
10593   // instruction so skip this pattern.
10594   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10595                                  isShuffleMaskInputInPlace(1, Mask))))
10596     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10597             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10598       return Result;
10599
10600   // If we have AVX2 then we always want to lower with a blend because an v4 we
10601   // can fully permute the elements.
10602   if (Subtarget->hasAVX2())
10603     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10604                                                       Mask, DAG);
10605
10606   // Otherwise fall back on generic lowering.
10607   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10608 }
10609
10610 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10611 ///
10612 /// This routine is only called when we have AVX2 and thus a reasonable
10613 /// instruction set for v4i64 shuffling..
10614 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10615                                        const X86Subtarget *Subtarget,
10616                                        SelectionDAG &DAG) {
10617   SDLoc DL(Op);
10618   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10619   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10620   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10621   ArrayRef<int> Mask = SVOp->getMask();
10622   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10623   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10624
10625   SmallVector<int, 4> WidenedMask;
10626   if (canWidenShuffleElements(Mask, WidenedMask))
10627     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10628                                     DAG);
10629
10630   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10631                                                 Subtarget, DAG))
10632     return Blend;
10633
10634   // Check for being able to broadcast a single element.
10635   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10636                                                         Mask, Subtarget, DAG))
10637     return Broadcast;
10638
10639   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10640   // use lower latency instructions that will operate on both 128-bit lanes.
10641   SmallVector<int, 2> RepeatedMask;
10642   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10643     if (isSingleInputShuffleMask(Mask)) {
10644       int PSHUFDMask[] = {-1, -1, -1, -1};
10645       for (int i = 0; i < 2; ++i)
10646         if (RepeatedMask[i] >= 0) {
10647           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10648           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10649         }
10650       return DAG.getBitcast(
10651           MVT::v4i64,
10652           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10653                       DAG.getBitcast(MVT::v8i32, V1),
10654                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10655     }
10656   }
10657
10658   // AVX2 provides a direct instruction for permuting a single input across
10659   // lanes.
10660   if (isSingleInputShuffleMask(Mask))
10661     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10662                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10663
10664   // Try to use shift instructions.
10665   if (SDValue Shift =
10666           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10667     return Shift;
10668
10669   // Use dedicated unpack instructions for masks that match their pattern.
10670   if (SDValue V =
10671           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10672     return V;
10673
10674   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10675   // shuffle. However, if we have AVX2 and either inputs are already in place,
10676   // we will be able to shuffle even across lanes the other input in a single
10677   // instruction so skip this pattern.
10678   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10679                                  isShuffleMaskInputInPlace(1, Mask))))
10680     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10681             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10682       return Result;
10683
10684   // Otherwise fall back on generic blend lowering.
10685   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10686                                                     Mask, DAG);
10687 }
10688
10689 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10690 ///
10691 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10692 /// isn't available.
10693 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10694                                        const X86Subtarget *Subtarget,
10695                                        SelectionDAG &DAG) {
10696   SDLoc DL(Op);
10697   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10698   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10699   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10700   ArrayRef<int> Mask = SVOp->getMask();
10701   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10702
10703   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10704                                                 Subtarget, DAG))
10705     return Blend;
10706
10707   // Check for being able to broadcast a single element.
10708   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10709                                                         Mask, Subtarget, DAG))
10710     return Broadcast;
10711
10712   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10713   // options to efficiently lower the shuffle.
10714   SmallVector<int, 4> RepeatedMask;
10715   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10716     assert(RepeatedMask.size() == 4 &&
10717            "Repeated masks must be half the mask width!");
10718
10719     // Use even/odd duplicate instructions for masks that match their pattern.
10720     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10721       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10722     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10723       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10724
10725     if (isSingleInputShuffleMask(Mask))
10726       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10727                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10728
10729     // Use dedicated unpack instructions for masks that match their pattern.
10730     if (SDValue V =
10731             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10732       return V;
10733
10734     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10735     // have already handled any direct blends. We also need to squash the
10736     // repeated mask into a simulated v4f32 mask.
10737     for (int i = 0; i < 4; ++i)
10738       if (RepeatedMask[i] >= 8)
10739         RepeatedMask[i] -= 4;
10740     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10741   }
10742
10743   // If we have a single input shuffle with different shuffle patterns in the
10744   // two 128-bit lanes use the variable mask to VPERMILPS.
10745   if (isSingleInputShuffleMask(Mask)) {
10746     SDValue VPermMask[8];
10747     for (int i = 0; i < 8; ++i)
10748       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10749                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10750     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10751       return DAG.getNode(
10752           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10753           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10754
10755     if (Subtarget->hasAVX2())
10756       return DAG.getNode(
10757           X86ISD::VPERMV, DL, MVT::v8f32,
10758           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10759
10760     // Otherwise, fall back.
10761     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10762                                                    DAG);
10763   }
10764
10765   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10766   // shuffle.
10767   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10768           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10769     return Result;
10770
10771   // If we have AVX2 then we always want to lower with a blend because at v8 we
10772   // can fully permute the elements.
10773   if (Subtarget->hasAVX2())
10774     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10775                                                       Mask, DAG);
10776
10777   // Otherwise fall back on generic lowering.
10778   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10779 }
10780
10781 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10782 ///
10783 /// This routine is only called when we have AVX2 and thus a reasonable
10784 /// instruction set for v8i32 shuffling..
10785 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10786                                        const X86Subtarget *Subtarget,
10787                                        SelectionDAG &DAG) {
10788   SDLoc DL(Op);
10789   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10790   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10791   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10792   ArrayRef<int> Mask = SVOp->getMask();
10793   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10794   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10795
10796   // Whenever we can lower this as a zext, that instruction is strictly faster
10797   // than any alternative. It also allows us to fold memory operands into the
10798   // shuffle in many cases.
10799   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10800                                                          Mask, Subtarget, DAG))
10801     return ZExt;
10802
10803   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10804                                                 Subtarget, DAG))
10805     return Blend;
10806
10807   // Check for being able to broadcast a single element.
10808   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10809                                                         Mask, Subtarget, DAG))
10810     return Broadcast;
10811
10812   // If the shuffle mask is repeated in each 128-bit lane we can use more
10813   // efficient instructions that mirror the shuffles across the two 128-bit
10814   // lanes.
10815   SmallVector<int, 4> RepeatedMask;
10816   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10817     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10818     if (isSingleInputShuffleMask(Mask))
10819       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10820                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10821
10822     // Use dedicated unpack instructions for masks that match their pattern.
10823     if (SDValue V =
10824             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10825       return V;
10826   }
10827
10828   // Try to use shift instructions.
10829   if (SDValue Shift =
10830           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10831     return Shift;
10832
10833   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10834           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10835     return Rotate;
10836
10837   // If the shuffle patterns aren't repeated but it is a single input, directly
10838   // generate a cross-lane VPERMD instruction.
10839   if (isSingleInputShuffleMask(Mask)) {
10840     SDValue VPermMask[8];
10841     for (int i = 0; i < 8; ++i)
10842       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10843                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10844     return DAG.getNode(
10845         X86ISD::VPERMV, DL, MVT::v8i32,
10846         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10847   }
10848
10849   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10850   // shuffle.
10851   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10852           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10853     return Result;
10854
10855   // Otherwise fall back on generic blend lowering.
10856   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10857                                                     Mask, DAG);
10858 }
10859
10860 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10861 ///
10862 /// This routine is only called when we have AVX2 and thus a reasonable
10863 /// instruction set for v16i16 shuffling..
10864 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10865                                         const X86Subtarget *Subtarget,
10866                                         SelectionDAG &DAG) {
10867   SDLoc DL(Op);
10868   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10869   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10870   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10871   ArrayRef<int> Mask = SVOp->getMask();
10872   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10873   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10874
10875   // Whenever we can lower this as a zext, that instruction is strictly faster
10876   // than any alternative. It also allows us to fold memory operands into the
10877   // shuffle in many cases.
10878   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10879                                                          Mask, Subtarget, DAG))
10880     return ZExt;
10881
10882   // Check for being able to broadcast a single element.
10883   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10884                                                         Mask, Subtarget, DAG))
10885     return Broadcast;
10886
10887   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10888                                                 Subtarget, DAG))
10889     return Blend;
10890
10891   // Use dedicated unpack instructions for masks that match their pattern.
10892   if (SDValue V =
10893           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10894     return V;
10895
10896   // Try to use shift instructions.
10897   if (SDValue Shift =
10898           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10899     return Shift;
10900
10901   // Try to use byte rotation instructions.
10902   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10903           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10904     return Rotate;
10905
10906   if (isSingleInputShuffleMask(Mask)) {
10907     // There are no generalized cross-lane shuffle operations available on i16
10908     // element types.
10909     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10910       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10911                                                      Mask, DAG);
10912
10913     SmallVector<int, 8> RepeatedMask;
10914     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10915       // As this is a single-input shuffle, the repeated mask should be
10916       // a strictly valid v8i16 mask that we can pass through to the v8i16
10917       // lowering to handle even the v16 case.
10918       return lowerV8I16GeneralSingleInputVectorShuffle(
10919           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10920     }
10921
10922     SDValue PSHUFBMask[32];
10923     for (int i = 0; i < 16; ++i) {
10924       if (Mask[i] == -1) {
10925         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10926         continue;
10927       }
10928
10929       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10930       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10931       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10932       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10933     }
10934     return DAG.getBitcast(MVT::v16i16,
10935                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10936                                       DAG.getBitcast(MVT::v32i8, V1),
10937                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10938                                                   MVT::v32i8, PSHUFBMask)));
10939   }
10940
10941   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10942   // shuffle.
10943   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10944           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10945     return Result;
10946
10947   // Otherwise fall back on generic lowering.
10948   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10949 }
10950
10951 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10952 ///
10953 /// This routine is only called when we have AVX2 and thus a reasonable
10954 /// instruction set for v32i8 shuffling..
10955 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10956                                        const X86Subtarget *Subtarget,
10957                                        SelectionDAG &DAG) {
10958   SDLoc DL(Op);
10959   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10960   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10961   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10962   ArrayRef<int> Mask = SVOp->getMask();
10963   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10964   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10965
10966   // Whenever we can lower this as a zext, that instruction is strictly faster
10967   // than any alternative. It also allows us to fold memory operands into the
10968   // shuffle in many cases.
10969   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10970                                                          Mask, Subtarget, DAG))
10971     return ZExt;
10972
10973   // Check for being able to broadcast a single element.
10974   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10975                                                         Mask, Subtarget, DAG))
10976     return Broadcast;
10977
10978   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10979                                                 Subtarget, DAG))
10980     return Blend;
10981
10982   // Use dedicated unpack instructions for masks that match their pattern.
10983   if (SDValue V =
10984           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10985     return V;
10986
10987   // Try to use shift instructions.
10988   if (SDValue Shift =
10989           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10990     return Shift;
10991
10992   // Try to use byte rotation instructions.
10993   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10994           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10995     return Rotate;
10996
10997   if (isSingleInputShuffleMask(Mask)) {
10998     // There are no generalized cross-lane shuffle operations available on i8
10999     // element types.
11000     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
11001       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
11002                                                      Mask, DAG);
11003
11004     SDValue PSHUFBMask[32];
11005     for (int i = 0; i < 32; ++i)
11006       PSHUFBMask[i] =
11007           Mask[i] < 0
11008               ? DAG.getUNDEF(MVT::i8)
11009               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
11010                                 MVT::i8);
11011
11012     return DAG.getNode(
11013         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11014         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11015   }
11016
11017   // Try to simplify this by merging 128-bit lanes to enable a lane-based
11018   // shuffle.
11019   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11020           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11021     return Result;
11022
11023   // Otherwise fall back on generic lowering.
11024   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11025 }
11026
11027 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11028 ///
11029 /// This routine either breaks down the specific type of a 256-bit x86 vector
11030 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11031 /// together based on the available instructions.
11032 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11033                                         MVT VT, const X86Subtarget *Subtarget,
11034                                         SelectionDAG &DAG) {
11035   SDLoc DL(Op);
11036   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11037   ArrayRef<int> Mask = SVOp->getMask();
11038
11039   // If we have a single input to the zero element, insert that into V1 if we
11040   // can do so cheaply.
11041   int NumElts = VT.getVectorNumElements();
11042   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11043     return M >= NumElts;
11044   });
11045
11046   if (NumV2Elements == 1 && Mask[0] >= NumElts)
11047     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11048                               DL, VT, V1, V2, Mask, Subtarget, DAG))
11049       return Insertion;
11050
11051   // Handle special cases where the lower or upper half is UNDEF.
11052   if (SDValue V =
11053           lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11054     return V;
11055
11056   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11057   // can check for those subtargets here and avoid much of the subtarget
11058   // querying in the per-vector-type lowering routines. With AVX1 we have
11059   // essentially *zero* ability to manipulate a 256-bit vector with integer
11060   // types. Since we'll use floating point types there eventually, just
11061   // immediately cast everything to a float and operate entirely in that domain.
11062   if (VT.isInteger() && !Subtarget->hasAVX2()) {
11063     int ElementBits = VT.getScalarSizeInBits();
11064     if (ElementBits < 32)
11065       // No floating point type available, decompose into 128-bit vectors.
11066       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11067
11068     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11069                                 VT.getVectorNumElements());
11070     V1 = DAG.getBitcast(FpVT, V1);
11071     V2 = DAG.getBitcast(FpVT, V2);
11072     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11073   }
11074
11075   switch (VT.SimpleTy) {
11076   case MVT::v4f64:
11077     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11078   case MVT::v4i64:
11079     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11080   case MVT::v8f32:
11081     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11082   case MVT::v8i32:
11083     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11084   case MVT::v16i16:
11085     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11086   case MVT::v32i8:
11087     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11088
11089   default:
11090     llvm_unreachable("Not a valid 256-bit x86 vector type!");
11091   }
11092 }
11093
11094 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11095 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11096                                         ArrayRef<int> Mask,
11097                                         SDValue V1, SDValue V2,
11098                                         SelectionDAG &DAG) {
11099   assert(VT.getScalarSizeInBits() == 64 &&
11100          "Unexpected element type size for 128bit shuffle.");
11101
11102   // To handle 256 bit vector requires VLX and most probably
11103   // function lowerV2X128VectorShuffle() is better solution.
11104   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11105
11106   SmallVector<int, 4> WidenedMask;
11107   if (!canWidenShuffleElements(Mask, WidenedMask))
11108     return SDValue();
11109
11110   // Form a 128-bit permutation.
11111   // Convert the 64-bit shuffle mask selection values into 128-bit selection
11112   // bits defined by a vshuf64x2 instruction's immediate control byte.
11113   unsigned PermMask = 0, Imm = 0;
11114   unsigned ControlBitsNum = WidenedMask.size() / 2;
11115
11116   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11117     if (WidenedMask[i] == SM_SentinelZero)
11118       return SDValue();
11119
11120     // Use first element in place of undef mask.
11121     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11122     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11123   }
11124
11125   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11126                      DAG.getConstant(PermMask, DL, MVT::i8));
11127 }
11128
11129 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11130                                            ArrayRef<int> Mask, SDValue V1,
11131                                            SDValue V2, SelectionDAG &DAG) {
11132
11133   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11134
11135   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11136   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11137
11138   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11139   if (isSingleInputShuffleMask(Mask))
11140     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11141
11142   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11143 }
11144
11145 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11146 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11147                                        const X86Subtarget *Subtarget,
11148                                        SelectionDAG &DAG) {
11149   SDLoc DL(Op);
11150   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11151   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11152   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11153   ArrayRef<int> Mask = SVOp->getMask();
11154   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11155
11156   if (SDValue Shuf128 =
11157           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11158     return Shuf128;
11159
11160   if (SDValue Unpck =
11161           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11162     return Unpck;
11163
11164   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11165 }
11166
11167 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11168 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11169                                         const X86Subtarget *Subtarget,
11170                                         SelectionDAG &DAG) {
11171   SDLoc DL(Op);
11172   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11173   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11174   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11175   ArrayRef<int> Mask = SVOp->getMask();
11176   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11177
11178   if (SDValue Unpck =
11179           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11180     return Unpck;
11181
11182   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11183 }
11184
11185 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11186 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11187                                        const X86Subtarget *Subtarget,
11188                                        SelectionDAG &DAG) {
11189   SDLoc DL(Op);
11190   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11191   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11192   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11193   ArrayRef<int> Mask = SVOp->getMask();
11194   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11195
11196   if (SDValue Shuf128 =
11197           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11198     return Shuf128;
11199
11200   if (SDValue Unpck =
11201           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11202     return Unpck;
11203
11204   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11205 }
11206
11207 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11208 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11209                                         const X86Subtarget *Subtarget,
11210                                         SelectionDAG &DAG) {
11211   SDLoc DL(Op);
11212   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11213   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11214   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11215   ArrayRef<int> Mask = SVOp->getMask();
11216   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11217
11218   if (SDValue Unpck =
11219           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11220     return Unpck;
11221
11222   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11223 }
11224
11225 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11226 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11227                                         const X86Subtarget *Subtarget,
11228                                         SelectionDAG &DAG) {
11229   SDLoc DL(Op);
11230   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11231   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11232   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11233   ArrayRef<int> Mask = SVOp->getMask();
11234   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11235   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11236
11237   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11238 }
11239
11240 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11241 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11242                                        const X86Subtarget *Subtarget,
11243                                        SelectionDAG &DAG) {
11244   SDLoc DL(Op);
11245   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11246   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11247   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11248   ArrayRef<int> Mask = SVOp->getMask();
11249   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11250   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11251
11252   // FIXME: Implement direct support for this type!
11253   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11254 }
11255
11256 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11257 ///
11258 /// This routine either breaks down the specific type of a 512-bit x86 vector
11259 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11260 /// together based on the available instructions.
11261 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11262                                         MVT VT, const X86Subtarget *Subtarget,
11263                                         SelectionDAG &DAG) {
11264   SDLoc DL(Op);
11265   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11266   ArrayRef<int> Mask = SVOp->getMask();
11267   assert(Subtarget->hasAVX512() &&
11268          "Cannot lower 512-bit vectors w/ basic ISA!");
11269
11270   // Check for being able to broadcast a single element.
11271   if (SDValue Broadcast =
11272           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11273     return Broadcast;
11274
11275   // Dispatch to each element type for lowering. If we don't have supprot for
11276   // specific element type shuffles at 512 bits, immediately split them and
11277   // lower them. Each lowering routine of a given type is allowed to assume that
11278   // the requisite ISA extensions for that element type are available.
11279   switch (VT.SimpleTy) {
11280   case MVT::v8f64:
11281     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11282   case MVT::v16f32:
11283     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11284   case MVT::v8i64:
11285     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11286   case MVT::v16i32:
11287     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11288   case MVT::v32i16:
11289     if (Subtarget->hasBWI())
11290       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11291     break;
11292   case MVT::v64i8:
11293     if (Subtarget->hasBWI())
11294       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11295     break;
11296
11297   default:
11298     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11299   }
11300
11301   // Otherwise fall back on splitting.
11302   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11303 }
11304
11305 // Lower vXi1 vector shuffles.
11306 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11307 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11308 // vector, shuffle and then truncate it back.
11309 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11310                                       MVT VT, const X86Subtarget *Subtarget,
11311                                       SelectionDAG &DAG) {
11312   SDLoc DL(Op);
11313   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11314   ArrayRef<int> Mask = SVOp->getMask();
11315   assert(Subtarget->hasAVX512() &&
11316          "Cannot lower 512-bit vectors w/o basic ISA!");
11317   MVT ExtVT;
11318   switch (VT.SimpleTy) {
11319   default:
11320     llvm_unreachable("Expected a vector of i1 elements");
11321   case MVT::v2i1:
11322     ExtVT = MVT::v2i64;
11323     break;
11324   case MVT::v4i1:
11325     ExtVT = MVT::v4i32;
11326     break;
11327   case MVT::v8i1:
11328     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11329     break;
11330   case MVT::v16i1:
11331     ExtVT = MVT::v16i32;
11332     break;
11333   case MVT::v32i1:
11334     ExtVT = MVT::v32i16;
11335     break;
11336   case MVT::v64i1:
11337     ExtVT = MVT::v64i8;
11338     break;
11339   }
11340
11341   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11342     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11343   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11344     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11345   else
11346     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11347
11348   if (V2.isUndef())
11349     V2 = DAG.getUNDEF(ExtVT);
11350   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11351     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11352   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11353     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11354   else
11355     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11356   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11357                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11358 }
11359 /// \brief Top-level lowering for x86 vector shuffles.
11360 ///
11361 /// This handles decomposition, canonicalization, and lowering of all x86
11362 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11363 /// above in helper routines. The canonicalization attempts to widen shuffles
11364 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11365 /// s.t. only one of the two inputs needs to be tested, etc.
11366 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11367                                   SelectionDAG &DAG) {
11368   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11369   ArrayRef<int> Mask = SVOp->getMask();
11370   SDValue V1 = Op.getOperand(0);
11371   SDValue V2 = Op.getOperand(1);
11372   MVT VT = Op.getSimpleValueType();
11373   int NumElements = VT.getVectorNumElements();
11374   SDLoc dl(Op);
11375   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11376
11377   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11378          "Can't lower MMX shuffles");
11379
11380   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11381   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11382   if (V1IsUndef && V2IsUndef)
11383     return DAG.getUNDEF(VT);
11384
11385   // When we create a shuffle node we put the UNDEF node to second operand,
11386   // but in some cases the first operand may be transformed to UNDEF.
11387   // In this case we should just commute the node.
11388   if (V1IsUndef)
11389     return DAG.getCommutedVectorShuffle(*SVOp);
11390
11391   // Check for non-undef masks pointing at an undef vector and make the masks
11392   // undef as well. This makes it easier to match the shuffle based solely on
11393   // the mask.
11394   if (V2IsUndef)
11395     for (int M : Mask)
11396       if (M >= NumElements) {
11397         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11398         for (int &M : NewMask)
11399           if (M >= NumElements)
11400             M = -1;
11401         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11402       }
11403
11404   // We actually see shuffles that are entirely re-arrangements of a set of
11405   // zero inputs. This mostly happens while decomposing complex shuffles into
11406   // simple ones. Directly lower these as a buildvector of zeros.
11407   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11408   if (Zeroable.all())
11409     return getZeroVector(VT, Subtarget, DAG, dl);
11410
11411   // Try to collapse shuffles into using a vector type with fewer elements but
11412   // wider element types. We cap this to not form integers or floating point
11413   // elements wider than 64 bits, but it might be interesting to form i128
11414   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11415   SmallVector<int, 16> WidenedMask;
11416   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11417       canWidenShuffleElements(Mask, WidenedMask)) {
11418     MVT NewEltVT = VT.isFloatingPoint()
11419                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11420                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11421     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11422     // Make sure that the new vector type is legal. For example, v2f64 isn't
11423     // legal on SSE1.
11424     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11425       V1 = DAG.getBitcast(NewVT, V1);
11426       V2 = DAG.getBitcast(NewVT, V2);
11427       return DAG.getBitcast(
11428           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11429     }
11430   }
11431
11432   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11433   for (int M : SVOp->getMask())
11434     if (M < 0)
11435       ++NumUndefElements;
11436     else if (M < NumElements)
11437       ++NumV1Elements;
11438     else
11439       ++NumV2Elements;
11440
11441   // Commute the shuffle as needed such that more elements come from V1 than
11442   // V2. This allows us to match the shuffle pattern strictly on how many
11443   // elements come from V1 without handling the symmetric cases.
11444   if (NumV2Elements > NumV1Elements)
11445     return DAG.getCommutedVectorShuffle(*SVOp);
11446
11447   // When the number of V1 and V2 elements are the same, try to minimize the
11448   // number of uses of V2 in the low half of the vector. When that is tied,
11449   // ensure that the sum of indices for V1 is equal to or lower than the sum
11450   // indices for V2. When those are equal, try to ensure that the number of odd
11451   // indices for V1 is lower than the number of odd indices for V2.
11452   if (NumV1Elements == NumV2Elements) {
11453     int LowV1Elements = 0, LowV2Elements = 0;
11454     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11455       if (M >= NumElements)
11456         ++LowV2Elements;
11457       else if (M >= 0)
11458         ++LowV1Elements;
11459     if (LowV2Elements > LowV1Elements) {
11460       return DAG.getCommutedVectorShuffle(*SVOp);
11461     } else if (LowV2Elements == LowV1Elements) {
11462       int SumV1Indices = 0, SumV2Indices = 0;
11463       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11464         if (SVOp->getMask()[i] >= NumElements)
11465           SumV2Indices += i;
11466         else if (SVOp->getMask()[i] >= 0)
11467           SumV1Indices += i;
11468       if (SumV2Indices < SumV1Indices) {
11469         return DAG.getCommutedVectorShuffle(*SVOp);
11470       } else if (SumV2Indices == SumV1Indices) {
11471         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11472         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11473           if (SVOp->getMask()[i] >= NumElements)
11474             NumV2OddIndices += i % 2;
11475           else if (SVOp->getMask()[i] >= 0)
11476             NumV1OddIndices += i % 2;
11477         if (NumV2OddIndices < NumV1OddIndices)
11478           return DAG.getCommutedVectorShuffle(*SVOp);
11479       }
11480     }
11481   }
11482
11483   // For each vector width, delegate to a specialized lowering routine.
11484   if (VT.is128BitVector())
11485     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11486
11487   if (VT.is256BitVector())
11488     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11489
11490   if (VT.is512BitVector())
11491     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11492
11493   if (Is1BitVector)
11494     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11495   llvm_unreachable("Unimplemented!");
11496 }
11497
11498 // This function assumes its argument is a BUILD_VECTOR of constants or
11499 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11500 // true.
11501 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11502                                     unsigned &MaskValue) {
11503   MaskValue = 0;
11504   unsigned NumElems = BuildVector->getNumOperands();
11505
11506   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11507   // We don't handle the >2 lanes case right now.
11508   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11509   if (NumLanes > 2)
11510     return false;
11511
11512   unsigned NumElemsInLane = NumElems / NumLanes;
11513
11514   // Blend for v16i16 should be symmetric for the both lanes.
11515   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11516     SDValue EltCond = BuildVector->getOperand(i);
11517     SDValue SndLaneEltCond =
11518         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11519
11520     int Lane1Cond = -1, Lane2Cond = -1;
11521     if (isa<ConstantSDNode>(EltCond))
11522       Lane1Cond = !isNullConstant(EltCond);
11523     if (isa<ConstantSDNode>(SndLaneEltCond))
11524       Lane2Cond = !isNullConstant(SndLaneEltCond);
11525
11526     unsigned LaneMask = 0;
11527     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11528       // Lane1Cond != 0, means we want the first argument.
11529       // Lane1Cond == 0, means we want the second argument.
11530       // The encoding of this argument is 0 for the first argument, 1
11531       // for the second. Therefore, invert the condition.
11532       LaneMask = !Lane1Cond << i;
11533     else if (Lane1Cond < 0)
11534       LaneMask = !Lane2Cond << i;
11535     else
11536       return false;
11537
11538     MaskValue |= LaneMask;
11539     if (NumLanes == 2)
11540       MaskValue |= LaneMask << NumElemsInLane;
11541   }
11542   return true;
11543 }
11544
11545 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11546 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11547                                            const X86Subtarget *Subtarget,
11548                                            SelectionDAG &DAG) {
11549   SDValue Cond = Op.getOperand(0);
11550   SDValue LHS = Op.getOperand(1);
11551   SDValue RHS = Op.getOperand(2);
11552   SDLoc dl(Op);
11553   MVT VT = Op.getSimpleValueType();
11554
11555   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11556     return SDValue();
11557   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11558
11559   // Only non-legal VSELECTs reach this lowering, convert those into generic
11560   // shuffles and re-use the shuffle lowering path for blends.
11561   SmallVector<int, 32> Mask;
11562   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11563     SDValue CondElt = CondBV->getOperand(i);
11564     Mask.push_back(
11565         isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11566                                      : -1);
11567   }
11568   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11569 }
11570
11571 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11572   // A vselect where all conditions and data are constants can be optimized into
11573   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11574   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11575       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11576       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11577     return SDValue();
11578
11579   // Try to lower this to a blend-style vector shuffle. This can handle all
11580   // constant condition cases.
11581   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11582     return BlendOp;
11583
11584   // Variable blends are only legal from SSE4.1 onward.
11585   if (!Subtarget->hasSSE41())
11586     return SDValue();
11587
11588   // Only some types will be legal on some subtargets. If we can emit a legal
11589   // VSELECT-matching blend, return Op, and but if we need to expand, return
11590   // a null value.
11591   switch (Op.getSimpleValueType().SimpleTy) {
11592   default:
11593     // Most of the vector types have blends past SSE4.1.
11594     return Op;
11595
11596   case MVT::v32i8:
11597     // The byte blends for AVX vectors were introduced only in AVX2.
11598     if (Subtarget->hasAVX2())
11599       return Op;
11600
11601     return SDValue();
11602
11603   case MVT::v8i16:
11604   case MVT::v16i16:
11605     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11606     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11607       return Op;
11608
11609     // FIXME: We should custom lower this by fixing the condition and using i8
11610     // blends.
11611     return SDValue();
11612   }
11613 }
11614
11615 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11616   MVT VT = Op.getSimpleValueType();
11617   SDLoc dl(Op);
11618
11619   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11620     return SDValue();
11621
11622   if (VT.getSizeInBits() == 8) {
11623     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11624                                   Op.getOperand(0), Op.getOperand(1));
11625     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11626                                   DAG.getValueType(VT));
11627     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11628   }
11629
11630   if (VT.getSizeInBits() == 16) {
11631     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11632     if (isNullConstant(Op.getOperand(1)))
11633       return DAG.getNode(
11634           ISD::TRUNCATE, dl, MVT::i16,
11635           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11636                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11637                       Op.getOperand(1)));
11638     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11639                                   Op.getOperand(0), Op.getOperand(1));
11640     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11641                                   DAG.getValueType(VT));
11642     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11643   }
11644
11645   if (VT == MVT::f32) {
11646     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11647     // the result back to FR32 register. It's only worth matching if the
11648     // result has a single use which is a store or a bitcast to i32.  And in
11649     // the case of a store, it's not worth it if the index is a constant 0,
11650     // because a MOVSSmr can be used instead, which is smaller and faster.
11651     if (!Op.hasOneUse())
11652       return SDValue();
11653     SDNode *User = *Op.getNode()->use_begin();
11654     if ((User->getOpcode() != ISD::STORE ||
11655          isNullConstant(Op.getOperand(1))) &&
11656         (User->getOpcode() != ISD::BITCAST ||
11657          User->getValueType(0) != MVT::i32))
11658       return SDValue();
11659     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11660                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11661                                   Op.getOperand(1));
11662     return DAG.getBitcast(MVT::f32, Extract);
11663   }
11664
11665   if (VT == MVT::i32 || VT == MVT::i64) {
11666     // ExtractPS/pextrq works with constant index.
11667     if (isa<ConstantSDNode>(Op.getOperand(1)))
11668       return Op;
11669   }
11670   return SDValue();
11671 }
11672
11673 /// Extract one bit from mask vector, like v16i1 or v8i1.
11674 /// AVX-512 feature.
11675 SDValue
11676 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11677   SDValue Vec = Op.getOperand(0);
11678   SDLoc dl(Vec);
11679   MVT VecVT = Vec.getSimpleValueType();
11680   SDValue Idx = Op.getOperand(1);
11681   MVT EltVT = Op.getSimpleValueType();
11682
11683   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11684   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11685          "Unexpected vector type in ExtractBitFromMaskVector");
11686
11687   // variable index can't be handled in mask registers,
11688   // extend vector to VR512
11689   if (!isa<ConstantSDNode>(Idx)) {
11690     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11691     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11692     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11693                               ExtVT.getVectorElementType(), Ext, Idx);
11694     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11695   }
11696
11697   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11698   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11699   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11700     rc = getRegClassFor(MVT::v16i1);
11701   unsigned MaxSift = rc->getSize()*8 - 1;
11702   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11703                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11704   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11705                     DAG.getConstant(MaxSift, dl, MVT::i8));
11706   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11707                        DAG.getIntPtrConstant(0, dl));
11708 }
11709
11710 SDValue
11711 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11712                                            SelectionDAG &DAG) const {
11713   SDLoc dl(Op);
11714   SDValue Vec = Op.getOperand(0);
11715   MVT VecVT = Vec.getSimpleValueType();
11716   SDValue Idx = Op.getOperand(1);
11717
11718   if (Op.getSimpleValueType() == MVT::i1)
11719     return ExtractBitFromMaskVector(Op, DAG);
11720
11721   if (!isa<ConstantSDNode>(Idx)) {
11722     if (VecVT.is512BitVector() ||
11723         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11724          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11725
11726       MVT MaskEltVT =
11727         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11728       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11729                                     MaskEltVT.getSizeInBits());
11730
11731       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11732       auto PtrVT = getPointerTy(DAG.getDataLayout());
11733       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11734                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11735                                  DAG.getConstant(0, dl, PtrVT));
11736       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11737       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11738                          DAG.getConstant(0, dl, PtrVT));
11739     }
11740     return SDValue();
11741   }
11742
11743   // If this is a 256-bit vector result, first extract the 128-bit vector and
11744   // then extract the element from the 128-bit vector.
11745   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11746
11747     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11748     // Get the 128-bit vector.
11749     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11750     MVT EltVT = VecVT.getVectorElementType();
11751
11752     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11753     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11754
11755     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11756     // this can be done with a mask.
11757     IdxVal &= ElemsPerChunk - 1;
11758     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11759                        DAG.getConstant(IdxVal, dl, MVT::i32));
11760   }
11761
11762   assert(VecVT.is128BitVector() && "Unexpected vector length");
11763
11764   if (Subtarget->hasSSE41())
11765     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11766       return Res;
11767
11768   MVT VT = Op.getSimpleValueType();
11769   // TODO: handle v16i8.
11770   if (VT.getSizeInBits() == 16) {
11771     SDValue Vec = Op.getOperand(0);
11772     if (isNullConstant(Op.getOperand(1)))
11773       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11774                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11775                                      DAG.getBitcast(MVT::v4i32, Vec),
11776                                      Op.getOperand(1)));
11777     // Transform it so it match pextrw which produces a 32-bit result.
11778     MVT EltVT = MVT::i32;
11779     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11780                                   Op.getOperand(0), Op.getOperand(1));
11781     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11782                                   DAG.getValueType(VT));
11783     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11784   }
11785
11786   if (VT.getSizeInBits() == 32) {
11787     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11788     if (Idx == 0)
11789       return Op;
11790
11791     // SHUFPS the element to the lowest double word, then movss.
11792     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11793     MVT VVT = Op.getOperand(0).getSimpleValueType();
11794     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11795                                        DAG.getUNDEF(VVT), Mask);
11796     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11797                        DAG.getIntPtrConstant(0, dl));
11798   }
11799
11800   if (VT.getSizeInBits() == 64) {
11801     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11802     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11803     //        to match extract_elt for f64.
11804     if (isNullConstant(Op.getOperand(1)))
11805       return Op;
11806
11807     // UNPCKHPD the element to the lowest double word, then movsd.
11808     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11809     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11810     int Mask[2] = { 1, -1 };
11811     MVT VVT = Op.getOperand(0).getSimpleValueType();
11812     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11813                                        DAG.getUNDEF(VVT), Mask);
11814     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11815                        DAG.getIntPtrConstant(0, dl));
11816   }
11817
11818   return SDValue();
11819 }
11820
11821 /// Insert one bit to mask vector, like v16i1 or v8i1.
11822 /// AVX-512 feature.
11823 SDValue
11824 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11825   SDLoc dl(Op);
11826   SDValue Vec = Op.getOperand(0);
11827   SDValue Elt = Op.getOperand(1);
11828   SDValue Idx = Op.getOperand(2);
11829   MVT VecVT = Vec.getSimpleValueType();
11830
11831   if (!isa<ConstantSDNode>(Idx)) {
11832     // Non constant index. Extend source and destination,
11833     // insert element and then truncate the result.
11834     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11835     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11836     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11837       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11838       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11839     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11840   }
11841
11842   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11843   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11844   if (IdxVal)
11845     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11846                            DAG.getConstant(IdxVal, dl, MVT::i8));
11847   if (Vec.getOpcode() == ISD::UNDEF)
11848     return EltInVec;
11849   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11850 }
11851
11852 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11853                                                   SelectionDAG &DAG) const {
11854   MVT VT = Op.getSimpleValueType();
11855   MVT EltVT = VT.getVectorElementType();
11856
11857   if (EltVT == MVT::i1)
11858     return InsertBitToMaskVector(Op, DAG);
11859
11860   SDLoc dl(Op);
11861   SDValue N0 = Op.getOperand(0);
11862   SDValue N1 = Op.getOperand(1);
11863   SDValue N2 = Op.getOperand(2);
11864   if (!isa<ConstantSDNode>(N2))
11865     return SDValue();
11866   auto *N2C = cast<ConstantSDNode>(N2);
11867   unsigned IdxVal = N2C->getZExtValue();
11868
11869   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11870   // into that, and then insert the subvector back into the result.
11871   if (VT.is256BitVector() || VT.is512BitVector()) {
11872     // With a 256-bit vector, we can insert into the zero element efficiently
11873     // using a blend if we have AVX or AVX2 and the right data type.
11874     if (VT.is256BitVector() && IdxVal == 0) {
11875       // TODO: It is worthwhile to cast integer to floating point and back
11876       // and incur a domain crossing penalty if that's what we'll end up
11877       // doing anyway after extracting to a 128-bit vector.
11878       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11879           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11880         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11881         N2 = DAG.getIntPtrConstant(1, dl);
11882         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11883       }
11884     }
11885
11886     // Get the desired 128-bit vector chunk.
11887     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11888
11889     // Insert the element into the desired chunk.
11890     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11891     assert(isPowerOf2_32(NumEltsIn128));
11892     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11893     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11894
11895     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11896                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11897
11898     // Insert the changed part back into the bigger vector
11899     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11900   }
11901   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11902
11903   if (Subtarget->hasSSE41()) {
11904     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11905       unsigned Opc;
11906       if (VT == MVT::v8i16) {
11907         Opc = X86ISD::PINSRW;
11908       } else {
11909         assert(VT == MVT::v16i8);
11910         Opc = X86ISD::PINSRB;
11911       }
11912
11913       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11914       // argument.
11915       if (N1.getValueType() != MVT::i32)
11916         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11917       if (N2.getValueType() != MVT::i32)
11918         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11919       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11920     }
11921
11922     if (EltVT == MVT::f32) {
11923       // Bits [7:6] of the constant are the source select. This will always be
11924       //   zero here. The DAG Combiner may combine an extract_elt index into
11925       //   these bits. For example (insert (extract, 3), 2) could be matched by
11926       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11927       // Bits [5:4] of the constant are the destination select. This is the
11928       //   value of the incoming immediate.
11929       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11930       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11931
11932       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11933       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11934         // If this is an insertion of 32-bits into the low 32-bits of
11935         // a vector, we prefer to generate a blend with immediate rather
11936         // than an insertps. Blends are simpler operations in hardware and so
11937         // will always have equal or better performance than insertps.
11938         // But if optimizing for size and there's a load folding opportunity,
11939         // generate insertps because blendps does not have a 32-bit memory
11940         // operand form.
11941         N2 = DAG.getIntPtrConstant(1, dl);
11942         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11943         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11944       }
11945       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11946       // Create this as a scalar to vector..
11947       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11948       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11949     }
11950
11951     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11952       // PINSR* works with constant index.
11953       return Op;
11954     }
11955   }
11956
11957   if (EltVT == MVT::i8)
11958     return SDValue();
11959
11960   if (EltVT.getSizeInBits() == 16) {
11961     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11962     // as its second argument.
11963     if (N1.getValueType() != MVT::i32)
11964       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11965     if (N2.getValueType() != MVT::i32)
11966       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11967     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11968   }
11969   return SDValue();
11970 }
11971
11972 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11973   SDLoc dl(Op);
11974   MVT OpVT = Op.getSimpleValueType();
11975
11976   // If this is a 256-bit vector result, first insert into a 128-bit
11977   // vector and then insert into the 256-bit vector.
11978   if (!OpVT.is128BitVector()) {
11979     // Insert into a 128-bit vector.
11980     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11981     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11982                                  OpVT.getVectorNumElements() / SizeFactor);
11983
11984     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11985
11986     // Insert the 128-bit vector.
11987     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11988   }
11989
11990   if (OpVT == MVT::v1i64 &&
11991       Op.getOperand(0).getValueType() == MVT::i64)
11992     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11993
11994   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11995   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11996   return DAG.getBitcast(
11997       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11998 }
11999
12000 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12001 // a simple subregister reference or explicit instructions to grab
12002 // upper bits of a vector.
12003 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12004                                       SelectionDAG &DAG) {
12005   SDLoc dl(Op);
12006   SDValue In =  Op.getOperand(0);
12007   SDValue Idx = Op.getOperand(1);
12008   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12009   MVT ResVT   = Op.getSimpleValueType();
12010   MVT InVT    = In.getSimpleValueType();
12011
12012   if (Subtarget->hasFp256()) {
12013     if (ResVT.is128BitVector() &&
12014         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12015         isa<ConstantSDNode>(Idx)) {
12016       return Extract128BitVector(In, IdxVal, DAG, dl);
12017     }
12018     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12019         isa<ConstantSDNode>(Idx)) {
12020       return Extract256BitVector(In, IdxVal, DAG, dl);
12021     }
12022   }
12023   return SDValue();
12024 }
12025
12026 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12027 // simple superregister reference or explicit instructions to insert
12028 // the upper bits of a vector.
12029 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12030                                      SelectionDAG &DAG) {
12031   if (!Subtarget->hasAVX())
12032     return SDValue();
12033
12034   SDLoc dl(Op);
12035   SDValue Vec = Op.getOperand(0);
12036   SDValue SubVec = Op.getOperand(1);
12037   SDValue Idx = Op.getOperand(2);
12038
12039   if (!isa<ConstantSDNode>(Idx))
12040     return SDValue();
12041
12042   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12043   MVT OpVT = Op.getSimpleValueType();
12044   MVT SubVecVT = SubVec.getSimpleValueType();
12045
12046   // Fold two 16-byte subvector loads into one 32-byte load:
12047   // (insert_subvector (insert_subvector undef, (load addr), 0),
12048   //                   (load addr + 16), Elts/2)
12049   // --> load32 addr
12050   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12051       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12052       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12053     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12054     if (Idx2 && Idx2->getZExtValue() == 0) {
12055       SDValue SubVec2 = Vec.getOperand(1);
12056       // If needed, look through a bitcast to get to the load.
12057       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12058         SubVec2 = SubVec2.getOperand(0);
12059
12060       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12061         bool Fast;
12062         unsigned Alignment = FirstLd->getAlignment();
12063         unsigned AS = FirstLd->getAddressSpace();
12064         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12065         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12066                                     OpVT, AS, Alignment, &Fast) && Fast) {
12067           SDValue Ops[] = { SubVec2, SubVec };
12068           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12069             return Ld;
12070         }
12071       }
12072     }
12073   }
12074
12075   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12076       SubVecVT.is128BitVector())
12077     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12078
12079   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12080     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12081
12082   if (OpVT.getVectorElementType() == MVT::i1)
12083     return Insert1BitVector(Op, DAG);
12084
12085   return SDValue();
12086 }
12087
12088 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12089 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12090 // one of the above mentioned nodes. It has to be wrapped because otherwise
12091 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12092 // be used to form addressing mode. These wrapped nodes will be selected
12093 // into MOV32ri.
12094 SDValue
12095 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12096   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12097
12098   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12099   // global base reg.
12100   unsigned char OpFlag = 0;
12101   unsigned WrapperKind = X86ISD::Wrapper;
12102   CodeModel::Model M = DAG.getTarget().getCodeModel();
12103
12104   if (Subtarget->isPICStyleRIPRel() &&
12105       (M == CodeModel::Small || M == CodeModel::Kernel))
12106     WrapperKind = X86ISD::WrapperRIP;
12107   else if (Subtarget->isPICStyleGOT())
12108     OpFlag = X86II::MO_GOTOFF;
12109   else if (Subtarget->isPICStyleStubPIC())
12110     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12111
12112   auto PtrVT = getPointerTy(DAG.getDataLayout());
12113   SDValue Result = DAG.getTargetConstantPool(
12114       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12115   SDLoc DL(CP);
12116   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12117   // With PIC, the address is actually $g + Offset.
12118   if (OpFlag) {
12119     Result =
12120         DAG.getNode(ISD::ADD, DL, PtrVT,
12121                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12122   }
12123
12124   return Result;
12125 }
12126
12127 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12128   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12129
12130   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12131   // global base reg.
12132   unsigned char OpFlag = 0;
12133   unsigned WrapperKind = X86ISD::Wrapper;
12134   CodeModel::Model M = DAG.getTarget().getCodeModel();
12135
12136   if (Subtarget->isPICStyleRIPRel() &&
12137       (M == CodeModel::Small || M == CodeModel::Kernel))
12138     WrapperKind = X86ISD::WrapperRIP;
12139   else if (Subtarget->isPICStyleGOT())
12140     OpFlag = X86II::MO_GOTOFF;
12141   else if (Subtarget->isPICStyleStubPIC())
12142     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12143
12144   auto PtrVT = getPointerTy(DAG.getDataLayout());
12145   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12146   SDLoc DL(JT);
12147   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12148
12149   // With PIC, the address is actually $g + Offset.
12150   if (OpFlag)
12151     Result =
12152         DAG.getNode(ISD::ADD, DL, PtrVT,
12153                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12154
12155   return Result;
12156 }
12157
12158 SDValue
12159 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12160   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12161
12162   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12163   // global base reg.
12164   unsigned char OpFlag = 0;
12165   unsigned WrapperKind = X86ISD::Wrapper;
12166   CodeModel::Model M = DAG.getTarget().getCodeModel();
12167
12168   if (Subtarget->isPICStyleRIPRel() &&
12169       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12170     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12171       OpFlag = X86II::MO_GOTPCREL;
12172     WrapperKind = X86ISD::WrapperRIP;
12173   } else if (Subtarget->isPICStyleGOT()) {
12174     OpFlag = X86II::MO_GOT;
12175   } else if (Subtarget->isPICStyleStubPIC()) {
12176     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12177   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12178     OpFlag = X86II::MO_DARWIN_NONLAZY;
12179   }
12180
12181   auto PtrVT = getPointerTy(DAG.getDataLayout());
12182   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12183
12184   SDLoc DL(Op);
12185   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12186
12187   // With PIC, the address is actually $g + Offset.
12188   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12189       !Subtarget->is64Bit()) {
12190     Result =
12191         DAG.getNode(ISD::ADD, DL, PtrVT,
12192                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12193   }
12194
12195   // For symbols that require a load from a stub to get the address, emit the
12196   // load.
12197   if (isGlobalStubReference(OpFlag))
12198     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12199                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12200                          false, false, false, 0);
12201
12202   return Result;
12203 }
12204
12205 SDValue
12206 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12207   // Create the TargetBlockAddressAddress node.
12208   unsigned char OpFlags =
12209     Subtarget->ClassifyBlockAddressReference();
12210   CodeModel::Model M = DAG.getTarget().getCodeModel();
12211   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12212   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12213   SDLoc dl(Op);
12214   auto PtrVT = getPointerTy(DAG.getDataLayout());
12215   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12216
12217   if (Subtarget->isPICStyleRIPRel() &&
12218       (M == CodeModel::Small || M == CodeModel::Kernel))
12219     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12220   else
12221     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12222
12223   // With PIC, the address is actually $g + Offset.
12224   if (isGlobalRelativeToPICBase(OpFlags)) {
12225     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12226                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12227   }
12228
12229   return Result;
12230 }
12231
12232 SDValue
12233 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12234                                       int64_t Offset, SelectionDAG &DAG) const {
12235   // Create the TargetGlobalAddress node, folding in the constant
12236   // offset if it is legal.
12237   unsigned char OpFlags =
12238       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12239   CodeModel::Model M = DAG.getTarget().getCodeModel();
12240   auto PtrVT = getPointerTy(DAG.getDataLayout());
12241   SDValue Result;
12242   if (OpFlags == X86II::MO_NO_FLAG &&
12243       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12244     // A direct static reference to a global.
12245     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12246     Offset = 0;
12247   } else {
12248     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12249   }
12250
12251   if (Subtarget->isPICStyleRIPRel() &&
12252       (M == CodeModel::Small || M == CodeModel::Kernel))
12253     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12254   else
12255     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12256
12257   // With PIC, the address is actually $g + Offset.
12258   if (isGlobalRelativeToPICBase(OpFlags)) {
12259     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12260                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12261   }
12262
12263   // For globals that require a load from a stub to get the address, emit the
12264   // load.
12265   if (isGlobalStubReference(OpFlags))
12266     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12267                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12268                          false, false, false, 0);
12269
12270   // If there was a non-zero offset that we didn't fold, create an explicit
12271   // addition for it.
12272   if (Offset != 0)
12273     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12274                          DAG.getConstant(Offset, dl, PtrVT));
12275
12276   return Result;
12277 }
12278
12279 SDValue
12280 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12281   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12282   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12283   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12284 }
12285
12286 static SDValue
12287 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12288            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12289            unsigned char OperandFlags, bool LocalDynamic = false) {
12290   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12291   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12292   SDLoc dl(GA);
12293   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12294                                            GA->getValueType(0),
12295                                            GA->getOffset(),
12296                                            OperandFlags);
12297
12298   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12299                                            : X86ISD::TLSADDR;
12300
12301   if (InFlag) {
12302     SDValue Ops[] = { Chain,  TGA, *InFlag };
12303     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12304   } else {
12305     SDValue Ops[]  = { Chain, TGA };
12306     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12307   }
12308
12309   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12310   MFI->setAdjustsStack(true);
12311   MFI->setHasCalls(true);
12312
12313   SDValue Flag = Chain.getValue(1);
12314   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12315 }
12316
12317 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12318 static SDValue
12319 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12320                                 const EVT PtrVT) {
12321   SDValue InFlag;
12322   SDLoc dl(GA);  // ? function entry point might be better
12323   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12324                                    DAG.getNode(X86ISD::GlobalBaseReg,
12325                                                SDLoc(), PtrVT), InFlag);
12326   InFlag = Chain.getValue(1);
12327
12328   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12329 }
12330
12331 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12332 static SDValue
12333 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12334                                 const EVT PtrVT) {
12335   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12336                     X86::RAX, X86II::MO_TLSGD);
12337 }
12338
12339 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12340                                            SelectionDAG &DAG,
12341                                            const EVT PtrVT,
12342                                            bool is64Bit) {
12343   SDLoc dl(GA);
12344
12345   // Get the start address of the TLS block for this module.
12346   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12347       .getInfo<X86MachineFunctionInfo>();
12348   MFI->incNumLocalDynamicTLSAccesses();
12349
12350   SDValue Base;
12351   if (is64Bit) {
12352     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12353                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12354   } else {
12355     SDValue InFlag;
12356     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12357         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12358     InFlag = Chain.getValue(1);
12359     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12360                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12361   }
12362
12363   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12364   // of Base.
12365
12366   // Build x@dtpoff.
12367   unsigned char OperandFlags = X86II::MO_DTPOFF;
12368   unsigned WrapperKind = X86ISD::Wrapper;
12369   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12370                                            GA->getValueType(0),
12371                                            GA->getOffset(), OperandFlags);
12372   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12373
12374   // Add x@dtpoff with the base.
12375   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12376 }
12377
12378 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12379 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12380                                    const EVT PtrVT, TLSModel::Model model,
12381                                    bool is64Bit, bool isPIC) {
12382   SDLoc dl(GA);
12383
12384   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12385   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12386                                                          is64Bit ? 257 : 256));
12387
12388   SDValue ThreadPointer =
12389       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12390                   MachinePointerInfo(Ptr), false, false, false, 0);
12391
12392   unsigned char OperandFlags = 0;
12393   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12394   // initialexec.
12395   unsigned WrapperKind = X86ISD::Wrapper;
12396   if (model == TLSModel::LocalExec) {
12397     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12398   } else if (model == TLSModel::InitialExec) {
12399     if (is64Bit) {
12400       OperandFlags = X86II::MO_GOTTPOFF;
12401       WrapperKind = X86ISD::WrapperRIP;
12402     } else {
12403       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12404     }
12405   } else {
12406     llvm_unreachable("Unexpected model");
12407   }
12408
12409   // emit "addl x@ntpoff,%eax" (local exec)
12410   // or "addl x@indntpoff,%eax" (initial exec)
12411   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12412   SDValue TGA =
12413       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12414                                  GA->getOffset(), OperandFlags);
12415   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12416
12417   if (model == TLSModel::InitialExec) {
12418     if (isPIC && !is64Bit) {
12419       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12420                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12421                            Offset);
12422     }
12423
12424     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12425                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12426                          false, false, false, 0);
12427   }
12428
12429   // The address of the thread local variable is the add of the thread
12430   // pointer with the offset of the variable.
12431   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12432 }
12433
12434 SDValue
12435 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12436
12437   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12438
12439   // Cygwin uses emutls.
12440   // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12441   if (Subtarget->isTargetWindowsCygwin())
12442     return LowerToTLSEmulatedModel(GA, DAG);
12443
12444   const GlobalValue *GV = GA->getGlobal();
12445   auto PtrVT = getPointerTy(DAG.getDataLayout());
12446
12447   if (Subtarget->isTargetELF()) {
12448     if (DAG.getTarget().Options.EmulatedTLS)
12449       return LowerToTLSEmulatedModel(GA, DAG);
12450     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12451     switch (model) {
12452       case TLSModel::GeneralDynamic:
12453         if (Subtarget->is64Bit())
12454           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12455         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12456       case TLSModel::LocalDynamic:
12457         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12458                                            Subtarget->is64Bit());
12459       case TLSModel::InitialExec:
12460       case TLSModel::LocalExec:
12461         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12462                                    DAG.getTarget().getRelocationModel() ==
12463                                        Reloc::PIC_);
12464     }
12465     llvm_unreachable("Unknown TLS model.");
12466   }
12467
12468   if (Subtarget->isTargetDarwin()) {
12469     // Darwin only has one model of TLS.  Lower to that.
12470     unsigned char OpFlag = 0;
12471     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12472                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12473
12474     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12475     // global base reg.
12476     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12477                  !Subtarget->is64Bit();
12478     if (PIC32)
12479       OpFlag = X86II::MO_TLVP_PIC_BASE;
12480     else
12481       OpFlag = X86II::MO_TLVP;
12482     SDLoc DL(Op);
12483     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12484                                                 GA->getValueType(0),
12485                                                 GA->getOffset(), OpFlag);
12486     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12487
12488     // With PIC32, the address is actually $g + Offset.
12489     if (PIC32)
12490       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12491                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12492                            Offset);
12493
12494     // Lowering the machine isd will make sure everything is in the right
12495     // location.
12496     SDValue Chain = DAG.getEntryNode();
12497     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12498     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
12499     SDValue Args[] = { Chain, Offset };
12500     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12501     Chain =
12502         DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
12503                            DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
12504
12505     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12506     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12507     MFI->setAdjustsStack(true);
12508
12509     // And our return value (tls address) is in the standard call return value
12510     // location.
12511     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12512     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12513   }
12514
12515   if (Subtarget->isTargetKnownWindowsMSVC() ||
12516       Subtarget->isTargetWindowsGNU()) {
12517     // Just use the implicit TLS architecture
12518     // Need to generate someting similar to:
12519     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12520     //                                  ; from TEB
12521     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12522     //   mov     rcx, qword [rdx+rcx*8]
12523     //   mov     eax, .tls$:tlsvar
12524     //   [rax+rcx] contains the address
12525     // Windows 64bit: gs:0x58
12526     // Windows 32bit: fs:__tls_array
12527
12528     SDLoc dl(GA);
12529     SDValue Chain = DAG.getEntryNode();
12530
12531     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12532     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12533     // use its literal value of 0x2C.
12534     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12535                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12536                                                              256)
12537                                         : Type::getInt32PtrTy(*DAG.getContext(),
12538                                                               257));
12539
12540     SDValue TlsArray = Subtarget->is64Bit()
12541                            ? DAG.getIntPtrConstant(0x58, dl)
12542                            : (Subtarget->isTargetWindowsGNU()
12543                                   ? DAG.getIntPtrConstant(0x2C, dl)
12544                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12545
12546     SDValue ThreadPointer =
12547         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12548                     false, false, 0);
12549
12550     SDValue res;
12551     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12552       res = ThreadPointer;
12553     } else {
12554       // Load the _tls_index variable
12555       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12556       if (Subtarget->is64Bit())
12557         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12558                              MachinePointerInfo(), MVT::i32, false, false,
12559                              false, 0);
12560       else
12561         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12562                           false, false, 0);
12563
12564       auto &DL = DAG.getDataLayout();
12565       SDValue Scale =
12566           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12567       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12568
12569       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12570     }
12571
12572     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12573                       false, 0);
12574
12575     // Get the offset of start of .tls section
12576     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12577                                              GA->getValueType(0),
12578                                              GA->getOffset(), X86II::MO_SECREL);
12579     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12580
12581     // The address of the thread local variable is the add of the thread
12582     // pointer with the offset of the variable.
12583     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12584   }
12585
12586   llvm_unreachable("TLS not implemented for this target.");
12587 }
12588
12589 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12590 /// and take a 2 x i32 value to shift plus a shift amount.
12591 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12592   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12593   MVT VT = Op.getSimpleValueType();
12594   unsigned VTBits = VT.getSizeInBits();
12595   SDLoc dl(Op);
12596   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12597   SDValue ShOpLo = Op.getOperand(0);
12598   SDValue ShOpHi = Op.getOperand(1);
12599   SDValue ShAmt  = Op.getOperand(2);
12600   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12601   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12602   // during isel.
12603   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12604                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12605   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12606                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12607                        : DAG.getConstant(0, dl, VT);
12608
12609   SDValue Tmp2, Tmp3;
12610   if (Op.getOpcode() == ISD::SHL_PARTS) {
12611     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12612     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12613   } else {
12614     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12615     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12616   }
12617
12618   // If the shift amount is larger or equal than the width of a part we can't
12619   // rely on the results of shld/shrd. Insert a test and select the appropriate
12620   // values for large shift amounts.
12621   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12622                                 DAG.getConstant(VTBits, dl, MVT::i8));
12623   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12624                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12625
12626   SDValue Hi, Lo;
12627   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12628   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12629   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12630
12631   if (Op.getOpcode() == ISD::SHL_PARTS) {
12632     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12633     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12634   } else {
12635     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12636     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12637   }
12638
12639   SDValue Ops[2] = { Lo, Hi };
12640   return DAG.getMergeValues(Ops, dl);
12641 }
12642
12643 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12644                                            SelectionDAG &DAG) const {
12645   SDValue Src = Op.getOperand(0);
12646   MVT SrcVT = Src.getSimpleValueType();
12647   MVT VT = Op.getSimpleValueType();
12648   SDLoc dl(Op);
12649
12650   if (SrcVT.isVector()) {
12651     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12652       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12653                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12654                          DAG.getUNDEF(SrcVT)));
12655     }
12656     if (SrcVT.getVectorElementType() == MVT::i1) {
12657       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12658       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12659                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12660     }
12661     return SDValue();
12662   }
12663
12664   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12665          "Unknown SINT_TO_FP to lower!");
12666
12667   // These are really Legal; return the operand so the caller accepts it as
12668   // Legal.
12669   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12670     return Op;
12671   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12672       Subtarget->is64Bit()) {
12673     return Op;
12674   }
12675
12676   SDValue ValueToStore = Op.getOperand(0);
12677   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12678       !Subtarget->is64Bit())
12679     // Bitcasting to f64 here allows us to do a single 64-bit store from
12680     // an SSE register, avoiding the store forwarding penalty that would come
12681     // with two 32-bit stores.
12682     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
12683
12684   unsigned Size = SrcVT.getSizeInBits()/8;
12685   MachineFunction &MF = DAG.getMachineFunction();
12686   auto PtrVT = getPointerTy(MF.getDataLayout());
12687   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12688   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12689   SDValue Chain = DAG.getStore(
12690       DAG.getEntryNode(), dl, ValueToStore, StackSlot,
12691       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12692       false, 0);
12693   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12694 }
12695
12696 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12697                                      SDValue StackSlot,
12698                                      SelectionDAG &DAG) const {
12699   // Build the FILD
12700   SDLoc DL(Op);
12701   SDVTList Tys;
12702   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12703   if (useSSE)
12704     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12705   else
12706     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12707
12708   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12709
12710   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12711   MachineMemOperand *MMO;
12712   if (FI) {
12713     int SSFI = FI->getIndex();
12714     MMO = DAG.getMachineFunction().getMachineMemOperand(
12715         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12716         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12717   } else {
12718     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12719     StackSlot = StackSlot.getOperand(1);
12720   }
12721   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12722   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12723                                            X86ISD::FILD, DL,
12724                                            Tys, Ops, SrcVT, MMO);
12725
12726   if (useSSE) {
12727     Chain = Result.getValue(1);
12728     SDValue InFlag = Result.getValue(2);
12729
12730     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12731     // shouldn't be necessary except that RFP cannot be live across
12732     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12733     MachineFunction &MF = DAG.getMachineFunction();
12734     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12735     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12736     auto PtrVT = getPointerTy(MF.getDataLayout());
12737     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12738     Tys = DAG.getVTList(MVT::Other);
12739     SDValue Ops[] = {
12740       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12741     };
12742     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12743         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12744         MachineMemOperand::MOStore, SSFISize, SSFISize);
12745
12746     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12747                                     Ops, Op.getValueType(), MMO);
12748     Result = DAG.getLoad(
12749         Op.getValueType(), DL, Chain, StackSlot,
12750         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12751         false, false, false, 0);
12752   }
12753
12754   return Result;
12755 }
12756
12757 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12758 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12759                                                SelectionDAG &DAG) const {
12760   // This algorithm is not obvious. Here it is what we're trying to output:
12761   /*
12762      movq       %rax,  %xmm0
12763      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12764      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12765      #ifdef __SSE3__
12766        haddpd   %xmm0, %xmm0
12767      #else
12768        pshufd   $0x4e, %xmm0, %xmm1
12769        addpd    %xmm1, %xmm0
12770      #endif
12771   */
12772
12773   SDLoc dl(Op);
12774   LLVMContext *Context = DAG.getContext();
12775
12776   // Build some magic constants.
12777   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12778   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12779   auto PtrVT = getPointerTy(DAG.getDataLayout());
12780   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12781
12782   SmallVector<Constant*,2> CV1;
12783   CV1.push_back(
12784     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12785                                       APInt(64, 0x4330000000000000ULL))));
12786   CV1.push_back(
12787     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12788                                       APInt(64, 0x4530000000000000ULL))));
12789   Constant *C1 = ConstantVector::get(CV1);
12790   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12791
12792   // Load the 64-bit value into an XMM register.
12793   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12794                             Op.getOperand(0));
12795   SDValue CLod0 =
12796       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12797                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12798                   false, false, false, 16);
12799   SDValue Unpck1 =
12800       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12801
12802   SDValue CLod1 =
12803       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12804                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12805                   false, false, false, 16);
12806   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12807   // TODO: Are there any fast-math-flags to propagate here?
12808   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12809   SDValue Result;
12810
12811   if (Subtarget->hasSSE3()) {
12812     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12813     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12814   } else {
12815     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12816     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12817                                            S2F, 0x4E, DAG);
12818     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12819                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12820   }
12821
12822   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12823                      DAG.getIntPtrConstant(0, dl));
12824 }
12825
12826 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12827 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12828                                                SelectionDAG &DAG) const {
12829   SDLoc dl(Op);
12830   // FP constant to bias correct the final result.
12831   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12832                                    MVT::f64);
12833
12834   // Load the 32-bit value into an XMM register.
12835   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12836                              Op.getOperand(0));
12837
12838   // Zero out the upper parts of the register.
12839   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12840
12841   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12842                      DAG.getBitcast(MVT::v2f64, Load),
12843                      DAG.getIntPtrConstant(0, dl));
12844
12845   // Or the load with the bias.
12846   SDValue Or = DAG.getNode(
12847       ISD::OR, dl, MVT::v2i64,
12848       DAG.getBitcast(MVT::v2i64,
12849                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12850       DAG.getBitcast(MVT::v2i64,
12851                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12852   Or =
12853       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12854                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12855
12856   // Subtract the bias.
12857   // TODO: Are there any fast-math-flags to propagate here?
12858   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12859
12860   // Handle final rounding.
12861   MVT DestVT = Op.getSimpleValueType();
12862
12863   if (DestVT.bitsLT(MVT::f64))
12864     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12865                        DAG.getIntPtrConstant(0, dl));
12866   if (DestVT.bitsGT(MVT::f64))
12867     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12868
12869   // Handle final rounding.
12870   return Sub;
12871 }
12872
12873 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12874                                      const X86Subtarget &Subtarget) {
12875   // The algorithm is the following:
12876   // #ifdef __SSE4_1__
12877   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12878   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12879   //                                 (uint4) 0x53000000, 0xaa);
12880   // #else
12881   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12882   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12883   // #endif
12884   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12885   //     return (float4) lo + fhi;
12886
12887   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12888   // reassociate the two FADDs, and if we do that, the algorithm fails
12889   // spectacularly (PR24512).
12890   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12891   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12892   // there's also the MachineCombiner reassociations happening on Machine IR.
12893   if (DAG.getTarget().Options.UnsafeFPMath)
12894     return SDValue();
12895
12896   SDLoc DL(Op);
12897   SDValue V = Op->getOperand(0);
12898   MVT VecIntVT = V.getSimpleValueType();
12899   bool Is128 = VecIntVT == MVT::v4i32;
12900   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12901   // If we convert to something else than the supported type, e.g., to v4f64,
12902   // abort early.
12903   if (VecFloatVT != Op->getSimpleValueType(0))
12904     return SDValue();
12905
12906   unsigned NumElts = VecIntVT.getVectorNumElements();
12907   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12908          "Unsupported custom type");
12909   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12910
12911   // In the #idef/#else code, we have in common:
12912   // - The vector of constants:
12913   // -- 0x4b000000
12914   // -- 0x53000000
12915   // - A shift:
12916   // -- v >> 16
12917
12918   // Create the splat vector for 0x4b000000.
12919   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12920   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12921                            CstLow, CstLow, CstLow, CstLow};
12922   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12923                                   makeArrayRef(&CstLowArray[0], NumElts));
12924   // Create the splat vector for 0x53000000.
12925   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12926   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12927                             CstHigh, CstHigh, CstHigh, CstHigh};
12928   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12929                                    makeArrayRef(&CstHighArray[0], NumElts));
12930
12931   // Create the right shift.
12932   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12933   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12934                              CstShift, CstShift, CstShift, CstShift};
12935   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12936                                     makeArrayRef(&CstShiftArray[0], NumElts));
12937   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12938
12939   SDValue Low, High;
12940   if (Subtarget.hasSSE41()) {
12941     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12942     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12943     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12944     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12945     // Low will be bitcasted right away, so do not bother bitcasting back to its
12946     // original type.
12947     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12948                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12949     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12950     //                                 (uint4) 0x53000000, 0xaa);
12951     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12952     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12953     // High will be bitcasted right away, so do not bother bitcasting back to
12954     // its original type.
12955     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12956                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12957   } else {
12958     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12959     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12960                                      CstMask, CstMask, CstMask);
12961     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12962     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12963     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12964
12965     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12966     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12967   }
12968
12969   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12970   SDValue CstFAdd = DAG.getConstantFP(
12971       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12972   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12973                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12974   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12975                                    makeArrayRef(&CstFAddArray[0], NumElts));
12976
12977   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12978   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12979   // TODO: Are there any fast-math-flags to propagate here?
12980   SDValue FHigh =
12981       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12982   //     return (float4) lo + fhi;
12983   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12984   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12985 }
12986
12987 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12988                                                SelectionDAG &DAG) const {
12989   SDValue N0 = Op.getOperand(0);
12990   MVT SVT = N0.getSimpleValueType();
12991   SDLoc dl(Op);
12992
12993   switch (SVT.SimpleTy) {
12994   default:
12995     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12996   case MVT::v4i8:
12997   case MVT::v4i16:
12998   case MVT::v8i8:
12999   case MVT::v8i16: {
13000     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13001     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13002                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13003   }
13004   case MVT::v4i32:
13005   case MVT::v8i32:
13006     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13007   case MVT::v16i8:
13008   case MVT::v16i16:
13009     assert(Subtarget->hasAVX512());
13010     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13011                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
13012   }
13013 }
13014
13015 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13016                                            SelectionDAG &DAG) const {
13017   SDValue N0 = Op.getOperand(0);
13018   SDLoc dl(Op);
13019   auto PtrVT = getPointerTy(DAG.getDataLayout());
13020
13021   if (Op.getSimpleValueType().isVector())
13022     return lowerUINT_TO_FP_vec(Op, DAG);
13023
13024   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13025   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13026   // the optimization here.
13027   if (DAG.SignBitIsZero(N0))
13028     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13029
13030   MVT SrcVT = N0.getSimpleValueType();
13031   MVT DstVT = Op.getSimpleValueType();
13032
13033   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13034       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13035     // Conversions from unsigned i32 to f32/f64 are legal,
13036     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
13037     return Op;
13038   }
13039
13040   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13041     return LowerUINT_TO_FP_i64(Op, DAG);
13042   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13043     return LowerUINT_TO_FP_i32(Op, DAG);
13044   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13045     return SDValue();
13046
13047   // Make a 64-bit buffer, and use it to build an FILD.
13048   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13049   if (SrcVT == MVT::i32) {
13050     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13051     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13052     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13053                                   StackSlot, MachinePointerInfo(),
13054                                   false, false, 0);
13055     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13056                                   OffsetSlot, MachinePointerInfo(),
13057                                   false, false, 0);
13058     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13059     return Fild;
13060   }
13061
13062   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13063   SDValue ValueToStore = Op.getOperand(0);
13064   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget->is64Bit())
13065     // Bitcasting to f64 here allows us to do a single 64-bit store from
13066     // an SSE register, avoiding the store forwarding penalty that would come
13067     // with two 32-bit stores.
13068     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
13069   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore,
13070                                StackSlot, MachinePointerInfo(),
13071                                false, false, 0);
13072   // For i64 source, we need to add the appropriate power of 2 if the input
13073   // was negative.  This is the same as the optimization in
13074   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13075   // we must be careful to do the computation in x87 extended precision, not
13076   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13077   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13078   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13079       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13080       MachineMemOperand::MOLoad, 8, 8);
13081
13082   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13083   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13084   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13085                                          MVT::i64, MMO);
13086
13087   APInt FF(32, 0x5F800000ULL);
13088
13089   // Check whether the sign bit is set.
13090   SDValue SignSet = DAG.getSetCC(
13091       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13092       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13093
13094   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13095   SDValue FudgePtr = DAG.getConstantPool(
13096       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13097
13098   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13099   SDValue Zero = DAG.getIntPtrConstant(0, dl);
13100   SDValue Four = DAG.getIntPtrConstant(4, dl);
13101   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13102                                Zero, Four);
13103   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13104
13105   // Load the value out, extending it from f32 to f80.
13106   // FIXME: Avoid the extend by constructing the right constant pool?
13107   SDValue Fudge = DAG.getExtLoad(
13108       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13109       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13110       false, false, false, 4);
13111   // Extend everything to 80 bits to force it to be done on x87.
13112   // TODO: Are there any fast-math-flags to propagate here?
13113   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13114   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13115                      DAG.getIntPtrConstant(0, dl));
13116 }
13117
13118 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13119 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13120 // just return an <SDValue(), SDValue()> pair.
13121 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13122 // to i16, i32 or i64, and we lower it to a legal sequence.
13123 // If lowered to the final integer result we return a <result, SDValue()> pair.
13124 // Otherwise we lower it to a sequence ending with a FIST, return a
13125 // <FIST, StackSlot> pair, and the caller is responsible for loading
13126 // the final integer result from StackSlot.
13127 std::pair<SDValue,SDValue>
13128 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13129                                    bool IsSigned, bool IsReplace) const {
13130   SDLoc DL(Op);
13131
13132   EVT DstTy = Op.getValueType();
13133   EVT TheVT = Op.getOperand(0).getValueType();
13134   auto PtrVT = getPointerTy(DAG.getDataLayout());
13135
13136   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13137     // f16 must be promoted before using the lowering in this routine.
13138     // fp128 does not use this lowering.
13139     return std::make_pair(SDValue(), SDValue());
13140   }
13141
13142   // If using FIST to compute an unsigned i64, we'll need some fixup
13143   // to handle values above the maximum signed i64.  A FIST is always
13144   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13145   bool UnsignedFixup = !IsSigned &&
13146                        DstTy == MVT::i64 &&
13147                        (!Subtarget->is64Bit() ||
13148                         !isScalarFPTypeInSSEReg(TheVT));
13149
13150   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13151     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13152     // The low 32 bits of the fist result will have the correct uint32 result.
13153     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13154     DstTy = MVT::i64;
13155   }
13156
13157   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13158          DstTy.getSimpleVT() >= MVT::i16 &&
13159          "Unknown FP_TO_INT to lower!");
13160
13161   // These are really Legal.
13162   if (DstTy == MVT::i32 &&
13163       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13164     return std::make_pair(SDValue(), SDValue());
13165   if (Subtarget->is64Bit() &&
13166       DstTy == MVT::i64 &&
13167       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13168     return std::make_pair(SDValue(), SDValue());
13169
13170   // We lower FP->int64 into FISTP64 followed by a load from a temporary
13171   // stack slot.
13172   MachineFunction &MF = DAG.getMachineFunction();
13173   unsigned MemSize = DstTy.getSizeInBits()/8;
13174   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13175   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13176
13177   unsigned Opc;
13178   switch (DstTy.getSimpleVT().SimpleTy) {
13179   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13180   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13181   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13182   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13183   }
13184
13185   SDValue Chain = DAG.getEntryNode();
13186   SDValue Value = Op.getOperand(0);
13187   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13188
13189   if (UnsignedFixup) {
13190     //
13191     // Conversion to unsigned i64 is implemented with a select,
13192     // depending on whether the source value fits in the range
13193     // of a signed i64.  Let Thresh be the FP equivalent of
13194     // 0x8000000000000000ULL.
13195     //
13196     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13197     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
13198     //  Fist-to-mem64 FistSrc
13199     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13200     //  to XOR'ing the high 32 bits with Adjust.
13201     //
13202     // Being a power of 2, Thresh is exactly representable in all FP formats.
13203     // For X87 we'd like to use the smallest FP type for this constant, but
13204     // for DAG type consistency we have to match the FP operand type.
13205
13206     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13207     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13208     bool LosesInfo = false;
13209     if (TheVT == MVT::f64)
13210       // The rounding mode is irrelevant as the conversion should be exact.
13211       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13212                               &LosesInfo);
13213     else if (TheVT == MVT::f80)
13214       Status = Thresh.convert(APFloat::x87DoubleExtended,
13215                               APFloat::rmNearestTiesToEven, &LosesInfo);
13216
13217     assert(Status == APFloat::opOK && !LosesInfo &&
13218            "FP conversion should have been exact");
13219
13220     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13221
13222     SDValue Cmp = DAG.getSetCC(DL,
13223                                getSetCCResultType(DAG.getDataLayout(),
13224                                                   *DAG.getContext(), TheVT),
13225                                Value, ThreshVal, ISD::SETLT);
13226     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13227                            DAG.getConstant(0, DL, MVT::i32),
13228                            DAG.getConstant(0x80000000, DL, MVT::i32));
13229     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13230     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13231                                               *DAG.getContext(), TheVT),
13232                        Value, ThreshVal, ISD::SETLT);
13233     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13234   }
13235
13236   // FIXME This causes a redundant load/store if the SSE-class value is already
13237   // in memory, such as if it is on the callstack.
13238   if (isScalarFPTypeInSSEReg(TheVT)) {
13239     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13240     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13241                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13242                          false, 0);
13243     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13244     SDValue Ops[] = {
13245       Chain, StackSlot, DAG.getValueType(TheVT)
13246     };
13247
13248     MachineMemOperand *MMO =
13249         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13250                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13251     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13252     Chain = Value.getValue(1);
13253     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13254     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13255   }
13256
13257   MachineMemOperand *MMO =
13258       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13259                               MachineMemOperand::MOStore, MemSize, MemSize);
13260
13261   if (UnsignedFixup) {
13262
13263     // Insert the FIST, load its result as two i32's,
13264     // and XOR the high i32 with Adjust.
13265
13266     SDValue FistOps[] = { Chain, Value, StackSlot };
13267     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13268                                            FistOps, DstTy, MMO);
13269
13270     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13271                                 MachinePointerInfo(),
13272                                 false, false, false, 0);
13273     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13274                                    DAG.getConstant(4, DL, PtrVT));
13275
13276     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13277                                  MachinePointerInfo(),
13278                                  false, false, false, 0);
13279     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13280
13281     if (Subtarget->is64Bit()) {
13282       // Join High32 and Low32 into a 64-bit result.
13283       // (High32 << 32) | Low32
13284       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13285       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13286       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13287                            DAG.getConstant(32, DL, MVT::i8));
13288       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13289       return std::make_pair(Result, SDValue());
13290     }
13291
13292     SDValue ResultOps[] = { Low32, High32 };
13293
13294     SDValue pair = IsReplace
13295       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13296       : DAG.getMergeValues(ResultOps, DL);
13297     return std::make_pair(pair, SDValue());
13298   } else {
13299     // Build the FP_TO_INT*_IN_MEM
13300     SDValue Ops[] = { Chain, Value, StackSlot };
13301     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13302                                            Ops, DstTy, MMO);
13303     return std::make_pair(FIST, StackSlot);
13304   }
13305 }
13306
13307 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13308                               const X86Subtarget *Subtarget) {
13309   MVT VT = Op->getSimpleValueType(0);
13310   SDValue In = Op->getOperand(0);
13311   MVT InVT = In.getSimpleValueType();
13312   SDLoc dl(Op);
13313
13314   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13315     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13316
13317   // Optimize vectors in AVX mode:
13318   //
13319   //   v8i16 -> v8i32
13320   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13321   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13322   //   Concat upper and lower parts.
13323   //
13324   //   v4i32 -> v4i64
13325   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13326   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13327   //   Concat upper and lower parts.
13328   //
13329
13330   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13331       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13332       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13333     return SDValue();
13334
13335   if (Subtarget->hasInt256())
13336     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13337
13338   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13339   SDValue Undef = DAG.getUNDEF(InVT);
13340   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13341   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13342   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13343
13344   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13345                              VT.getVectorNumElements()/2);
13346
13347   OpLo = DAG.getBitcast(HVT, OpLo);
13348   OpHi = DAG.getBitcast(HVT, OpHi);
13349
13350   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13351 }
13352
13353 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13354                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13355   MVT VT = Op->getSimpleValueType(0);
13356   SDValue In = Op->getOperand(0);
13357   MVT InVT = In.getSimpleValueType();
13358   SDLoc DL(Op);
13359   unsigned int NumElts = VT.getVectorNumElements();
13360   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13361     return SDValue();
13362
13363   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13364     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13365
13366   assert(InVT.getVectorElementType() == MVT::i1);
13367   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13368   SDValue One =
13369    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13370   SDValue Zero =
13371    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13372
13373   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13374   if (VT.is512BitVector())
13375     return V;
13376   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13377 }
13378
13379 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13380                                SelectionDAG &DAG) {
13381   if (Subtarget->hasFp256())
13382     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13383       return Res;
13384
13385   return SDValue();
13386 }
13387
13388 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13389                                 SelectionDAG &DAG) {
13390   SDLoc DL(Op);
13391   MVT VT = Op.getSimpleValueType();
13392   SDValue In = Op.getOperand(0);
13393   MVT SVT = In.getSimpleValueType();
13394
13395   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13396     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13397
13398   if (Subtarget->hasFp256())
13399     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13400       return Res;
13401
13402   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13403          VT.getVectorNumElements() != SVT.getVectorNumElements());
13404   return SDValue();
13405 }
13406
13407 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13408                                   const X86Subtarget *Subtarget) {
13409
13410   SDLoc DL(Op);
13411   MVT VT = Op.getSimpleValueType();
13412   SDValue In = Op.getOperand(0);
13413   MVT InVT = In.getSimpleValueType();
13414
13415   assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13416
13417   // Shift LSB to MSB and use VPMOVB2M - SKX.
13418   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13419   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13420          Subtarget->hasBWI()) ||     // legal, will go to VPMOVB2M, VPMOVW2M
13421       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13422              InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13423              Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13424     // Shift packed bytes not supported natively, bitcast to dword
13425     MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13426     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13427                                      DAG.getBitcast(ExtVT, In),
13428                                      DAG.getConstant(ShiftInx, DL, ExtVT));
13429     ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13430     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13431   }
13432   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13433          Subtarget->hasDQI()) ||  // legal, will go to VPMOVD2M, VPMOVQ2M
13434       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13435          InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13436          Subtarget->hasVLX())) {  // legal, will go to VPMOVD2M, VPMOVQ2M
13437
13438     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13439                                      DAG.getConstant(ShiftInx, DL, InVT));
13440     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13441   }
13442
13443   // Shift LSB to MSB, extend if necessary and use TESTM.
13444   unsigned NumElts = InVT.getVectorNumElements();
13445   if (InVT.getSizeInBits() < 512 &&
13446       (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13447        !Subtarget->hasVLX())) {
13448     assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13449
13450     // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13451     // so vector should be extended to packed dword/qword.
13452     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13453     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13454     InVT = ExtVT;
13455     ShiftInx = InVT.getScalarSizeInBits() - 1;
13456   }
13457
13458   SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13459                                    DAG.getConstant(ShiftInx, DL, InVT));
13460   return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13461 }
13462
13463 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13464   SDLoc DL(Op);
13465   MVT VT = Op.getSimpleValueType();
13466   SDValue In = Op.getOperand(0);
13467   MVT InVT = In.getSimpleValueType();
13468
13469   if (VT == MVT::i1) {
13470     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13471            "Invalid scalar TRUNCATE operation");
13472     if (InVT.getSizeInBits() >= 32)
13473       return SDValue();
13474     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13475     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13476   }
13477   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13478          "Invalid TRUNCATE operation");
13479
13480   if (VT.getVectorElementType() == MVT::i1)
13481     return LowerTruncateVecI1(Op, DAG, Subtarget);
13482
13483   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13484   if (Subtarget->hasAVX512()) {
13485     // word to byte only under BWI
13486     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13487       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13488                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13489     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13490   }
13491   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13492     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13493     if (Subtarget->hasInt256()) {
13494       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13495       In = DAG.getBitcast(MVT::v8i32, In);
13496       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13497                                 ShufMask);
13498       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13499                          DAG.getIntPtrConstant(0, DL));
13500     }
13501
13502     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13503                                DAG.getIntPtrConstant(0, DL));
13504     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13505                                DAG.getIntPtrConstant(2, DL));
13506     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13507     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13508     static const int ShufMask[] = {0, 2, 4, 6};
13509     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13510   }
13511
13512   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13513     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13514     if (Subtarget->hasInt256()) {
13515       In = DAG.getBitcast(MVT::v32i8, In);
13516
13517       SmallVector<SDValue,32> pshufbMask;
13518       for (unsigned i = 0; i < 2; ++i) {
13519         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13520         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13521         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13522         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13523         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13524         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13525         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13526         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13527         for (unsigned j = 0; j < 8; ++j)
13528           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13529       }
13530       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13531       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13532       In = DAG.getBitcast(MVT::v4i64, In);
13533
13534       static const int ShufMask[] = {0,  2,  -1,  -1};
13535       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13536                                 &ShufMask[0]);
13537       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13538                        DAG.getIntPtrConstant(0, DL));
13539       return DAG.getBitcast(VT, In);
13540     }
13541
13542     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13543                                DAG.getIntPtrConstant(0, DL));
13544
13545     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13546                                DAG.getIntPtrConstant(4, DL));
13547
13548     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13549     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13550
13551     // The PSHUFB mask:
13552     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13553                                    -1, -1, -1, -1, -1, -1, -1, -1};
13554
13555     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13556     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13557     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13558
13559     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13560     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13561
13562     // The MOVLHPS Mask:
13563     static const int ShufMask2[] = {0, 1, 4, 5};
13564     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13565     return DAG.getBitcast(MVT::v8i16, res);
13566   }
13567
13568   // Handle truncation of V256 to V128 using shuffles.
13569   if (!VT.is128BitVector() || !InVT.is256BitVector())
13570     return SDValue();
13571
13572   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13573
13574   unsigned NumElems = VT.getVectorNumElements();
13575   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13576
13577   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13578   // Prepare truncation shuffle mask
13579   for (unsigned i = 0; i != NumElems; ++i)
13580     MaskVec[i] = i * 2;
13581   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13582                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13583   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13584                      DAG.getIntPtrConstant(0, DL));
13585 }
13586
13587 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13588                                            SelectionDAG &DAG) const {
13589   assert(!Op.getSimpleValueType().isVector());
13590
13591   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13592     /*IsSigned=*/ true, /*IsReplace=*/ false);
13593   SDValue FIST = Vals.first, StackSlot = Vals.second;
13594   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13595   if (!FIST.getNode())
13596     return Op;
13597
13598   if (StackSlot.getNode())
13599     // Load the result.
13600     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13601                        FIST, StackSlot, MachinePointerInfo(),
13602                        false, false, false, 0);
13603
13604   // The node is the result.
13605   return FIST;
13606 }
13607
13608 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13609                                            SelectionDAG &DAG) const {
13610   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13611     /*IsSigned=*/ false, /*IsReplace=*/ false);
13612   SDValue FIST = Vals.first, StackSlot = Vals.second;
13613   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13614   if (!FIST.getNode())
13615     return Op;
13616
13617   if (StackSlot.getNode())
13618     // Load the result.
13619     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13620                        FIST, StackSlot, MachinePointerInfo(),
13621                        false, false, false, 0);
13622
13623   // The node is the result.
13624   return FIST;
13625 }
13626
13627 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13628   SDLoc DL(Op);
13629   MVT VT = Op.getSimpleValueType();
13630   SDValue In = Op.getOperand(0);
13631   MVT SVT = In.getSimpleValueType();
13632
13633   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13634
13635   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13636                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13637                                  In, DAG.getUNDEF(SVT)));
13638 }
13639
13640 /// The only differences between FABS and FNEG are the mask and the logic op.
13641 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13642 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13643   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13644          "Wrong opcode for lowering FABS or FNEG.");
13645
13646   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13647
13648   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13649   // into an FNABS. We'll lower the FABS after that if it is still in use.
13650   if (IsFABS)
13651     for (SDNode *User : Op->uses())
13652       if (User->getOpcode() == ISD::FNEG)
13653         return Op;
13654
13655   SDLoc dl(Op);
13656   MVT VT = Op.getSimpleValueType();
13657
13658   bool IsF128 = (VT == MVT::f128);
13659
13660   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13661   // decide if we should generate a 16-byte constant mask when we only need 4 or
13662   // 8 bytes for the scalar case.
13663
13664   MVT LogicVT;
13665   MVT EltVT;
13666   unsigned NumElts;
13667
13668   if (VT.isVector()) {
13669     LogicVT = VT;
13670     EltVT = VT.getVectorElementType();
13671     NumElts = VT.getVectorNumElements();
13672   } else if (IsF128) {
13673     // SSE instructions are used for optimized f128 logical operations.
13674     LogicVT = MVT::f128;
13675     EltVT = VT;
13676     NumElts = 1;
13677   } else {
13678     // There are no scalar bitwise logical SSE/AVX instructions, so we
13679     // generate a 16-byte vector constant and logic op even for the scalar case.
13680     // Using a 16-byte mask allows folding the load of the mask with
13681     // the logic op, so it can save (~4 bytes) on code size.
13682     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13683     EltVT = VT;
13684     NumElts = (VT == MVT::f64) ? 2 : 4;
13685   }
13686
13687   unsigned EltBits = EltVT.getSizeInBits();
13688   LLVMContext *Context = DAG.getContext();
13689   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13690   APInt MaskElt =
13691     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13692   Constant *C = ConstantInt::get(*Context, MaskElt);
13693   C = ConstantVector::getSplat(NumElts, C);
13694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13695   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13696   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13697   SDValue Mask =
13698       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13699                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13700                   false, false, false, Alignment);
13701
13702   SDValue Op0 = Op.getOperand(0);
13703   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13704   unsigned LogicOp =
13705     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13706   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13707
13708   if (VT.isVector() || IsF128)
13709     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13710
13711   // For the scalar case extend to a 128-bit vector, perform the logic op,
13712   // and extract the scalar result back out.
13713   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13714   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13715   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13716                      DAG.getIntPtrConstant(0, dl));
13717 }
13718
13719 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13720   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13721   LLVMContext *Context = DAG.getContext();
13722   SDValue Op0 = Op.getOperand(0);
13723   SDValue Op1 = Op.getOperand(1);
13724   SDLoc dl(Op);
13725   MVT VT = Op.getSimpleValueType();
13726   MVT SrcVT = Op1.getSimpleValueType();
13727   bool IsF128 = (VT == MVT::f128);
13728
13729   // If second operand is smaller, extend it first.
13730   if (SrcVT.bitsLT(VT)) {
13731     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13732     SrcVT = VT;
13733   }
13734   // And if it is bigger, shrink it first.
13735   if (SrcVT.bitsGT(VT)) {
13736     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13737     SrcVT = VT;
13738   }
13739
13740   // At this point the operands and the result should have the same
13741   // type, and that won't be f80 since that is not custom lowered.
13742   assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13743          "Unexpected type in LowerFCOPYSIGN");
13744
13745   const fltSemantics &Sem =
13746       VT == MVT::f64 ? APFloat::IEEEdouble :
13747           (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13748   const unsigned SizeInBits = VT.getSizeInBits();
13749
13750   SmallVector<Constant *, 4> CV(
13751       VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13752       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13753
13754   // First, clear all bits but the sign bit from the second operand (sign).
13755   CV[0] = ConstantFP::get(*Context,
13756                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13757   Constant *C = ConstantVector::get(CV);
13758   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13759   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13760
13761   // Perform all logic operations as 16-byte vectors because there are no
13762   // scalar FP logic instructions in SSE. This allows load folding of the
13763   // constants into the logic instructions.
13764   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13765   SDValue Mask1 =
13766       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13767                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13768                   false, false, false, 16);
13769   if (!IsF128)
13770     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13771   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13772
13773   // Next, clear the sign bit from the first operand (magnitude).
13774   // If it's a constant, we can clear it here.
13775   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13776     APFloat APF = Op0CN->getValueAPF();
13777     // If the magnitude is a positive zero, the sign bit alone is enough.
13778     if (APF.isPosZero())
13779       return IsF128 ? SignBit :
13780           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13781                       DAG.getIntPtrConstant(0, dl));
13782     APF.clearSign();
13783     CV[0] = ConstantFP::get(*Context, APF);
13784   } else {
13785     CV[0] = ConstantFP::get(
13786         *Context,
13787         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13788   }
13789   C = ConstantVector::get(CV);
13790   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13791   SDValue Val =
13792       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13793                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13794                   false, false, false, 16);
13795   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13796   if (!isa<ConstantFPSDNode>(Op0)) {
13797     if (!IsF128)
13798       Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13799     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13800   }
13801   // OR the magnitude value with the sign bit.
13802   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13803   return IsF128 ? Val :
13804       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13805                   DAG.getIntPtrConstant(0, dl));
13806 }
13807
13808 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13809   SDValue N0 = Op.getOperand(0);
13810   SDLoc dl(Op);
13811   MVT VT = Op.getSimpleValueType();
13812
13813   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13814   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13815                                   DAG.getConstant(1, dl, VT));
13816   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13817 }
13818
13819 // Check whether an OR'd tree is PTEST-able.
13820 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13821                                       SelectionDAG &DAG) {
13822   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13823
13824   if (!Subtarget->hasSSE41())
13825     return SDValue();
13826
13827   if (!Op->hasOneUse())
13828     return SDValue();
13829
13830   SDNode *N = Op.getNode();
13831   SDLoc DL(N);
13832
13833   SmallVector<SDValue, 8> Opnds;
13834   DenseMap<SDValue, unsigned> VecInMap;
13835   SmallVector<SDValue, 8> VecIns;
13836   EVT VT = MVT::Other;
13837
13838   // Recognize a special case where a vector is casted into wide integer to
13839   // test all 0s.
13840   Opnds.push_back(N->getOperand(0));
13841   Opnds.push_back(N->getOperand(1));
13842
13843   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13844     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13845     // BFS traverse all OR'd operands.
13846     if (I->getOpcode() == ISD::OR) {
13847       Opnds.push_back(I->getOperand(0));
13848       Opnds.push_back(I->getOperand(1));
13849       // Re-evaluate the number of nodes to be traversed.
13850       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13851       continue;
13852     }
13853
13854     // Quit if a non-EXTRACT_VECTOR_ELT
13855     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13856       return SDValue();
13857
13858     // Quit if without a constant index.
13859     SDValue Idx = I->getOperand(1);
13860     if (!isa<ConstantSDNode>(Idx))
13861       return SDValue();
13862
13863     SDValue ExtractedFromVec = I->getOperand(0);
13864     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13865     if (M == VecInMap.end()) {
13866       VT = ExtractedFromVec.getValueType();
13867       // Quit if not 128/256-bit vector.
13868       if (!VT.is128BitVector() && !VT.is256BitVector())
13869         return SDValue();
13870       // Quit if not the same type.
13871       if (VecInMap.begin() != VecInMap.end() &&
13872           VT != VecInMap.begin()->first.getValueType())
13873         return SDValue();
13874       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13875       VecIns.push_back(ExtractedFromVec);
13876     }
13877     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13878   }
13879
13880   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13881          "Not extracted from 128-/256-bit vector.");
13882
13883   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13884
13885   for (DenseMap<SDValue, unsigned>::const_iterator
13886         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13887     // Quit if not all elements are used.
13888     if (I->second != FullMask)
13889       return SDValue();
13890   }
13891
13892   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13893
13894   // Cast all vectors into TestVT for PTEST.
13895   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13896     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13897
13898   // If more than one full vectors are evaluated, OR them first before PTEST.
13899   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13900     // Each iteration will OR 2 nodes and append the result until there is only
13901     // 1 node left, i.e. the final OR'd value of all vectors.
13902     SDValue LHS = VecIns[Slot];
13903     SDValue RHS = VecIns[Slot + 1];
13904     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13905   }
13906
13907   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13908                      VecIns.back(), VecIns.back());
13909 }
13910
13911 /// \brief return true if \c Op has a use that doesn't just read flags.
13912 static bool hasNonFlagsUse(SDValue Op) {
13913   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13914        ++UI) {
13915     SDNode *User = *UI;
13916     unsigned UOpNo = UI.getOperandNo();
13917     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13918       // Look pass truncate.
13919       UOpNo = User->use_begin().getOperandNo();
13920       User = *User->use_begin();
13921     }
13922
13923     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13924         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13925       return true;
13926   }
13927   return false;
13928 }
13929
13930 /// Emit nodes that will be selected as "test Op0,Op0", or something
13931 /// equivalent.
13932 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13933                                     SelectionDAG &DAG) const {
13934   if (Op.getValueType() == MVT::i1) {
13935     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13936     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13937                        DAG.getConstant(0, dl, MVT::i8));
13938   }
13939   // CF and OF aren't always set the way we want. Determine which
13940   // of these we need.
13941   bool NeedCF = false;
13942   bool NeedOF = false;
13943   switch (X86CC) {
13944   default: break;
13945   case X86::COND_A: case X86::COND_AE:
13946   case X86::COND_B: case X86::COND_BE:
13947     NeedCF = true;
13948     break;
13949   case X86::COND_G: case X86::COND_GE:
13950   case X86::COND_L: case X86::COND_LE:
13951   case X86::COND_O: case X86::COND_NO: {
13952     // Check if we really need to set the
13953     // Overflow flag. If NoSignedWrap is present
13954     // that is not actually needed.
13955     switch (Op->getOpcode()) {
13956     case ISD::ADD:
13957     case ISD::SUB:
13958     case ISD::MUL:
13959     case ISD::SHL: {
13960       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13961       if (BinNode->Flags.hasNoSignedWrap())
13962         break;
13963     }
13964     default:
13965       NeedOF = true;
13966       break;
13967     }
13968     break;
13969   }
13970   }
13971   // See if we can use the EFLAGS value from the operand instead of
13972   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13973   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13974   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13975     // Emit a CMP with 0, which is the TEST pattern.
13976     //if (Op.getValueType() == MVT::i1)
13977     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13978     //                     DAG.getConstant(0, MVT::i1));
13979     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13980                        DAG.getConstant(0, dl, Op.getValueType()));
13981   }
13982   unsigned Opcode = 0;
13983   unsigned NumOperands = 0;
13984
13985   // Truncate operations may prevent the merge of the SETCC instruction
13986   // and the arithmetic instruction before it. Attempt to truncate the operands
13987   // of the arithmetic instruction and use a reduced bit-width instruction.
13988   bool NeedTruncation = false;
13989   SDValue ArithOp = Op;
13990   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13991     SDValue Arith = Op->getOperand(0);
13992     // Both the trunc and the arithmetic op need to have one user each.
13993     if (Arith->hasOneUse())
13994       switch (Arith.getOpcode()) {
13995         default: break;
13996         case ISD::ADD:
13997         case ISD::SUB:
13998         case ISD::AND:
13999         case ISD::OR:
14000         case ISD::XOR: {
14001           NeedTruncation = true;
14002           ArithOp = Arith;
14003         }
14004       }
14005   }
14006
14007   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14008   // which may be the result of a CAST.  We use the variable 'Op', which is the
14009   // non-casted variable when we check for possible users.
14010   switch (ArithOp.getOpcode()) {
14011   case ISD::ADD:
14012     // Due to an isel shortcoming, be conservative if this add is likely to be
14013     // selected as part of a load-modify-store instruction. When the root node
14014     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14015     // uses of other nodes in the match, such as the ADD in this case. This
14016     // leads to the ADD being left around and reselected, with the result being
14017     // two adds in the output.  Alas, even if none our users are stores, that
14018     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14019     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14020     // climbing the DAG back to the root, and it doesn't seem to be worth the
14021     // effort.
14022     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14023          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14024       if (UI->getOpcode() != ISD::CopyToReg &&
14025           UI->getOpcode() != ISD::SETCC &&
14026           UI->getOpcode() != ISD::STORE)
14027         goto default_case;
14028
14029     if (ConstantSDNode *C =
14030         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14031       // An add of one will be selected as an INC.
14032       if (C->isOne() && !Subtarget->slowIncDec()) {
14033         Opcode = X86ISD::INC;
14034         NumOperands = 1;
14035         break;
14036       }
14037
14038       // An add of negative one (subtract of one) will be selected as a DEC.
14039       if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14040         Opcode = X86ISD::DEC;
14041         NumOperands = 1;
14042         break;
14043       }
14044     }
14045
14046     // Otherwise use a regular EFLAGS-setting add.
14047     Opcode = X86ISD::ADD;
14048     NumOperands = 2;
14049     break;
14050   case ISD::SHL:
14051   case ISD::SRL:
14052     // If we have a constant logical shift that's only used in a comparison
14053     // against zero turn it into an equivalent AND. This allows turning it into
14054     // a TEST instruction later.
14055     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14056         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14057       EVT VT = Op.getValueType();
14058       unsigned BitWidth = VT.getSizeInBits();
14059       unsigned ShAmt = Op->getConstantOperandVal(1);
14060       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14061         break;
14062       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14063                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14064                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14065       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14066         break;
14067       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14068                                 DAG.getConstant(Mask, dl, VT));
14069       DAG.ReplaceAllUsesWith(Op, New);
14070       Op = New;
14071     }
14072     break;
14073
14074   case ISD::AND:
14075     // If the primary and result isn't used, don't bother using X86ISD::AND,
14076     // because a TEST instruction will be better.
14077     if (!hasNonFlagsUse(Op))
14078       break;
14079     // FALL THROUGH
14080   case ISD::SUB:
14081   case ISD::OR:
14082   case ISD::XOR:
14083     // Due to the ISEL shortcoming noted above, be conservative if this op is
14084     // likely to be selected as part of a load-modify-store instruction.
14085     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14086            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14087       if (UI->getOpcode() == ISD::STORE)
14088         goto default_case;
14089
14090     // Otherwise use a regular EFLAGS-setting instruction.
14091     switch (ArithOp.getOpcode()) {
14092     default: llvm_unreachable("unexpected operator!");
14093     case ISD::SUB: Opcode = X86ISD::SUB; break;
14094     case ISD::XOR: Opcode = X86ISD::XOR; break;
14095     case ISD::AND: Opcode = X86ISD::AND; break;
14096     case ISD::OR: {
14097       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14098         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14099         if (EFLAGS.getNode())
14100           return EFLAGS;
14101       }
14102       Opcode = X86ISD::OR;
14103       break;
14104     }
14105     }
14106
14107     NumOperands = 2;
14108     break;
14109   case X86ISD::ADD:
14110   case X86ISD::SUB:
14111   case X86ISD::INC:
14112   case X86ISD::DEC:
14113   case X86ISD::OR:
14114   case X86ISD::XOR:
14115   case X86ISD::AND:
14116     return SDValue(Op.getNode(), 1);
14117   default:
14118   default_case:
14119     break;
14120   }
14121
14122   // If we found that truncation is beneficial, perform the truncation and
14123   // update 'Op'.
14124   if (NeedTruncation) {
14125     EVT VT = Op.getValueType();
14126     SDValue WideVal = Op->getOperand(0);
14127     EVT WideVT = WideVal.getValueType();
14128     unsigned ConvertedOp = 0;
14129     // Use a target machine opcode to prevent further DAGCombine
14130     // optimizations that may separate the arithmetic operations
14131     // from the setcc node.
14132     switch (WideVal.getOpcode()) {
14133       default: break;
14134       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14135       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14136       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14137       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14138       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14139     }
14140
14141     if (ConvertedOp) {
14142       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14143       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14144         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14145         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14146         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14147       }
14148     }
14149   }
14150
14151   if (Opcode == 0)
14152     // Emit a CMP with 0, which is the TEST pattern.
14153     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14154                        DAG.getConstant(0, dl, Op.getValueType()));
14155
14156   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14157   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14158
14159   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14160   DAG.ReplaceAllUsesWith(Op, New);
14161   return SDValue(New.getNode(), 1);
14162 }
14163
14164 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14165 /// equivalent.
14166 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14167                                    SDLoc dl, SelectionDAG &DAG) const {
14168   if (isNullConstant(Op1))
14169     return EmitTest(Op0, X86CC, dl, DAG);
14170
14171   assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14172          "Unexpected comparison operation for MVT::i1 operands");
14173
14174   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14175        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14176     // Do the comparison at i32 if it's smaller, besides the Atom case.
14177     // This avoids subregister aliasing issues. Keep the smaller reference
14178     // if we're optimizing for size, however, as that'll allow better folding
14179     // of memory operations.
14180     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14181         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14182         !Subtarget->isAtom()) {
14183       unsigned ExtendOp =
14184           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14185       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14186       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14187     }
14188     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14189     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14190     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14191                               Op0, Op1);
14192     return SDValue(Sub.getNode(), 1);
14193   }
14194   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14195 }
14196
14197 /// Convert a comparison if required by the subtarget.
14198 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14199                                                  SelectionDAG &DAG) const {
14200   // If the subtarget does not support the FUCOMI instruction, floating-point
14201   // comparisons have to be converted.
14202   if (Subtarget->hasCMov() ||
14203       Cmp.getOpcode() != X86ISD::CMP ||
14204       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14205       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14206     return Cmp;
14207
14208   // The instruction selector will select an FUCOM instruction instead of
14209   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14210   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14211   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14212   SDLoc dl(Cmp);
14213   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14214   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14215   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14216                             DAG.getConstant(8, dl, MVT::i8));
14217   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14218
14219   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14220   assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14221   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14222 }
14223
14224 /// The minimum architected relative accuracy is 2^-12. We need one
14225 /// Newton-Raphson step to have a good float result (24 bits of precision).
14226 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14227                                             DAGCombinerInfo &DCI,
14228                                             unsigned &RefinementSteps,
14229                                             bool &UseOneConstNR) const {
14230   EVT VT = Op.getValueType();
14231   const char *RecipOp;
14232
14233   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14234   // TODO: Add support for AVX512 (v16f32).
14235   // It is likely not profitable to do this for f64 because a double-precision
14236   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14237   // instructions: convert to single, rsqrtss, convert back to double, refine
14238   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14239   // along with FMA, this could be a throughput win.
14240   if (VT == MVT::f32 && Subtarget->hasSSE1())
14241     RecipOp = "sqrtf";
14242   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14243            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14244     RecipOp = "vec-sqrtf";
14245   else
14246     return SDValue();
14247
14248   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14249   if (!Recips.isEnabled(RecipOp))
14250     return SDValue();
14251
14252   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14253   UseOneConstNR = false;
14254   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14255 }
14256
14257 /// The minimum architected relative accuracy is 2^-12. We need one
14258 /// Newton-Raphson step to have a good float result (24 bits of precision).
14259 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14260                                             DAGCombinerInfo &DCI,
14261                                             unsigned &RefinementSteps) const {
14262   EVT VT = Op.getValueType();
14263   const char *RecipOp;
14264
14265   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14266   // TODO: Add support for AVX512 (v16f32).
14267   // It is likely not profitable to do this for f64 because a double-precision
14268   // reciprocal estimate with refinement on x86 prior to FMA requires
14269   // 15 instructions: convert to single, rcpss, convert back to double, refine
14270   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14271   // along with FMA, this could be a throughput win.
14272   if (VT == MVT::f32 && Subtarget->hasSSE1())
14273     RecipOp = "divf";
14274   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14275            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14276     RecipOp = "vec-divf";
14277   else
14278     return SDValue();
14279
14280   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14281   if (!Recips.isEnabled(RecipOp))
14282     return SDValue();
14283
14284   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14285   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14286 }
14287
14288 /// If we have at least two divisions that use the same divisor, convert to
14289 /// multplication by a reciprocal. This may need to be adjusted for a given
14290 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14291 /// This is because we still need one division to calculate the reciprocal and
14292 /// then we need two multiplies by that reciprocal as replacements for the
14293 /// original divisions.
14294 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14295   return 2;
14296 }
14297
14298 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14299 /// if it's possible.
14300 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14301                                      SDLoc dl, SelectionDAG &DAG) const {
14302   SDValue Op0 = And.getOperand(0);
14303   SDValue Op1 = And.getOperand(1);
14304   if (Op0.getOpcode() == ISD::TRUNCATE)
14305     Op0 = Op0.getOperand(0);
14306   if (Op1.getOpcode() == ISD::TRUNCATE)
14307     Op1 = Op1.getOperand(0);
14308
14309   SDValue LHS, RHS;
14310   if (Op1.getOpcode() == ISD::SHL)
14311     std::swap(Op0, Op1);
14312   if (Op0.getOpcode() == ISD::SHL) {
14313     if (isOneConstant(Op0.getOperand(0))) {
14314         // If we looked past a truncate, check that it's only truncating away
14315         // known zeros.
14316         unsigned BitWidth = Op0.getValueSizeInBits();
14317         unsigned AndBitWidth = And.getValueSizeInBits();
14318         if (BitWidth > AndBitWidth) {
14319           APInt Zeros, Ones;
14320           DAG.computeKnownBits(Op0, Zeros, Ones);
14321           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14322             return SDValue();
14323         }
14324         LHS = Op1;
14325         RHS = Op0.getOperand(1);
14326       }
14327   } else if (Op1.getOpcode() == ISD::Constant) {
14328     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14329     uint64_t AndRHSVal = AndRHS->getZExtValue();
14330     SDValue AndLHS = Op0;
14331
14332     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14333       LHS = AndLHS.getOperand(0);
14334       RHS = AndLHS.getOperand(1);
14335     }
14336
14337     // Use BT if the immediate can't be encoded in a TEST instruction.
14338     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14339       LHS = AndLHS;
14340       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14341     }
14342   }
14343
14344   if (LHS.getNode()) {
14345     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14346     // instruction.  Since the shift amount is in-range-or-undefined, we know
14347     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14348     // the encoding for the i16 version is larger than the i32 version.
14349     // Also promote i16 to i32 for performance / code size reason.
14350     if (LHS.getValueType() == MVT::i8 ||
14351         LHS.getValueType() == MVT::i16)
14352       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14353
14354     // If the operand types disagree, extend the shift amount to match.  Since
14355     // BT ignores high bits (like shifts) we can use anyextend.
14356     if (LHS.getValueType() != RHS.getValueType())
14357       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14358
14359     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14360     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14361     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14362                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14363   }
14364
14365   return SDValue();
14366 }
14367
14368 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14369 /// mask CMPs.
14370 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14371                               SDValue &Op1) {
14372   unsigned SSECC;
14373   bool Swap = false;
14374
14375   // SSE Condition code mapping:
14376   //  0 - EQ
14377   //  1 - LT
14378   //  2 - LE
14379   //  3 - UNORD
14380   //  4 - NEQ
14381   //  5 - NLT
14382   //  6 - NLE
14383   //  7 - ORD
14384   switch (SetCCOpcode) {
14385   default: llvm_unreachable("Unexpected SETCC condition");
14386   case ISD::SETOEQ:
14387   case ISD::SETEQ:  SSECC = 0; break;
14388   case ISD::SETOGT:
14389   case ISD::SETGT:  Swap = true; // Fallthrough
14390   case ISD::SETLT:
14391   case ISD::SETOLT: SSECC = 1; break;
14392   case ISD::SETOGE:
14393   case ISD::SETGE:  Swap = true; // Fallthrough
14394   case ISD::SETLE:
14395   case ISD::SETOLE: SSECC = 2; break;
14396   case ISD::SETUO:  SSECC = 3; break;
14397   case ISD::SETUNE:
14398   case ISD::SETNE:  SSECC = 4; break;
14399   case ISD::SETULE: Swap = true; // Fallthrough
14400   case ISD::SETUGE: SSECC = 5; break;
14401   case ISD::SETULT: Swap = true; // Fallthrough
14402   case ISD::SETUGT: SSECC = 6; break;
14403   case ISD::SETO:   SSECC = 7; break;
14404   case ISD::SETUEQ:
14405   case ISD::SETONE: SSECC = 8; break;
14406   }
14407   if (Swap)
14408     std::swap(Op0, Op1);
14409
14410   return SSECC;
14411 }
14412
14413 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14414 // ones, and then concatenate the result back.
14415 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14416   MVT VT = Op.getSimpleValueType();
14417
14418   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14419          "Unsupported value type for operation");
14420
14421   unsigned NumElems = VT.getVectorNumElements();
14422   SDLoc dl(Op);
14423   SDValue CC = Op.getOperand(2);
14424
14425   // Extract the LHS vectors
14426   SDValue LHS = Op.getOperand(0);
14427   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14428   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14429
14430   // Extract the RHS vectors
14431   SDValue RHS = Op.getOperand(1);
14432   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14433   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14434
14435   // Issue the operation on the smaller types and concatenate the result back
14436   MVT EltVT = VT.getVectorElementType();
14437   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14438   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14439                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14440                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14441 }
14442
14443 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14444   SDValue Op0 = Op.getOperand(0);
14445   SDValue Op1 = Op.getOperand(1);
14446   SDValue CC = Op.getOperand(2);
14447   MVT VT = Op.getSimpleValueType();
14448   SDLoc dl(Op);
14449
14450   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14451          "Unexpected type for boolean compare operation");
14452   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14453   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14454                                DAG.getConstant(-1, dl, VT));
14455   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14456                                DAG.getConstant(-1, dl, VT));
14457   switch (SetCCOpcode) {
14458   default: llvm_unreachable("Unexpected SETCC condition");
14459   case ISD::SETEQ:
14460     // (x == y) -> ~(x ^ y)
14461     return DAG.getNode(ISD::XOR, dl, VT,
14462                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14463                        DAG.getConstant(-1, dl, VT));
14464   case ISD::SETNE:
14465     // (x != y) -> (x ^ y)
14466     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14467   case ISD::SETUGT:
14468   case ISD::SETGT:
14469     // (x > y) -> (x & ~y)
14470     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14471   case ISD::SETULT:
14472   case ISD::SETLT:
14473     // (x < y) -> (~x & y)
14474     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14475   case ISD::SETULE:
14476   case ISD::SETLE:
14477     // (x <= y) -> (~x | y)
14478     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14479   case ISD::SETUGE:
14480   case ISD::SETGE:
14481     // (x >=y) -> (x | ~y)
14482     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14483   }
14484 }
14485
14486 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14487                                      const X86Subtarget *Subtarget) {
14488   SDValue Op0 = Op.getOperand(0);
14489   SDValue Op1 = Op.getOperand(1);
14490   SDValue CC = Op.getOperand(2);
14491   MVT VT = Op.getSimpleValueType();
14492   SDLoc dl(Op);
14493
14494   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14495          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14496          "Cannot set masked compare for this operation");
14497
14498   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14499   unsigned  Opc = 0;
14500   bool Unsigned = false;
14501   bool Swap = false;
14502   unsigned SSECC;
14503   switch (SetCCOpcode) {
14504   default: llvm_unreachable("Unexpected SETCC condition");
14505   case ISD::SETNE:  SSECC = 4; break;
14506   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14507   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14508   case ISD::SETLT:  Swap = true; //fall-through
14509   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14510   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14511   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14512   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14513   case ISD::SETULE: Unsigned = true; //fall-through
14514   case ISD::SETLE:  SSECC = 2; break;
14515   }
14516
14517   if (Swap)
14518     std::swap(Op0, Op1);
14519   if (Opc)
14520     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14521   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14522   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14523                      DAG.getConstant(SSECC, dl, MVT::i8));
14524 }
14525
14526 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14527 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14528 /// return an empty value.
14529 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14530 {
14531   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14532   if (!BV)
14533     return SDValue();
14534
14535   MVT VT = Op1.getSimpleValueType();
14536   MVT EVT = VT.getVectorElementType();
14537   unsigned n = VT.getVectorNumElements();
14538   SmallVector<SDValue, 8> ULTOp1;
14539
14540   for (unsigned i = 0; i < n; ++i) {
14541     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14542     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14543       return SDValue();
14544
14545     // Avoid underflow.
14546     APInt Val = Elt->getAPIntValue();
14547     if (Val == 0)
14548       return SDValue();
14549
14550     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14551   }
14552
14553   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14554 }
14555
14556 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14557                            SelectionDAG &DAG) {
14558   SDValue Op0 = Op.getOperand(0);
14559   SDValue Op1 = Op.getOperand(1);
14560   SDValue CC = Op.getOperand(2);
14561   MVT VT = Op.getSimpleValueType();
14562   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14563   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14564   SDLoc dl(Op);
14565
14566   if (isFP) {
14567 #ifndef NDEBUG
14568     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14569     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14570 #endif
14571
14572     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14573     unsigned Opc = X86ISD::CMPP;
14574     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14575       assert(VT.getVectorNumElements() <= 16);
14576       Opc = X86ISD::CMPM;
14577     }
14578     // In the two special cases we can't handle, emit two comparisons.
14579     if (SSECC == 8) {
14580       unsigned CC0, CC1;
14581       unsigned CombineOpc;
14582       if (SetCCOpcode == ISD::SETUEQ) {
14583         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14584       } else {
14585         assert(SetCCOpcode == ISD::SETONE);
14586         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14587       }
14588
14589       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14590                                  DAG.getConstant(CC0, dl, MVT::i8));
14591       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14592                                  DAG.getConstant(CC1, dl, MVT::i8));
14593       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14594     }
14595     // Handle all other FP comparisons here.
14596     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14597                        DAG.getConstant(SSECC, dl, MVT::i8));
14598   }
14599
14600   MVT VTOp0 = Op0.getSimpleValueType();
14601   assert(VTOp0 == Op1.getSimpleValueType() &&
14602          "Expected operands with same type!");
14603   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14604          "Invalid number of packed elements for source and destination!");
14605
14606   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14607     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14608     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14609     // legalizer firstly checks if the first operand in input to the setcc has
14610     // a legal type. If so, then it promotes the return type to that same type.
14611     // Otherwise, the return type is promoted to the 'next legal type' which,
14612     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14613     //
14614     // We reach this code only if the following two conditions are met:
14615     // 1. Both return type and operand type have been promoted to wider types
14616     //    by the type legalizer.
14617     // 2. The original operand type has been promoted to a 256-bit vector.
14618     //
14619     // Note that condition 2. only applies for AVX targets.
14620     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14621     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14622   }
14623
14624   // The non-AVX512 code below works under the assumption that source and
14625   // destination types are the same.
14626   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14627          "Value types for source and destination must be the same!");
14628
14629   // Break 256-bit integer vector compare into smaller ones.
14630   if (VT.is256BitVector() && !Subtarget->hasInt256())
14631     return Lower256IntVSETCC(Op, DAG);
14632
14633   MVT OpVT = Op1.getSimpleValueType();
14634   if (OpVT.getVectorElementType() == MVT::i1)
14635     return LowerBoolVSETCC_AVX512(Op, DAG);
14636
14637   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14638   if (Subtarget->hasAVX512()) {
14639     if (Op1.getSimpleValueType().is512BitVector() ||
14640         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14641         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14642       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14643
14644     // In AVX-512 architecture setcc returns mask with i1 elements,
14645     // But there is no compare instruction for i8 and i16 elements in KNL.
14646     // We are not talking about 512-bit operands in this case, these
14647     // types are illegal.
14648     if (MaskResult &&
14649         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14650          OpVT.getVectorElementType().getSizeInBits() >= 8))
14651       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14652                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14653   }
14654
14655   // Lower using XOP integer comparisons.
14656   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14657        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14658     // Translate compare code to XOP PCOM compare mode.
14659     unsigned CmpMode = 0;
14660     switch (SetCCOpcode) {
14661     default: llvm_unreachable("Unexpected SETCC condition");
14662     case ISD::SETULT:
14663     case ISD::SETLT: CmpMode = 0x00; break;
14664     case ISD::SETULE:
14665     case ISD::SETLE: CmpMode = 0x01; break;
14666     case ISD::SETUGT:
14667     case ISD::SETGT: CmpMode = 0x02; break;
14668     case ISD::SETUGE:
14669     case ISD::SETGE: CmpMode = 0x03; break;
14670     case ISD::SETEQ: CmpMode = 0x04; break;
14671     case ISD::SETNE: CmpMode = 0x05; break;
14672     }
14673
14674     // Are we comparing unsigned or signed integers?
14675     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14676       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14677
14678     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14679                        DAG.getConstant(CmpMode, dl, MVT::i8));
14680   }
14681
14682   // We are handling one of the integer comparisons here.  Since SSE only has
14683   // GT and EQ comparisons for integer, swapping operands and multiple
14684   // operations may be required for some comparisons.
14685   unsigned Opc;
14686   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14687   bool Subus = false;
14688
14689   switch (SetCCOpcode) {
14690   default: llvm_unreachable("Unexpected SETCC condition");
14691   case ISD::SETNE:  Invert = true;
14692   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14693   case ISD::SETLT:  Swap = true;
14694   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14695   case ISD::SETGE:  Swap = true;
14696   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14697                     Invert = true; break;
14698   case ISD::SETULT: Swap = true;
14699   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14700                     FlipSigns = true; break;
14701   case ISD::SETUGE: Swap = true;
14702   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14703                     FlipSigns = true; Invert = true; break;
14704   }
14705
14706   // Special case: Use min/max operations for SETULE/SETUGE
14707   MVT VET = VT.getVectorElementType();
14708   bool hasMinMax =
14709        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14710     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14711
14712   if (hasMinMax) {
14713     switch (SetCCOpcode) {
14714     default: break;
14715     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14716     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14717     }
14718
14719     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14720   }
14721
14722   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14723   if (!MinMax && hasSubus) {
14724     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14725     // Op0 u<= Op1:
14726     //   t = psubus Op0, Op1
14727     //   pcmpeq t, <0..0>
14728     switch (SetCCOpcode) {
14729     default: break;
14730     case ISD::SETULT: {
14731       // If the comparison is against a constant we can turn this into a
14732       // setule.  With psubus, setule does not require a swap.  This is
14733       // beneficial because the constant in the register is no longer
14734       // destructed as the destination so it can be hoisted out of a loop.
14735       // Only do this pre-AVX since vpcmp* is no longer destructive.
14736       if (Subtarget->hasAVX())
14737         break;
14738       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14739       if (ULEOp1.getNode()) {
14740         Op1 = ULEOp1;
14741         Subus = true; Invert = false; Swap = false;
14742       }
14743       break;
14744     }
14745     // Psubus is better than flip-sign because it requires no inversion.
14746     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14747     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14748     }
14749
14750     if (Subus) {
14751       Opc = X86ISD::SUBUS;
14752       FlipSigns = false;
14753     }
14754   }
14755
14756   if (Swap)
14757     std::swap(Op0, Op1);
14758
14759   // Check that the operation in question is available (most are plain SSE2,
14760   // but PCMPGTQ and PCMPEQQ have different requirements).
14761   if (VT == MVT::v2i64) {
14762     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14763       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14764
14765       // First cast everything to the right type.
14766       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14767       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14768
14769       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14770       // bits of the inputs before performing those operations. The lower
14771       // compare is always unsigned.
14772       SDValue SB;
14773       if (FlipSigns) {
14774         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14775       } else {
14776         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14777         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14778         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14779                          Sign, Zero, Sign, Zero);
14780       }
14781       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14782       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14783
14784       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14785       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14786       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14787
14788       // Create masks for only the low parts/high parts of the 64 bit integers.
14789       static const int MaskHi[] = { 1, 1, 3, 3 };
14790       static const int MaskLo[] = { 0, 0, 2, 2 };
14791       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14792       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14793       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14794
14795       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14796       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14797
14798       if (Invert)
14799         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14800
14801       return DAG.getBitcast(VT, Result);
14802     }
14803
14804     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14805       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14806       // pcmpeqd + pshufd + pand.
14807       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14808
14809       // First cast everything to the right type.
14810       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14811       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14812
14813       // Do the compare.
14814       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14815
14816       // Make sure the lower and upper halves are both all-ones.
14817       static const int Mask[] = { 1, 0, 3, 2 };
14818       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14819       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14820
14821       if (Invert)
14822         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14823
14824       return DAG.getBitcast(VT, Result);
14825     }
14826   }
14827
14828   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14829   // bits of the inputs before performing those operations.
14830   if (FlipSigns) {
14831     MVT EltVT = VT.getVectorElementType();
14832     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14833                                  VT);
14834     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14835     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14836   }
14837
14838   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14839
14840   // If the logical-not of the result is required, perform that now.
14841   if (Invert)
14842     Result = DAG.getNOT(dl, Result, VT);
14843
14844   if (MinMax)
14845     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14846
14847   if (Subus)
14848     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14849                          getZeroVector(VT, Subtarget, DAG, dl));
14850
14851   return Result;
14852 }
14853
14854 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14855
14856   MVT VT = Op.getSimpleValueType();
14857
14858   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14859
14860   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14861          && "SetCC type must be 8-bit or 1-bit integer");
14862   SDValue Op0 = Op.getOperand(0);
14863   SDValue Op1 = Op.getOperand(1);
14864   SDLoc dl(Op);
14865   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14866
14867   // Optimize to BT if possible.
14868   // Lower (X & (1 << N)) == 0 to BT(X, N).
14869   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14870   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14871   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14872       isNullConstant(Op1) &&
14873       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14874     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14875       if (VT == MVT::i1)
14876         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14877       return NewSetCC;
14878     }
14879   }
14880
14881   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14882   // these.
14883   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14884       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14885
14886     // If the input is a setcc, then reuse the input setcc or use a new one with
14887     // the inverted condition.
14888     if (Op0.getOpcode() == X86ISD::SETCC) {
14889       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14890       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14891       if (!Invert)
14892         return Op0;
14893
14894       CCode = X86::GetOppositeBranchCondition(CCode);
14895       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14896                                   DAG.getConstant(CCode, dl, MVT::i8),
14897                                   Op0.getOperand(1));
14898       if (VT == MVT::i1)
14899         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14900       return SetCC;
14901     }
14902   }
14903   if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14904       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14905
14906     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14907     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14908   }
14909
14910   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14911   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14912   if (X86CC == X86::COND_INVALID)
14913     return SDValue();
14914
14915   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14916   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14917   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14918                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14919   if (VT == MVT::i1)
14920     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14921   return SetCC;
14922 }
14923
14924 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14925   SDValue LHS = Op.getOperand(0);
14926   SDValue RHS = Op.getOperand(1);
14927   SDValue Carry = Op.getOperand(2);
14928   SDValue Cond = Op.getOperand(3);
14929   SDLoc DL(Op);
14930
14931   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14932   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14933
14934   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14935   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14936   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14937   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14938                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14939 }
14940
14941 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14942 static bool isX86LogicalCmp(SDValue Op) {
14943   unsigned Opc = Op.getNode()->getOpcode();
14944   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14945       Opc == X86ISD::SAHF)
14946     return true;
14947   if (Op.getResNo() == 1 &&
14948       (Opc == X86ISD::ADD ||
14949        Opc == X86ISD::SUB ||
14950        Opc == X86ISD::ADC ||
14951        Opc == X86ISD::SBB ||
14952        Opc == X86ISD::SMUL ||
14953        Opc == X86ISD::UMUL ||
14954        Opc == X86ISD::INC ||
14955        Opc == X86ISD::DEC ||
14956        Opc == X86ISD::OR ||
14957        Opc == X86ISD::XOR ||
14958        Opc == X86ISD::AND))
14959     return true;
14960
14961   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14962     return true;
14963
14964   return false;
14965 }
14966
14967 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14968   if (V.getOpcode() != ISD::TRUNCATE)
14969     return false;
14970
14971   SDValue VOp0 = V.getOperand(0);
14972   unsigned InBits = VOp0.getValueSizeInBits();
14973   unsigned Bits = V.getValueSizeInBits();
14974   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14975 }
14976
14977 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14978   bool addTest = true;
14979   SDValue Cond  = Op.getOperand(0);
14980   SDValue Op1 = Op.getOperand(1);
14981   SDValue Op2 = Op.getOperand(2);
14982   SDLoc DL(Op);
14983   MVT VT = Op1.getSimpleValueType();
14984   SDValue CC;
14985
14986   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14987   // are available or VBLENDV if AVX is available.
14988   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14989   if (Cond.getOpcode() == ISD::SETCC &&
14990       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14991        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14992       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14993     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14994     int SSECC = translateX86FSETCC(
14995         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14996
14997     if (SSECC != 8) {
14998       if (Subtarget->hasAVX512()) {
14999         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15000                                   DAG.getConstant(SSECC, DL, MVT::i8));
15001         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15002       }
15003
15004       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15005                                 DAG.getConstant(SSECC, DL, MVT::i8));
15006
15007       // If we have AVX, we can use a variable vector select (VBLENDV) instead
15008       // of 3 logic instructions for size savings and potentially speed.
15009       // Unfortunately, there is no scalar form of VBLENDV.
15010
15011       // If either operand is a constant, don't try this. We can expect to
15012       // optimize away at least one of the logic instructions later in that
15013       // case, so that sequence would be faster than a variable blend.
15014
15015       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
15016       // uses XMM0 as the selection register. That may need just as many
15017       // instructions as the AND/ANDN/OR sequence due to register moves, so
15018       // don't bother.
15019
15020       if (Subtarget->hasAVX() &&
15021           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
15022
15023         // Convert to vectors, do a VSELECT, and convert back to scalar.
15024         // All of the conversions should be optimized away.
15025
15026         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15027         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15028         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15029         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15030
15031         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15032         VCmp = DAG.getBitcast(VCmpVT, VCmp);
15033
15034         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15035
15036         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15037                            VSel, DAG.getIntPtrConstant(0, DL));
15038       }
15039       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15040       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15041       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15042     }
15043   }
15044
15045   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15046     SDValue Op1Scalar;
15047     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15048       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15049     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15050       Op1Scalar = Op1.getOperand(0);
15051     SDValue Op2Scalar;
15052     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15053       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15054     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15055       Op2Scalar = Op2.getOperand(0);
15056     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15057       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15058                                       Op1Scalar.getValueType(),
15059                                       Cond, Op1Scalar, Op2Scalar);
15060       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15061         return DAG.getBitcast(VT, newSelect);
15062       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15063       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15064                          DAG.getIntPtrConstant(0, DL));
15065     }
15066   }
15067
15068   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15069     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15070     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15071                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15072     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15073                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15074     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15075                                     Cond, Op1, Op2);
15076     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15077   }
15078
15079   if (Cond.getOpcode() == ISD::SETCC) {
15080     SDValue NewCond = LowerSETCC(Cond, DAG);
15081     if (NewCond.getNode())
15082       Cond = NewCond;
15083   }
15084
15085   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15086   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15087   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15088   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15089   if (Cond.getOpcode() == X86ISD::SETCC &&
15090       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15091       isNullConstant(Cond.getOperand(1).getOperand(1))) {
15092     SDValue Cmp = Cond.getOperand(1);
15093
15094     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15095
15096     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15097         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15098       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15099
15100       SDValue CmpOp0 = Cmp.getOperand(0);
15101       // Apply further optimizations for special cases
15102       // (select (x != 0), -1, 0) -> neg & sbb
15103       // (select (x == 0), 0, -1) -> neg & sbb
15104       if (isNullConstant(Y) &&
15105             (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15106           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15107           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15108                                     DAG.getConstant(0, DL,
15109                                                     CmpOp0.getValueType()),
15110                                     CmpOp0);
15111           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15112                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
15113                                     SDValue(Neg.getNode(), 1));
15114           return Res;
15115         }
15116
15117       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15118                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15119       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15120
15121       SDValue Res =   // Res = 0 or -1.
15122         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15123                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15124
15125       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15126         Res = DAG.getNOT(DL, Res, Res.getValueType());
15127
15128       if (!isNullConstant(Op2))
15129         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15130       return Res;
15131     }
15132   }
15133
15134   // Look past (and (setcc_carry (cmp ...)), 1).
15135   if (Cond.getOpcode() == ISD::AND &&
15136       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15137       isOneConstant(Cond.getOperand(1)))
15138     Cond = Cond.getOperand(0);
15139
15140   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15141   // setting operand in place of the X86ISD::SETCC.
15142   unsigned CondOpcode = Cond.getOpcode();
15143   if (CondOpcode == X86ISD::SETCC ||
15144       CondOpcode == X86ISD::SETCC_CARRY) {
15145     CC = Cond.getOperand(0);
15146
15147     SDValue Cmp = Cond.getOperand(1);
15148     unsigned Opc = Cmp.getOpcode();
15149     MVT VT = Op.getSimpleValueType();
15150
15151     bool IllegalFPCMov = false;
15152     if (VT.isFloatingPoint() && !VT.isVector() &&
15153         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15154       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15155
15156     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15157         Opc == X86ISD::BT) { // FIXME
15158       Cond = Cmp;
15159       addTest = false;
15160     }
15161   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15162              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15163              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15164               Cond.getOperand(0).getValueType() != MVT::i8)) {
15165     SDValue LHS = Cond.getOperand(0);
15166     SDValue RHS = Cond.getOperand(1);
15167     unsigned X86Opcode;
15168     unsigned X86Cond;
15169     SDVTList VTs;
15170     switch (CondOpcode) {
15171     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15172     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15173     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15174     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15175     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15176     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15177     default: llvm_unreachable("unexpected overflowing operator");
15178     }
15179     if (CondOpcode == ISD::UMULO)
15180       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15181                           MVT::i32);
15182     else
15183       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15184
15185     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15186
15187     if (CondOpcode == ISD::UMULO)
15188       Cond = X86Op.getValue(2);
15189     else
15190       Cond = X86Op.getValue(1);
15191
15192     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15193     addTest = false;
15194   }
15195
15196   if (addTest) {
15197     // Look past the truncate if the high bits are known zero.
15198     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15199       Cond = Cond.getOperand(0);
15200
15201     // We know the result of AND is compared against zero. Try to match
15202     // it to BT.
15203     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15204       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15205         CC = NewSetCC.getOperand(0);
15206         Cond = NewSetCC.getOperand(1);
15207         addTest = false;
15208       }
15209     }
15210   }
15211
15212   if (addTest) {
15213     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15214     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15215   }
15216
15217   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15218   // a <  b ?  0 : -1 -> RES = setcc_carry
15219   // a >= b ? -1 :  0 -> RES = setcc_carry
15220   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15221   if (Cond.getOpcode() == X86ISD::SUB) {
15222     Cond = ConvertCmpIfNecessary(Cond, DAG);
15223     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15224
15225     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15226         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15227         (isNullConstant(Op1) || isNullConstant(Op2))) {
15228       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15229                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15230                                 Cond);
15231       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15232         return DAG.getNOT(DL, Res, Res.getValueType());
15233       return Res;
15234     }
15235   }
15236
15237   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15238   // widen the cmov and push the truncate through. This avoids introducing a new
15239   // branch during isel and doesn't add any extensions.
15240   if (Op.getValueType() == MVT::i8 &&
15241       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15242     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15243     if (T1.getValueType() == T2.getValueType() &&
15244         // Blacklist CopyFromReg to avoid partial register stalls.
15245         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15246       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15247       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15248       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15249     }
15250   }
15251
15252   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15253   // condition is true.
15254   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15255   SDValue Ops[] = { Op2, Op1, CC, Cond };
15256   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15257 }
15258
15259 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15260                                        const X86Subtarget *Subtarget,
15261                                        SelectionDAG &DAG) {
15262   MVT VT = Op->getSimpleValueType(0);
15263   SDValue In = Op->getOperand(0);
15264   MVT InVT = In.getSimpleValueType();
15265   MVT VTElt = VT.getVectorElementType();
15266   MVT InVTElt = InVT.getVectorElementType();
15267   SDLoc dl(Op);
15268
15269   // SKX processor
15270   if ((InVTElt == MVT::i1) &&
15271       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15272         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15273
15274        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15275         VTElt.getSizeInBits() <= 16)) ||
15276
15277        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15278         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15279
15280        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15281         VTElt.getSizeInBits() >= 32))))
15282     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15283
15284   unsigned int NumElts = VT.getVectorNumElements();
15285
15286   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15287     return SDValue();
15288
15289   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15290     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15291       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15292     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15293   }
15294
15295   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15296   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15297   SDValue NegOne =
15298    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15299                    ExtVT);
15300   SDValue Zero =
15301    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15302
15303   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15304   if (VT.is512BitVector())
15305     return V;
15306   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15307 }
15308
15309 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15310                                              const X86Subtarget *Subtarget,
15311                                              SelectionDAG &DAG) {
15312   SDValue In = Op->getOperand(0);
15313   MVT VT = Op->getSimpleValueType(0);
15314   MVT InVT = In.getSimpleValueType();
15315   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15316
15317   MVT InSVT = InVT.getVectorElementType();
15318   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15319
15320   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15321     return SDValue();
15322   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15323     return SDValue();
15324
15325   SDLoc dl(Op);
15326
15327   // SSE41 targets can use the pmovsx* instructions directly.
15328   if (Subtarget->hasSSE41())
15329     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15330
15331   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15332   SDValue Curr = In;
15333   MVT CurrVT = InVT;
15334
15335   // As SRAI is only available on i16/i32 types, we expand only up to i32
15336   // and handle i64 separately.
15337   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15338     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15339     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15340     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15341     Curr = DAG.getBitcast(CurrVT, Curr);
15342   }
15343
15344   SDValue SignExt = Curr;
15345   if (CurrVT != InVT) {
15346     unsigned SignExtShift =
15347         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15348     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15349                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15350   }
15351
15352   if (CurrVT == VT)
15353     return SignExt;
15354
15355   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15356     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15357                                DAG.getConstant(31, dl, MVT::i8));
15358     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15359     return DAG.getBitcast(VT, Ext);
15360   }
15361
15362   return SDValue();
15363 }
15364
15365 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15366                                 SelectionDAG &DAG) {
15367   MVT VT = Op->getSimpleValueType(0);
15368   SDValue In = Op->getOperand(0);
15369   MVT InVT = In.getSimpleValueType();
15370   SDLoc dl(Op);
15371
15372   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15373     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15374
15375   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15376       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15377       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15378     return SDValue();
15379
15380   if (Subtarget->hasInt256())
15381     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15382
15383   // Optimize vectors in AVX mode
15384   // Sign extend  v8i16 to v8i32 and
15385   //              v4i32 to v4i64
15386   //
15387   // Divide input vector into two parts
15388   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15389   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15390   // concat the vectors to original VT
15391
15392   unsigned NumElems = InVT.getVectorNumElements();
15393   SDValue Undef = DAG.getUNDEF(InVT);
15394
15395   SmallVector<int,8> ShufMask1(NumElems, -1);
15396   for (unsigned i = 0; i != NumElems/2; ++i)
15397     ShufMask1[i] = i;
15398
15399   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15400
15401   SmallVector<int,8> ShufMask2(NumElems, -1);
15402   for (unsigned i = 0; i != NumElems/2; ++i)
15403     ShufMask2[i] = i + NumElems/2;
15404
15405   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15406
15407   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15408                                 VT.getVectorNumElements()/2);
15409
15410   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15411   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15412
15413   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15414 }
15415
15416 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15417 // may emit an illegal shuffle but the expansion is still better than scalar
15418 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15419 // we'll emit a shuffle and a arithmetic shift.
15420 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15421 // TODO: It is possible to support ZExt by zeroing the undef values during
15422 // the shuffle phase or after the shuffle.
15423 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15424                                  SelectionDAG &DAG) {
15425   MVT RegVT = Op.getSimpleValueType();
15426   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15427   assert(RegVT.isInteger() &&
15428          "We only custom lower integer vector sext loads.");
15429
15430   // Nothing useful we can do without SSE2 shuffles.
15431   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15432
15433   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15434   SDLoc dl(Ld);
15435   EVT MemVT = Ld->getMemoryVT();
15436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15437   unsigned RegSz = RegVT.getSizeInBits();
15438
15439   ISD::LoadExtType Ext = Ld->getExtensionType();
15440
15441   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15442          && "Only anyext and sext are currently implemented.");
15443   assert(MemVT != RegVT && "Cannot extend to the same type");
15444   assert(MemVT.isVector() && "Must load a vector from memory");
15445
15446   unsigned NumElems = RegVT.getVectorNumElements();
15447   unsigned MemSz = MemVT.getSizeInBits();
15448   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15449
15450   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15451     // The only way in which we have a legal 256-bit vector result but not the
15452     // integer 256-bit operations needed to directly lower a sextload is if we
15453     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15454     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15455     // correctly legalized. We do this late to allow the canonical form of
15456     // sextload to persist throughout the rest of the DAG combiner -- it wants
15457     // to fold together any extensions it can, and so will fuse a sign_extend
15458     // of an sextload into a sextload targeting a wider value.
15459     SDValue Load;
15460     if (MemSz == 128) {
15461       // Just switch this to a normal load.
15462       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15463                                        "it must be a legal 128-bit vector "
15464                                        "type!");
15465       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15466                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15467                   Ld->isInvariant(), Ld->getAlignment());
15468     } else {
15469       assert(MemSz < 128 &&
15470              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15471       // Do an sext load to a 128-bit vector type. We want to use the same
15472       // number of elements, but elements half as wide. This will end up being
15473       // recursively lowered by this routine, but will succeed as we definitely
15474       // have all the necessary features if we're using AVX1.
15475       EVT HalfEltVT =
15476           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15477       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15478       Load =
15479           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15480                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15481                          Ld->isNonTemporal(), Ld->isInvariant(),
15482                          Ld->getAlignment());
15483     }
15484
15485     // Replace chain users with the new chain.
15486     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15487     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15488
15489     // Finally, do a normal sign-extend to the desired register.
15490     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15491   }
15492
15493   // All sizes must be a power of two.
15494   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15495          "Non-power-of-two elements are not custom lowered!");
15496
15497   // Attempt to load the original value using scalar loads.
15498   // Find the largest scalar type that divides the total loaded size.
15499   MVT SclrLoadTy = MVT::i8;
15500   for (MVT Tp : MVT::integer_valuetypes()) {
15501     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15502       SclrLoadTy = Tp;
15503     }
15504   }
15505
15506   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15507   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15508       (64 <= MemSz))
15509     SclrLoadTy = MVT::f64;
15510
15511   // Calculate the number of scalar loads that we need to perform
15512   // in order to load our vector from memory.
15513   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15514
15515   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15516          "Can only lower sext loads with a single scalar load!");
15517
15518   unsigned loadRegZize = RegSz;
15519   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15520     loadRegZize = 128;
15521
15522   // Represent our vector as a sequence of elements which are the
15523   // largest scalar that we can load.
15524   EVT LoadUnitVecVT = EVT::getVectorVT(
15525       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15526
15527   // Represent the data using the same element type that is stored in
15528   // memory. In practice, we ''widen'' MemVT.
15529   EVT WideVecVT =
15530       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15531                        loadRegZize / MemVT.getScalarSizeInBits());
15532
15533   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15534          "Invalid vector type");
15535
15536   // We can't shuffle using an illegal type.
15537   assert(TLI.isTypeLegal(WideVecVT) &&
15538          "We only lower types that form legal widened vector types");
15539
15540   SmallVector<SDValue, 8> Chains;
15541   SDValue Ptr = Ld->getBasePtr();
15542   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15543                                       TLI.getPointerTy(DAG.getDataLayout()));
15544   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15545
15546   for (unsigned i = 0; i < NumLoads; ++i) {
15547     // Perform a single load.
15548     SDValue ScalarLoad =
15549         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15550                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15551                     Ld->getAlignment());
15552     Chains.push_back(ScalarLoad.getValue(1));
15553     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15554     // another round of DAGCombining.
15555     if (i == 0)
15556       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15557     else
15558       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15559                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15560
15561     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15562   }
15563
15564   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15565
15566   // Bitcast the loaded value to a vector of the original element type, in
15567   // the size of the target vector type.
15568   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15569   unsigned SizeRatio = RegSz / MemSz;
15570
15571   if (Ext == ISD::SEXTLOAD) {
15572     // If we have SSE4.1, we can directly emit a VSEXT node.
15573     if (Subtarget->hasSSE41()) {
15574       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15575       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15576       return Sext;
15577     }
15578
15579     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15580     // lanes.
15581     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15582            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15583
15584     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15585     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15586     return Shuff;
15587   }
15588
15589   // Redistribute the loaded elements into the different locations.
15590   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15591   for (unsigned i = 0; i != NumElems; ++i)
15592     ShuffleVec[i * SizeRatio] = i;
15593
15594   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15595                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15596
15597   // Bitcast to the requested type.
15598   Shuff = DAG.getBitcast(RegVT, Shuff);
15599   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15600   return Shuff;
15601 }
15602
15603 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15604 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15605 // from the AND / OR.
15606 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15607   Opc = Op.getOpcode();
15608   if (Opc != ISD::OR && Opc != ISD::AND)
15609     return false;
15610   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15611           Op.getOperand(0).hasOneUse() &&
15612           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15613           Op.getOperand(1).hasOneUse());
15614 }
15615
15616 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15617 // 1 and that the SETCC node has a single use.
15618 static bool isXor1OfSetCC(SDValue Op) {
15619   if (Op.getOpcode() != ISD::XOR)
15620     return false;
15621   if (isOneConstant(Op.getOperand(1)))
15622     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15623            Op.getOperand(0).hasOneUse();
15624   return false;
15625 }
15626
15627 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15628   bool addTest = true;
15629   SDValue Chain = Op.getOperand(0);
15630   SDValue Cond  = Op.getOperand(1);
15631   SDValue Dest  = Op.getOperand(2);
15632   SDLoc dl(Op);
15633   SDValue CC;
15634   bool Inverted = false;
15635
15636   if (Cond.getOpcode() == ISD::SETCC) {
15637     // Check for setcc([su]{add,sub,mul}o == 0).
15638     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15639         isNullConstant(Cond.getOperand(1)) &&
15640         Cond.getOperand(0).getResNo() == 1 &&
15641         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15642          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15643          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15644          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15645          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15646          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15647       Inverted = true;
15648       Cond = Cond.getOperand(0);
15649     } else {
15650       SDValue NewCond = LowerSETCC(Cond, DAG);
15651       if (NewCond.getNode())
15652         Cond = NewCond;
15653     }
15654   }
15655 #if 0
15656   // FIXME: LowerXALUO doesn't handle these!!
15657   else if (Cond.getOpcode() == X86ISD::ADD  ||
15658            Cond.getOpcode() == X86ISD::SUB  ||
15659            Cond.getOpcode() == X86ISD::SMUL ||
15660            Cond.getOpcode() == X86ISD::UMUL)
15661     Cond = LowerXALUO(Cond, DAG);
15662 #endif
15663
15664   // Look pass (and (setcc_carry (cmp ...)), 1).
15665   if (Cond.getOpcode() == ISD::AND &&
15666       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15667       isOneConstant(Cond.getOperand(1)))
15668     Cond = Cond.getOperand(0);
15669
15670   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15671   // setting operand in place of the X86ISD::SETCC.
15672   unsigned CondOpcode = Cond.getOpcode();
15673   if (CondOpcode == X86ISD::SETCC ||
15674       CondOpcode == X86ISD::SETCC_CARRY) {
15675     CC = Cond.getOperand(0);
15676
15677     SDValue Cmp = Cond.getOperand(1);
15678     unsigned Opc = Cmp.getOpcode();
15679     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15680     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15681       Cond = Cmp;
15682       addTest = false;
15683     } else {
15684       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15685       default: break;
15686       case X86::COND_O:
15687       case X86::COND_B:
15688         // These can only come from an arithmetic instruction with overflow,
15689         // e.g. SADDO, UADDO.
15690         Cond = Cond.getNode()->getOperand(1);
15691         addTest = false;
15692         break;
15693       }
15694     }
15695   }
15696   CondOpcode = Cond.getOpcode();
15697   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15698       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15699       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15700        Cond.getOperand(0).getValueType() != MVT::i8)) {
15701     SDValue LHS = Cond.getOperand(0);
15702     SDValue RHS = Cond.getOperand(1);
15703     unsigned X86Opcode;
15704     unsigned X86Cond;
15705     SDVTList VTs;
15706     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15707     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15708     // X86ISD::INC).
15709     switch (CondOpcode) {
15710     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15711     case ISD::SADDO:
15712       if (isOneConstant(RHS)) {
15713           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15714           break;
15715         }
15716       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15717     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15718     case ISD::SSUBO:
15719       if (isOneConstant(RHS)) {
15720           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15721           break;
15722         }
15723       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15724     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15725     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15726     default: llvm_unreachable("unexpected overflowing operator");
15727     }
15728     if (Inverted)
15729       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15730     if (CondOpcode == ISD::UMULO)
15731       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15732                           MVT::i32);
15733     else
15734       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15735
15736     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15737
15738     if (CondOpcode == ISD::UMULO)
15739       Cond = X86Op.getValue(2);
15740     else
15741       Cond = X86Op.getValue(1);
15742
15743     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15744     addTest = false;
15745   } else {
15746     unsigned CondOpc;
15747     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15748       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15749       if (CondOpc == ISD::OR) {
15750         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15751         // two branches instead of an explicit OR instruction with a
15752         // separate test.
15753         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15754             isX86LogicalCmp(Cmp)) {
15755           CC = Cond.getOperand(0).getOperand(0);
15756           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15757                               Chain, Dest, CC, Cmp);
15758           CC = Cond.getOperand(1).getOperand(0);
15759           Cond = Cmp;
15760           addTest = false;
15761         }
15762       } else { // ISD::AND
15763         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15764         // two branches instead of an explicit AND instruction with a
15765         // separate test. However, we only do this if this block doesn't
15766         // have a fall-through edge, because this requires an explicit
15767         // jmp when the condition is false.
15768         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15769             isX86LogicalCmp(Cmp) &&
15770             Op.getNode()->hasOneUse()) {
15771           X86::CondCode CCode =
15772             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15773           CCode = X86::GetOppositeBranchCondition(CCode);
15774           CC = DAG.getConstant(CCode, dl, MVT::i8);
15775           SDNode *User = *Op.getNode()->use_begin();
15776           // Look for an unconditional branch following this conditional branch.
15777           // We need this because we need to reverse the successors in order
15778           // to implement FCMP_OEQ.
15779           if (User->getOpcode() == ISD::BR) {
15780             SDValue FalseBB = User->getOperand(1);
15781             SDNode *NewBR =
15782               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15783             assert(NewBR == User);
15784             (void)NewBR;
15785             Dest = FalseBB;
15786
15787             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15788                                 Chain, Dest, CC, Cmp);
15789             X86::CondCode CCode =
15790               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15791             CCode = X86::GetOppositeBranchCondition(CCode);
15792             CC = DAG.getConstant(CCode, dl, MVT::i8);
15793             Cond = Cmp;
15794             addTest = false;
15795           }
15796         }
15797       }
15798     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15799       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15800       // It should be transformed during dag combiner except when the condition
15801       // is set by a arithmetics with overflow node.
15802       X86::CondCode CCode =
15803         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15804       CCode = X86::GetOppositeBranchCondition(CCode);
15805       CC = DAG.getConstant(CCode, dl, MVT::i8);
15806       Cond = Cond.getOperand(0).getOperand(1);
15807       addTest = false;
15808     } else if (Cond.getOpcode() == ISD::SETCC &&
15809                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15810       // For FCMP_OEQ, we can emit
15811       // two branches instead of an explicit AND instruction with a
15812       // separate test. However, we only do this if this block doesn't
15813       // have a fall-through edge, because this requires an explicit
15814       // jmp when the condition is false.
15815       if (Op.getNode()->hasOneUse()) {
15816         SDNode *User = *Op.getNode()->use_begin();
15817         // Look for an unconditional branch following this conditional branch.
15818         // We need this because we need to reverse the successors in order
15819         // to implement FCMP_OEQ.
15820         if (User->getOpcode() == ISD::BR) {
15821           SDValue FalseBB = User->getOperand(1);
15822           SDNode *NewBR =
15823             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15824           assert(NewBR == User);
15825           (void)NewBR;
15826           Dest = FalseBB;
15827
15828           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15829                                     Cond.getOperand(0), Cond.getOperand(1));
15830           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15831           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15832           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15833                               Chain, Dest, CC, Cmp);
15834           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15835           Cond = Cmp;
15836           addTest = false;
15837         }
15838       }
15839     } else if (Cond.getOpcode() == ISD::SETCC &&
15840                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15841       // For FCMP_UNE, we can emit
15842       // two branches instead of an explicit AND instruction with a
15843       // separate test. However, we only do this if this block doesn't
15844       // have a fall-through edge, because this requires an explicit
15845       // jmp when the condition is false.
15846       if (Op.getNode()->hasOneUse()) {
15847         SDNode *User = *Op.getNode()->use_begin();
15848         // Look for an unconditional branch following this conditional branch.
15849         // We need this because we need to reverse the successors in order
15850         // to implement FCMP_UNE.
15851         if (User->getOpcode() == ISD::BR) {
15852           SDValue FalseBB = User->getOperand(1);
15853           SDNode *NewBR =
15854             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15855           assert(NewBR == User);
15856           (void)NewBR;
15857
15858           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15859                                     Cond.getOperand(0), Cond.getOperand(1));
15860           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15861           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15862           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15863                               Chain, Dest, CC, Cmp);
15864           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15865           Cond = Cmp;
15866           addTest = false;
15867           Dest = FalseBB;
15868         }
15869       }
15870     }
15871   }
15872
15873   if (addTest) {
15874     // Look pass the truncate if the high bits are known zero.
15875     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15876         Cond = Cond.getOperand(0);
15877
15878     // We know the result of AND is compared against zero. Try to match
15879     // it to BT.
15880     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15881       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15882         CC = NewSetCC.getOperand(0);
15883         Cond = NewSetCC.getOperand(1);
15884         addTest = false;
15885       }
15886     }
15887   }
15888
15889   if (addTest) {
15890     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15891     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15892     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15893   }
15894   Cond = ConvertCmpIfNecessary(Cond, DAG);
15895   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15896                      Chain, Dest, CC, Cond);
15897 }
15898
15899 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15900 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15901 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15902 // that the guard pages used by the OS virtual memory manager are allocated in
15903 // correct sequence.
15904 SDValue
15905 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15906                                            SelectionDAG &DAG) const {
15907   MachineFunction &MF = DAG.getMachineFunction();
15908   bool SplitStack = MF.shouldSplitStack();
15909   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15910                SplitStack;
15911   SDLoc dl(Op);
15912
15913   // Get the inputs.
15914   SDNode *Node = Op.getNode();
15915   SDValue Chain = Op.getOperand(0);
15916   SDValue Size  = Op.getOperand(1);
15917   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15918   EVT VT = Node->getValueType(0);
15919
15920   // Chain the dynamic stack allocation so that it doesn't modify the stack
15921   // pointer when other instructions are using the stack.
15922   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15923
15924   bool Is64Bit = Subtarget->is64Bit();
15925   MVT SPTy = getPointerTy(DAG.getDataLayout());
15926
15927   SDValue Result;
15928   if (!Lower) {
15929     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15930     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15931     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15932                     " not tell us which reg is the stack pointer!");
15933     EVT VT = Node->getValueType(0);
15934     SDValue Tmp3 = Node->getOperand(2);
15935
15936     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15937     Chain = SP.getValue(1);
15938     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15939     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15940     unsigned StackAlign = TFI.getStackAlignment();
15941     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15942     if (Align > StackAlign)
15943       Result = DAG.getNode(ISD::AND, dl, VT, Result,
15944                          DAG.getConstant(-(uint64_t)Align, dl, VT));
15945     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15946   } else if (SplitStack) {
15947     MachineRegisterInfo &MRI = MF.getRegInfo();
15948
15949     if (Is64Bit) {
15950       // The 64 bit implementation of segmented stacks needs to clobber both r10
15951       // r11. This makes it impossible to use it along with nested parameters.
15952       const Function *F = MF.getFunction();
15953
15954       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15955            I != E; ++I)
15956         if (I->hasNestAttr())
15957           report_fatal_error("Cannot use segmented stacks with functions that "
15958                              "have nested arguments.");
15959     }
15960
15961     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15962     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15963     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15964     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15965                                 DAG.getRegister(Vreg, SPTy));
15966   } else {
15967     SDValue Flag;
15968     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15969
15970     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15971     Flag = Chain.getValue(1);
15972     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15973
15974     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15975
15976     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15977     unsigned SPReg = RegInfo->getStackRegister();
15978     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15979     Chain = SP.getValue(1);
15980
15981     if (Align) {
15982       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15983                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15984       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15985     }
15986
15987     Result = SP;
15988   }
15989
15990   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15991                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
15992
15993   SDValue Ops[2] = {Result, Chain};
15994   return DAG.getMergeValues(Ops, dl);
15995 }
15996
15997 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15998   MachineFunction &MF = DAG.getMachineFunction();
15999   auto PtrVT = getPointerTy(MF.getDataLayout());
16000   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16001
16002   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16003   SDLoc DL(Op);
16004
16005   if (!Subtarget->is64Bit() ||
16006       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
16007     // vastart just stores the address of the VarArgsFrameIndex slot into the
16008     // memory location argument.
16009     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16010     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16011                         MachinePointerInfo(SV), false, false, 0);
16012   }
16013
16014   // __va_list_tag:
16015   //   gp_offset         (0 - 6 * 8)
16016   //   fp_offset         (48 - 48 + 8 * 16)
16017   //   overflow_arg_area (point to parameters coming in memory).
16018   //   reg_save_area
16019   SmallVector<SDValue, 8> MemOps;
16020   SDValue FIN = Op.getOperand(1);
16021   // Store gp_offset
16022   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16023                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16024                                                DL, MVT::i32),
16025                                FIN, MachinePointerInfo(SV), false, false, 0);
16026   MemOps.push_back(Store);
16027
16028   // Store fp_offset
16029   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16030   Store = DAG.getStore(Op.getOperand(0), DL,
16031                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
16032                                        MVT::i32),
16033                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16034   MemOps.push_back(Store);
16035
16036   // Store ptr to overflow_arg_area
16037   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16038   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16039   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16040                        MachinePointerInfo(SV, 8),
16041                        false, false, 0);
16042   MemOps.push_back(Store);
16043
16044   // Store ptr to reg_save_area.
16045   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16046       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16047   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16048   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16049       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16050   MemOps.push_back(Store);
16051   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16052 }
16053
16054 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16055   assert(Subtarget->is64Bit() &&
16056          "LowerVAARG only handles 64-bit va_arg!");
16057   assert(Op.getNode()->getNumOperands() == 4);
16058
16059   MachineFunction &MF = DAG.getMachineFunction();
16060   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16061     // The Win64 ABI uses char* instead of a structure.
16062     return DAG.expandVAArg(Op.getNode());
16063
16064   SDValue Chain = Op.getOperand(0);
16065   SDValue SrcPtr = Op.getOperand(1);
16066   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16067   unsigned Align = Op.getConstantOperandVal(3);
16068   SDLoc dl(Op);
16069
16070   EVT ArgVT = Op.getNode()->getValueType(0);
16071   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16072   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16073   uint8_t ArgMode;
16074
16075   // Decide which area this value should be read from.
16076   // TODO: Implement the AMD64 ABI in its entirety. This simple
16077   // selection mechanism works only for the basic types.
16078   if (ArgVT == MVT::f80) {
16079     llvm_unreachable("va_arg for f80 not yet implemented");
16080   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16081     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16082   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16083     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16084   } else {
16085     llvm_unreachable("Unhandled argument type in LowerVAARG");
16086   }
16087
16088   if (ArgMode == 2) {
16089     // Sanity Check: Make sure using fp_offset makes sense.
16090     assert(!Subtarget->useSoftFloat() &&
16091            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16092            Subtarget->hasSSE1());
16093   }
16094
16095   // Insert VAARG_64 node into the DAG
16096   // VAARG_64 returns two values: Variable Argument Address, Chain
16097   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16098                        DAG.getConstant(ArgMode, dl, MVT::i8),
16099                        DAG.getConstant(Align, dl, MVT::i32)};
16100   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16101   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16102                                           VTs, InstOps, MVT::i64,
16103                                           MachinePointerInfo(SV),
16104                                           /*Align=*/0,
16105                                           /*Volatile=*/false,
16106                                           /*ReadMem=*/true,
16107                                           /*WriteMem=*/true);
16108   Chain = VAARG.getValue(1);
16109
16110   // Load the next argument and return it
16111   return DAG.getLoad(ArgVT, dl,
16112                      Chain,
16113                      VAARG,
16114                      MachinePointerInfo(),
16115                      false, false, false, 0);
16116 }
16117
16118 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16119                            SelectionDAG &DAG) {
16120   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16121   // where a va_list is still an i8*.
16122   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16123   if (Subtarget->isCallingConvWin64(
16124         DAG.getMachineFunction().getFunction()->getCallingConv()))
16125     // Probably a Win64 va_copy.
16126     return DAG.expandVACopy(Op.getNode());
16127
16128   SDValue Chain = Op.getOperand(0);
16129   SDValue DstPtr = Op.getOperand(1);
16130   SDValue SrcPtr = Op.getOperand(2);
16131   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16132   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16133   SDLoc DL(Op);
16134
16135   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16136                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16137                        false, false,
16138                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16139 }
16140
16141 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16142 // amount is a constant. Takes immediate version of shift as input.
16143 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16144                                           SDValue SrcOp, uint64_t ShiftAmt,
16145                                           SelectionDAG &DAG) {
16146   MVT ElementType = VT.getVectorElementType();
16147
16148   // Fold this packed shift into its first operand if ShiftAmt is 0.
16149   if (ShiftAmt == 0)
16150     return SrcOp;
16151
16152   // Check for ShiftAmt >= element width
16153   if (ShiftAmt >= ElementType.getSizeInBits()) {
16154     if (Opc == X86ISD::VSRAI)
16155       ShiftAmt = ElementType.getSizeInBits() - 1;
16156     else
16157       return DAG.getConstant(0, dl, VT);
16158   }
16159
16160   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16161          && "Unknown target vector shift-by-constant node");
16162
16163   // Fold this packed vector shift into a build vector if SrcOp is a
16164   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16165   if (VT == SrcOp.getSimpleValueType() &&
16166       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16167     SmallVector<SDValue, 8> Elts;
16168     unsigned NumElts = SrcOp->getNumOperands();
16169     ConstantSDNode *ND;
16170
16171     switch(Opc) {
16172     default: llvm_unreachable(nullptr);
16173     case X86ISD::VSHLI:
16174       for (unsigned i=0; i!=NumElts; ++i) {
16175         SDValue CurrentOp = SrcOp->getOperand(i);
16176         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16177           Elts.push_back(CurrentOp);
16178           continue;
16179         }
16180         ND = cast<ConstantSDNode>(CurrentOp);
16181         const APInt &C = ND->getAPIntValue();
16182         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16183       }
16184       break;
16185     case X86ISD::VSRLI:
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.lshr(ShiftAmt), dl, ElementType));
16195       }
16196       break;
16197     case X86ISD::VSRAI:
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.ashr(ShiftAmt), dl, ElementType));
16207       }
16208       break;
16209     }
16210
16211     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16212   }
16213
16214   return DAG.getNode(Opc, dl, VT, SrcOp,
16215                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
16216 }
16217
16218 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16219 // may or may not be a constant. Takes immediate version of shift as input.
16220 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16221                                    SDValue SrcOp, SDValue ShAmt,
16222                                    SelectionDAG &DAG) {
16223   MVT SVT = ShAmt.getSimpleValueType();
16224   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16225
16226   // Catch shift-by-constant.
16227   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16228     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16229                                       CShAmt->getZExtValue(), DAG);
16230
16231   // Change opcode to non-immediate version
16232   switch (Opc) {
16233     default: llvm_unreachable("Unknown target vector shift node");
16234     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16235     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16236     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16237   }
16238
16239   const X86Subtarget &Subtarget =
16240       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16241   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16242       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16243     // Let the shuffle legalizer expand this shift amount node.
16244     SDValue Op0 = ShAmt.getOperand(0);
16245     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16246     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16247   } else {
16248     // Need to build a vector containing shift amount.
16249     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16250     SmallVector<SDValue, 4> ShOps;
16251     ShOps.push_back(ShAmt);
16252     if (SVT == MVT::i32) {
16253       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16254       ShOps.push_back(DAG.getUNDEF(SVT));
16255     }
16256     ShOps.push_back(DAG.getUNDEF(SVT));
16257
16258     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16259     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16260   }
16261
16262   // The return type has to be a 128-bit type with the same element
16263   // type as the input type.
16264   MVT EltVT = VT.getVectorElementType();
16265   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16266
16267   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16268   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16269 }
16270
16271 /// \brief Return Mask with the necessary casting or extending
16272 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16273 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16274                            const X86Subtarget *Subtarget,
16275                            SelectionDAG &DAG, SDLoc dl) {
16276
16277   if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16278     // Mask should be extended
16279     Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16280                        MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16281   }
16282
16283   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16284     if (MaskVT == MVT::v64i1) {
16285       assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16286       // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16287       SDValue Lo, Hi;
16288       Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16289                           DAG.getConstant(0, dl, MVT::i32));
16290       Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16291                           DAG.getConstant(1, dl, MVT::i32));
16292
16293       Lo = DAG.getBitcast(MVT::v32i1, Lo);
16294       Hi = DAG.getBitcast(MVT::v32i1, Hi);
16295
16296       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16297     } else {
16298       // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16299       // and bitcast.
16300       MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16301       return DAG.getBitcast(MaskVT,
16302                             DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16303     }
16304
16305   } else {
16306     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16307                                      Mask.getSimpleValueType().getSizeInBits());
16308     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16309     // are extracted by EXTRACT_SUBVECTOR.
16310     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16311                        DAG.getBitcast(BitcastVT, Mask),
16312                        DAG.getIntPtrConstant(0, dl));
16313   }
16314 }
16315
16316 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16317 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16318 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16319 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16320                   SDValue PreservedSrc,
16321                   const X86Subtarget *Subtarget,
16322                   SelectionDAG &DAG) {
16323   MVT VT = Op.getSimpleValueType();
16324   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16325   unsigned OpcodeSelect = ISD::VSELECT;
16326   SDLoc dl(Op);
16327
16328   if (isAllOnesConstant(Mask))
16329     return Op;
16330
16331   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16332
16333   switch (Op.getOpcode()) {
16334   default: break;
16335   case X86ISD::PCMPEQM:
16336   case X86ISD::PCMPGTM:
16337   case X86ISD::CMPM:
16338   case X86ISD::CMPMU:
16339     return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16340   case X86ISD::VFPCLASS:
16341     case X86ISD::VFPCLASSS:
16342     return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16343   case X86ISD::VTRUNC:
16344   case X86ISD::VTRUNCS:
16345   case X86ISD::VTRUNCUS:
16346     // We can't use ISD::VSELECT here because it is not always "Legal"
16347     // for the destination type. For example vpmovqb require only AVX512
16348     // and vselect that can operate on byte element type require BWI
16349     OpcodeSelect = X86ISD::SELECT;
16350     break;
16351   }
16352   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16353     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16354   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16355 }
16356
16357 /// \brief Creates an SDNode for a predicated scalar operation.
16358 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16359 /// The mask is coming as MVT::i8 and it should be truncated
16360 /// to MVT::i1 while lowering masking intrinsics.
16361 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16362 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16363 /// for a scalar instruction.
16364 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16365                                     SDValue PreservedSrc,
16366                                     const X86Subtarget *Subtarget,
16367                                     SelectionDAG &DAG) {
16368   if (isAllOnesConstant(Mask))
16369     return Op;
16370
16371   MVT VT = Op.getSimpleValueType();
16372   SDLoc dl(Op);
16373   // The mask should be of type MVT::i1
16374   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16375
16376   if (Op.getOpcode() == X86ISD::FSETCC)
16377     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16378   if (Op.getOpcode() == X86ISD::VFPCLASS ||
16379       Op.getOpcode() == X86ISD::VFPCLASSS)
16380     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16381
16382   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16383     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16384   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16385 }
16386
16387 static int getSEHRegistrationNodeSize(const Function *Fn) {
16388   if (!Fn->hasPersonalityFn())
16389     report_fatal_error(
16390         "querying registration node size for function without personality");
16391   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16392   // WinEHStatePass for the full struct definition.
16393   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16394   case EHPersonality::MSVC_X86SEH: return 24;
16395   case EHPersonality::MSVC_CXX: return 16;
16396   default: break;
16397   }
16398   report_fatal_error(
16399       "can only recover FP for 32-bit MSVC EH personality functions");
16400 }
16401
16402 /// When the MSVC runtime transfers control to us, either to an outlined
16403 /// function or when returning to a parent frame after catching an exception, we
16404 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16405 /// Here's the math:
16406 ///   RegNodeBase = EntryEBP - RegNodeSize
16407 ///   ParentFP = RegNodeBase - ParentFrameOffset
16408 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16409 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16410 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16411                                    SDValue EntryEBP) {
16412   MachineFunction &MF = DAG.getMachineFunction();
16413   SDLoc dl;
16414
16415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16416   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16417
16418   // It's possible that the parent function no longer has a personality function
16419   // if the exceptional code was optimized away, in which case we just return
16420   // the incoming EBP.
16421   if (!Fn->hasPersonalityFn())
16422     return EntryEBP;
16423
16424   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16425   // registration, or the .set_setframe offset.
16426   MCSymbol *OffsetSym =
16427       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16428           GlobalValue::getRealLinkageName(Fn->getName()));
16429   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16430   SDValue ParentFrameOffset =
16431       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16432
16433   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16434   // prologue to RBP in the parent function.
16435   const X86Subtarget &Subtarget =
16436       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16437   if (Subtarget.is64Bit())
16438     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16439
16440   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16441   // RegNodeBase = EntryEBP - RegNodeSize
16442   // ParentFP = RegNodeBase - ParentFrameOffset
16443   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16444                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16445   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16446 }
16447
16448 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16449                                        SelectionDAG &DAG) {
16450   SDLoc dl(Op);
16451   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16452   MVT VT = Op.getSimpleValueType();
16453   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16454   if (IntrData) {
16455     switch(IntrData->Type) {
16456     case INTR_TYPE_1OP:
16457       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16458     case INTR_TYPE_2OP:
16459       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16460         Op.getOperand(2));
16461     case INTR_TYPE_2OP_IMM8:
16462       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16463                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16464     case INTR_TYPE_3OP:
16465       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16466         Op.getOperand(2), Op.getOperand(3));
16467     case INTR_TYPE_4OP:
16468       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16469         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16470     case INTR_TYPE_1OP_MASK_RM: {
16471       SDValue Src = Op.getOperand(1);
16472       SDValue PassThru = Op.getOperand(2);
16473       SDValue Mask = Op.getOperand(3);
16474       SDValue RoundingMode;
16475       // We allways add rounding mode to the Node.
16476       // If the rounding mode is not specified, we add the
16477       // "current direction" mode.
16478       if (Op.getNumOperands() == 4)
16479         RoundingMode =
16480           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16481       else
16482         RoundingMode = Op.getOperand(4);
16483       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16484       if (IntrWithRoundingModeOpcode != 0)
16485         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16486             X86::STATIC_ROUNDING::CUR_DIRECTION)
16487           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16488                                       dl, Op.getValueType(), Src, RoundingMode),
16489                                       Mask, PassThru, Subtarget, DAG);
16490       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16491                                               RoundingMode),
16492                                   Mask, PassThru, Subtarget, DAG);
16493     }
16494     case INTR_TYPE_1OP_MASK: {
16495       SDValue Src = Op.getOperand(1);
16496       SDValue PassThru = Op.getOperand(2);
16497       SDValue Mask = Op.getOperand(3);
16498       // We add rounding mode to the Node when
16499       //   - RM Opcode is specified and
16500       //   - RM is not "current direction".
16501       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16502       if (IntrWithRoundingModeOpcode != 0) {
16503         SDValue Rnd = Op.getOperand(4);
16504         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16505         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16506           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16507                                       dl, Op.getValueType(),
16508                                       Src, Rnd),
16509                                       Mask, PassThru, Subtarget, DAG);
16510         }
16511       }
16512       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16513                                   Mask, PassThru, Subtarget, DAG);
16514     }
16515     case INTR_TYPE_SCALAR_MASK: {
16516       SDValue Src1 = Op.getOperand(1);
16517       SDValue Src2 = Op.getOperand(2);
16518       SDValue passThru = Op.getOperand(3);
16519       SDValue Mask = Op.getOperand(4);
16520       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16521                                   Mask, passThru, Subtarget, DAG);
16522     }
16523     case INTR_TYPE_SCALAR_MASK_RM: {
16524       SDValue Src1 = Op.getOperand(1);
16525       SDValue Src2 = Op.getOperand(2);
16526       SDValue Src0 = Op.getOperand(3);
16527       SDValue Mask = Op.getOperand(4);
16528       // There are 2 kinds of intrinsics in this group:
16529       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16530       // (2) With rounding mode and sae - 7 operands.
16531       if (Op.getNumOperands() == 6) {
16532         SDValue Sae  = Op.getOperand(5);
16533         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16534         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16535                                                 Sae),
16536                                     Mask, Src0, Subtarget, DAG);
16537       }
16538       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16539       SDValue RoundingMode  = Op.getOperand(5);
16540       SDValue Sae  = Op.getOperand(6);
16541       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16542                                               RoundingMode, Sae),
16543                                   Mask, Src0, Subtarget, DAG);
16544     }
16545     case INTR_TYPE_2OP_MASK:
16546     case INTR_TYPE_2OP_IMM8_MASK: {
16547       SDValue Src1 = Op.getOperand(1);
16548       SDValue Src2 = Op.getOperand(2);
16549       SDValue PassThru = Op.getOperand(3);
16550       SDValue Mask = Op.getOperand(4);
16551
16552       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16553         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16554
16555       // We specify 2 possible opcodes for intrinsics with rounding modes.
16556       // First, we check if the intrinsic may have non-default rounding mode,
16557       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16558       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16559       if (IntrWithRoundingModeOpcode != 0) {
16560         SDValue Rnd = Op.getOperand(5);
16561         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16562         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16563           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16564                                       dl, Op.getValueType(),
16565                                       Src1, Src2, Rnd),
16566                                       Mask, PassThru, Subtarget, DAG);
16567         }
16568       }
16569       // TODO: Intrinsics should have fast-math-flags to propagate.
16570       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16571                                   Mask, PassThru, Subtarget, DAG);
16572     }
16573     case INTR_TYPE_2OP_MASK_RM: {
16574       SDValue Src1 = Op.getOperand(1);
16575       SDValue Src2 = Op.getOperand(2);
16576       SDValue PassThru = Op.getOperand(3);
16577       SDValue Mask = Op.getOperand(4);
16578       // We specify 2 possible modes for intrinsics, with/without rounding
16579       // modes.
16580       // First, we check if the intrinsic have rounding mode (6 operands),
16581       // if not, we set rounding mode to "current".
16582       SDValue Rnd;
16583       if (Op.getNumOperands() == 6)
16584         Rnd = Op.getOperand(5);
16585       else
16586         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16587       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16588                                               Src1, Src2, Rnd),
16589                                   Mask, PassThru, Subtarget, DAG);
16590     }
16591     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16592       SDValue Src1 = Op.getOperand(1);
16593       SDValue Src2 = Op.getOperand(2);
16594       SDValue Src3 = Op.getOperand(3);
16595       SDValue PassThru = Op.getOperand(4);
16596       SDValue Mask = Op.getOperand(5);
16597       SDValue Sae  = Op.getOperand(6);
16598
16599       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16600                                               Src2, Src3, Sae),
16601                                   Mask, PassThru, Subtarget, DAG);
16602     }
16603     case INTR_TYPE_3OP_MASK_RM: {
16604       SDValue Src1 = Op.getOperand(1);
16605       SDValue Src2 = Op.getOperand(2);
16606       SDValue Imm = Op.getOperand(3);
16607       SDValue PassThru = Op.getOperand(4);
16608       SDValue Mask = Op.getOperand(5);
16609       // We specify 2 possible modes for intrinsics, with/without rounding
16610       // modes.
16611       // First, we check if the intrinsic have rounding mode (7 operands),
16612       // if not, we set rounding mode to "current".
16613       SDValue Rnd;
16614       if (Op.getNumOperands() == 7)
16615         Rnd = Op.getOperand(6);
16616       else
16617         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16618       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16619         Src1, Src2, Imm, Rnd),
16620         Mask, PassThru, Subtarget, DAG);
16621     }
16622     case INTR_TYPE_3OP_IMM8_MASK:
16623     case INTR_TYPE_3OP_MASK:
16624     case INSERT_SUBVEC: {
16625       SDValue Src1 = Op.getOperand(1);
16626       SDValue Src2 = Op.getOperand(2);
16627       SDValue Src3 = Op.getOperand(3);
16628       SDValue PassThru = Op.getOperand(4);
16629       SDValue Mask = Op.getOperand(5);
16630
16631       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16632         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16633       else if (IntrData->Type == INSERT_SUBVEC) {
16634         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16635         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16636         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16637         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16638         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16639       }
16640
16641       // We specify 2 possible opcodes for intrinsics with rounding modes.
16642       // First, we check if the intrinsic may have non-default rounding mode,
16643       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16644       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16645       if (IntrWithRoundingModeOpcode != 0) {
16646         SDValue Rnd = Op.getOperand(6);
16647         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16648         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16649           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16650                                       dl, Op.getValueType(),
16651                                       Src1, Src2, Src3, Rnd),
16652                                       Mask, PassThru, Subtarget, DAG);
16653         }
16654       }
16655       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16656                                               Src1, Src2, Src3),
16657                                   Mask, PassThru, Subtarget, DAG);
16658     }
16659     case VPERM_3OP_MASKZ:
16660     case VPERM_3OP_MASK:{
16661       // Src2 is the PassThru
16662       SDValue Src1 = Op.getOperand(1);
16663       SDValue Src2 = Op.getOperand(2);
16664       SDValue Src3 = Op.getOperand(3);
16665       SDValue Mask = Op.getOperand(4);
16666       MVT VT = Op.getSimpleValueType();
16667       SDValue PassThru = SDValue();
16668
16669       // set PassThru element
16670       if (IntrData->Type == VPERM_3OP_MASKZ)
16671         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16672       else
16673         PassThru = DAG.getBitcast(VT, Src2);
16674
16675       // Swap Src1 and Src2 in the node creation
16676       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16677                                               dl, Op.getValueType(),
16678                                               Src2, Src1, Src3),
16679                                   Mask, PassThru, Subtarget, DAG);
16680     }
16681     case FMA_OP_MASK3:
16682     case FMA_OP_MASKZ:
16683     case FMA_OP_MASK: {
16684       SDValue Src1 = Op.getOperand(1);
16685       SDValue Src2 = Op.getOperand(2);
16686       SDValue Src3 = Op.getOperand(3);
16687       SDValue Mask = Op.getOperand(4);
16688       MVT VT = Op.getSimpleValueType();
16689       SDValue PassThru = SDValue();
16690
16691       // set PassThru element
16692       if (IntrData->Type == FMA_OP_MASKZ)
16693         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16694       else if (IntrData->Type == FMA_OP_MASK3)
16695         PassThru = Src3;
16696       else
16697         PassThru = Src1;
16698
16699       // We specify 2 possible opcodes for intrinsics with rounding modes.
16700       // First, we check if the intrinsic may have non-default rounding mode,
16701       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16702       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16703       if (IntrWithRoundingModeOpcode != 0) {
16704         SDValue Rnd = Op.getOperand(5);
16705         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16706             X86::STATIC_ROUNDING::CUR_DIRECTION)
16707           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16708                                                   dl, Op.getValueType(),
16709                                                   Src1, Src2, Src3, Rnd),
16710                                       Mask, PassThru, Subtarget, DAG);
16711       }
16712       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16713                                               dl, Op.getValueType(),
16714                                               Src1, Src2, Src3),
16715                                   Mask, PassThru, Subtarget, DAG);
16716     }
16717     case TERLOG_OP_MASK:
16718     case TERLOG_OP_MASKZ: {
16719       SDValue Src1 = Op.getOperand(1);
16720       SDValue Src2 = Op.getOperand(2);
16721       SDValue Src3 = Op.getOperand(3);
16722       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16723       SDValue Mask = Op.getOperand(5);
16724       MVT VT = Op.getSimpleValueType();
16725       SDValue PassThru = Src1;
16726       // Set PassThru element.
16727       if (IntrData->Type == TERLOG_OP_MASKZ)
16728         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16729
16730       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16731                                               Src1, Src2, Src3, Src4),
16732                                   Mask, PassThru, Subtarget, DAG);
16733     }
16734     case FPCLASS: {
16735       // FPclass intrinsics with mask
16736        SDValue Src1 = Op.getOperand(1);
16737        MVT VT = Src1.getSimpleValueType();
16738        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16739        SDValue Imm = Op.getOperand(2);
16740        SDValue Mask = Op.getOperand(3);
16741        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16742                                      Mask.getSimpleValueType().getSizeInBits());
16743        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16744        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16745                                                  DAG.getTargetConstant(0, dl, MaskVT),
16746                                                  Subtarget, DAG);
16747        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16748                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16749                                  DAG.getIntPtrConstant(0, dl));
16750        return DAG.getBitcast(Op.getValueType(), Res);
16751     }
16752     case FPCLASSS: {
16753       SDValue Src1 = Op.getOperand(1);
16754       SDValue Imm = Op.getOperand(2);
16755       SDValue Mask = Op.getOperand(3);
16756       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16757       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16758         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16759       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16760     }
16761     case CMP_MASK:
16762     case CMP_MASK_CC: {
16763       // Comparison intrinsics with masks.
16764       // Example of transformation:
16765       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16766       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16767       // (i8 (bitcast
16768       //   (v8i1 (insert_subvector undef,
16769       //           (v2i1 (and (PCMPEQM %a, %b),
16770       //                      (extract_subvector
16771       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16772       MVT VT = Op.getOperand(1).getSimpleValueType();
16773       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16774       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16775       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16776                                        Mask.getSimpleValueType().getSizeInBits());
16777       SDValue Cmp;
16778       if (IntrData->Type == CMP_MASK_CC) {
16779         SDValue CC = Op.getOperand(3);
16780         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16781         // We specify 2 possible opcodes for intrinsics with rounding modes.
16782         // First, we check if the intrinsic may have non-default rounding mode,
16783         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16784         if (IntrData->Opc1 != 0) {
16785           SDValue Rnd = Op.getOperand(5);
16786           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16787               X86::STATIC_ROUNDING::CUR_DIRECTION)
16788             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16789                               Op.getOperand(2), CC, Rnd);
16790         }
16791         //default rounding mode
16792         if(!Cmp.getNode())
16793             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16794                               Op.getOperand(2), CC);
16795
16796       } else {
16797         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16798         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16799                           Op.getOperand(2));
16800       }
16801       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16802                                              DAG.getTargetConstant(0, dl,
16803                                                                    MaskVT),
16804                                              Subtarget, DAG);
16805       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16806                                 DAG.getUNDEF(BitcastVT), CmpMask,
16807                                 DAG.getIntPtrConstant(0, dl));
16808       return DAG.getBitcast(Op.getValueType(), Res);
16809     }
16810     case CMP_MASK_SCALAR_CC: {
16811       SDValue Src1 = Op.getOperand(1);
16812       SDValue Src2 = Op.getOperand(2);
16813       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16814       SDValue Mask = Op.getOperand(4);
16815
16816       SDValue Cmp;
16817       if (IntrData->Opc1 != 0) {
16818         SDValue Rnd = Op.getOperand(5);
16819         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16820             X86::STATIC_ROUNDING::CUR_DIRECTION)
16821           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16822       }
16823       //default rounding mode
16824       if(!Cmp.getNode())
16825         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16826
16827       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16828                                              DAG.getTargetConstant(0, dl,
16829                                                                    MVT::i1),
16830                                              Subtarget, DAG);
16831
16832       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16833                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16834                          DAG.getValueType(MVT::i1));
16835     }
16836     case COMI: { // Comparison intrinsics
16837       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16838       SDValue LHS = Op.getOperand(1);
16839       SDValue RHS = Op.getOperand(2);
16840       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16841       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16842       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16843       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16844                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16845       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16846     }
16847     case COMI_RM: { // Comparison intrinsics with Sae
16848       SDValue LHS = Op.getOperand(1);
16849       SDValue RHS = Op.getOperand(2);
16850       SDValue CC = Op.getOperand(3);
16851       SDValue Sae = Op.getOperand(4);
16852       auto ComiType = TranslateX86ConstCondToX86CC(CC);
16853       // choose between ordered and unordered (comi/ucomi)
16854       unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16855       SDValue Cond;
16856       if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16857                                            X86::STATIC_ROUNDING::CUR_DIRECTION)
16858         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16859       else
16860         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16861       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16862         DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16863       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16864     }
16865     case VSHIFT:
16866       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16867                                  Op.getOperand(1), Op.getOperand(2), DAG);
16868     case VSHIFT_MASK:
16869       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16870                                                       Op.getSimpleValueType(),
16871                                                       Op.getOperand(1),
16872                                                       Op.getOperand(2), DAG),
16873                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16874                                   DAG);
16875     case COMPRESS_EXPAND_IN_REG: {
16876       SDValue Mask = Op.getOperand(3);
16877       SDValue DataToCompress = Op.getOperand(1);
16878       SDValue PassThru = Op.getOperand(2);
16879       if (isAllOnesConstant(Mask)) // return data as is
16880         return Op.getOperand(1);
16881
16882       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16883                                               DataToCompress),
16884                                   Mask, PassThru, Subtarget, DAG);
16885     }
16886     case BROADCASTM: {
16887       SDValue Mask = Op.getOperand(1);
16888       MVT MaskVT = MVT::getVectorVT(MVT::i1,
16889                                     Mask.getSimpleValueType().getSizeInBits());
16890       Mask = DAG.getBitcast(MaskVT, Mask);
16891       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16892     }
16893     case BLEND: {
16894       SDValue Mask = Op.getOperand(3);
16895       MVT VT = Op.getSimpleValueType();
16896       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16897       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16898       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16899                          Op.getOperand(2));
16900     }
16901     case KUNPCK: {
16902       MVT VT = Op.getSimpleValueType();
16903       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16904
16905       SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16906       SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16907       // Arguments should be swapped.
16908       SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16909                                 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16910                                 Src2, Src1);
16911       return DAG.getBitcast(VT, Res);
16912     }
16913     case CONVERT_TO_MASK: {
16914       MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16915       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16916       MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16917
16918       SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16919                                     Op.getOperand(1));
16920       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16921                                 DAG.getUNDEF(BitcastVT), CvtMask,
16922                                 DAG.getIntPtrConstant(0, dl));
16923       return DAG.getBitcast(Op.getValueType(), Res);
16924     }
16925     case CONVERT_MASK_TO_VEC: {
16926       SDValue Mask = Op.getOperand(1);
16927       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16928       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16929       return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16930     }
16931     case BRCST_SUBVEC_TO_VEC: {
16932       SDValue Src = Op.getOperand(1);
16933       SDValue Passthru = Op.getOperand(2);
16934       SDValue Mask = Op.getOperand(3);
16935       EVT resVT = Passthru.getValueType();
16936       SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16937                                        DAG.getUNDEF(resVT), Src,
16938                                        DAG.getIntPtrConstant(0, dl));
16939       SDValue immVal;
16940       if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16941         immVal = DAG.getConstant(0x44, dl, MVT::i8);
16942       else
16943         immVal = DAG.getConstant(0, dl, MVT::i8);
16944       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16945                                               subVec, subVec, immVal),
16946                                   Mask, Passthru, Subtarget, DAG);
16947     }
16948     default:
16949       break;
16950     }
16951   }
16952
16953   switch (IntNo) {
16954   default: return SDValue();    // Don't custom lower most intrinsics.
16955
16956   case Intrinsic::x86_avx2_permd:
16957   case Intrinsic::x86_avx2_permps:
16958     // Operands intentionally swapped. Mask is last operand to intrinsic,
16959     // but second operand for node/instruction.
16960     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16961                        Op.getOperand(2), Op.getOperand(1));
16962
16963   // ptest and testp intrinsics. The intrinsic these come from are designed to
16964   // return an integer value, not just an instruction so lower it to the ptest
16965   // or testp pattern and a setcc for the result.
16966   case Intrinsic::x86_sse41_ptestz:
16967   case Intrinsic::x86_sse41_ptestc:
16968   case Intrinsic::x86_sse41_ptestnzc:
16969   case Intrinsic::x86_avx_ptestz_256:
16970   case Intrinsic::x86_avx_ptestc_256:
16971   case Intrinsic::x86_avx_ptestnzc_256:
16972   case Intrinsic::x86_avx_vtestz_ps:
16973   case Intrinsic::x86_avx_vtestc_ps:
16974   case Intrinsic::x86_avx_vtestnzc_ps:
16975   case Intrinsic::x86_avx_vtestz_pd:
16976   case Intrinsic::x86_avx_vtestc_pd:
16977   case Intrinsic::x86_avx_vtestnzc_pd:
16978   case Intrinsic::x86_avx_vtestz_ps_256:
16979   case Intrinsic::x86_avx_vtestc_ps_256:
16980   case Intrinsic::x86_avx_vtestnzc_ps_256:
16981   case Intrinsic::x86_avx_vtestz_pd_256:
16982   case Intrinsic::x86_avx_vtestc_pd_256:
16983   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16984     bool IsTestPacked = false;
16985     unsigned X86CC;
16986     switch (IntNo) {
16987     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16988     case Intrinsic::x86_avx_vtestz_ps:
16989     case Intrinsic::x86_avx_vtestz_pd:
16990     case Intrinsic::x86_avx_vtestz_ps_256:
16991     case Intrinsic::x86_avx_vtestz_pd_256:
16992       IsTestPacked = true; // Fallthrough
16993     case Intrinsic::x86_sse41_ptestz:
16994     case Intrinsic::x86_avx_ptestz_256:
16995       // ZF = 1
16996       X86CC = X86::COND_E;
16997       break;
16998     case Intrinsic::x86_avx_vtestc_ps:
16999     case Intrinsic::x86_avx_vtestc_pd:
17000     case Intrinsic::x86_avx_vtestc_ps_256:
17001     case Intrinsic::x86_avx_vtestc_pd_256:
17002       IsTestPacked = true; // Fallthrough
17003     case Intrinsic::x86_sse41_ptestc:
17004     case Intrinsic::x86_avx_ptestc_256:
17005       // CF = 1
17006       X86CC = X86::COND_B;
17007       break;
17008     case Intrinsic::x86_avx_vtestnzc_ps:
17009     case Intrinsic::x86_avx_vtestnzc_pd:
17010     case Intrinsic::x86_avx_vtestnzc_ps_256:
17011     case Intrinsic::x86_avx_vtestnzc_pd_256:
17012       IsTestPacked = true; // Fallthrough
17013     case Intrinsic::x86_sse41_ptestnzc:
17014     case Intrinsic::x86_avx_ptestnzc_256:
17015       // ZF and CF = 0
17016       X86CC = X86::COND_A;
17017       break;
17018     }
17019
17020     SDValue LHS = Op.getOperand(1);
17021     SDValue RHS = Op.getOperand(2);
17022     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17023     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17024     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17025     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17026     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17027   }
17028   case Intrinsic::x86_avx512_kortestz_w:
17029   case Intrinsic::x86_avx512_kortestc_w: {
17030     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17031     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
17032     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
17033     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17034     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17035     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17036     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17037   }
17038
17039   case Intrinsic::x86_sse42_pcmpistria128:
17040   case Intrinsic::x86_sse42_pcmpestria128:
17041   case Intrinsic::x86_sse42_pcmpistric128:
17042   case Intrinsic::x86_sse42_pcmpestric128:
17043   case Intrinsic::x86_sse42_pcmpistrio128:
17044   case Intrinsic::x86_sse42_pcmpestrio128:
17045   case Intrinsic::x86_sse42_pcmpistris128:
17046   case Intrinsic::x86_sse42_pcmpestris128:
17047   case Intrinsic::x86_sse42_pcmpistriz128:
17048   case Intrinsic::x86_sse42_pcmpestriz128: {
17049     unsigned Opcode;
17050     unsigned X86CC;
17051     switch (IntNo) {
17052     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17053     case Intrinsic::x86_sse42_pcmpistria128:
17054       Opcode = X86ISD::PCMPISTRI;
17055       X86CC = X86::COND_A;
17056       break;
17057     case Intrinsic::x86_sse42_pcmpestria128:
17058       Opcode = X86ISD::PCMPESTRI;
17059       X86CC = X86::COND_A;
17060       break;
17061     case Intrinsic::x86_sse42_pcmpistric128:
17062       Opcode = X86ISD::PCMPISTRI;
17063       X86CC = X86::COND_B;
17064       break;
17065     case Intrinsic::x86_sse42_pcmpestric128:
17066       Opcode = X86ISD::PCMPESTRI;
17067       X86CC = X86::COND_B;
17068       break;
17069     case Intrinsic::x86_sse42_pcmpistrio128:
17070       Opcode = X86ISD::PCMPISTRI;
17071       X86CC = X86::COND_O;
17072       break;
17073     case Intrinsic::x86_sse42_pcmpestrio128:
17074       Opcode = X86ISD::PCMPESTRI;
17075       X86CC = X86::COND_O;
17076       break;
17077     case Intrinsic::x86_sse42_pcmpistris128:
17078       Opcode = X86ISD::PCMPISTRI;
17079       X86CC = X86::COND_S;
17080       break;
17081     case Intrinsic::x86_sse42_pcmpestris128:
17082       Opcode = X86ISD::PCMPESTRI;
17083       X86CC = X86::COND_S;
17084       break;
17085     case Intrinsic::x86_sse42_pcmpistriz128:
17086       Opcode = X86ISD::PCMPISTRI;
17087       X86CC = X86::COND_E;
17088       break;
17089     case Intrinsic::x86_sse42_pcmpestriz128:
17090       Opcode = X86ISD::PCMPESTRI;
17091       X86CC = X86::COND_E;
17092       break;
17093     }
17094     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17095     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17096     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17097     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17098                                 DAG.getConstant(X86CC, dl, MVT::i8),
17099                                 SDValue(PCMP.getNode(), 1));
17100     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17101   }
17102
17103   case Intrinsic::x86_sse42_pcmpistri128:
17104   case Intrinsic::x86_sse42_pcmpestri128: {
17105     unsigned Opcode;
17106     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17107       Opcode = X86ISD::PCMPISTRI;
17108     else
17109       Opcode = X86ISD::PCMPESTRI;
17110
17111     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17112     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17113     return DAG.getNode(Opcode, dl, VTs, NewOps);
17114   }
17115
17116   case Intrinsic::x86_seh_lsda: {
17117     // Compute the symbol for the LSDA. We know it'll get emitted later.
17118     MachineFunction &MF = DAG.getMachineFunction();
17119     SDValue Op1 = Op.getOperand(1);
17120     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17121     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17122         GlobalValue::getRealLinkageName(Fn->getName()));
17123
17124     // Generate a simple absolute symbol reference. This intrinsic is only
17125     // supported on 32-bit Windows, which isn't PIC.
17126     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17127     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17128   }
17129
17130   case Intrinsic::x86_seh_recoverfp: {
17131     SDValue FnOp = Op.getOperand(1);
17132     SDValue IncomingFPOp = Op.getOperand(2);
17133     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17134     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17135     if (!Fn)
17136       report_fatal_error(
17137           "llvm.x86.seh.recoverfp must take a function as the first argument");
17138     return recoverFramePointer(DAG, Fn, IncomingFPOp);
17139   }
17140
17141   case Intrinsic::localaddress: {
17142     // Returns one of the stack, base, or frame pointer registers, depending on
17143     // which is used to reference local variables.
17144     MachineFunction &MF = DAG.getMachineFunction();
17145     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17146     unsigned Reg;
17147     if (RegInfo->hasBasePointer(MF))
17148       Reg = RegInfo->getBaseRegister();
17149     else // This function handles the SP or FP case.
17150       Reg = RegInfo->getPtrSizedFrameRegister(MF);
17151     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17152   }
17153   }
17154 }
17155
17156 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17157                               SDValue Src, SDValue Mask, SDValue Base,
17158                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17159                               const X86Subtarget * Subtarget) {
17160   SDLoc dl(Op);
17161   auto *C = cast<ConstantSDNode>(ScaleOp);
17162   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17163   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17164                              Index.getSimpleValueType().getVectorNumElements());
17165   SDValue MaskInReg;
17166   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17167   if (MaskC)
17168     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17169   else {
17170     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17171                                      Mask.getSimpleValueType().getSizeInBits());
17172
17173     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17174     // are extracted by EXTRACT_SUBVECTOR.
17175     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17176                             DAG.getBitcast(BitcastVT, Mask),
17177                             DAG.getIntPtrConstant(0, dl));
17178   }
17179   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17180   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17181   SDValue Segment = DAG.getRegister(0, MVT::i32);
17182   if (Src.getOpcode() == ISD::UNDEF)
17183     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17184   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17185   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17186   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17187   return DAG.getMergeValues(RetOps, dl);
17188 }
17189
17190 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17191                                SDValue Src, SDValue Mask, SDValue Base,
17192                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17193   SDLoc dl(Op);
17194   auto *C = cast<ConstantSDNode>(ScaleOp);
17195   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17196   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17197   SDValue Segment = DAG.getRegister(0, MVT::i32);
17198   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17199                              Index.getSimpleValueType().getVectorNumElements());
17200   SDValue MaskInReg;
17201   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17202   if (MaskC)
17203     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17204   else {
17205     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17206                                      Mask.getSimpleValueType().getSizeInBits());
17207
17208     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17209     // are extracted by EXTRACT_SUBVECTOR.
17210     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17211                             DAG.getBitcast(BitcastVT, Mask),
17212                             DAG.getIntPtrConstant(0, dl));
17213   }
17214   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17215   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17216   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17217   return SDValue(Res, 1);
17218 }
17219
17220 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17221                                SDValue Mask, SDValue Base, SDValue Index,
17222                                SDValue ScaleOp, SDValue Chain) {
17223   SDLoc dl(Op);
17224   auto *C = cast<ConstantSDNode>(ScaleOp);
17225   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17226   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17227   SDValue Segment = DAG.getRegister(0, MVT::i32);
17228   MVT MaskVT =
17229     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17230   SDValue MaskInReg;
17231   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17232   if (MaskC)
17233     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17234   else
17235     MaskInReg = DAG.getBitcast(MaskVT, Mask);
17236   //SDVTList VTs = DAG.getVTList(MVT::Other);
17237   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17238   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17239   return SDValue(Res, 0);
17240 }
17241
17242 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17243 // read performance monitor counters (x86_rdpmc).
17244 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17245                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17246                               SmallVectorImpl<SDValue> &Results) {
17247   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17248   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17249   SDValue LO, HI;
17250
17251   // The ECX register is used to select the index of the performance counter
17252   // to read.
17253   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17254                                    N->getOperand(2));
17255   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17256
17257   // Reads the content of a 64-bit performance counter and returns it in the
17258   // registers EDX:EAX.
17259   if (Subtarget->is64Bit()) {
17260     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17261     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17262                             LO.getValue(2));
17263   } else {
17264     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17265     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17266                             LO.getValue(2));
17267   }
17268   Chain = HI.getValue(1);
17269
17270   if (Subtarget->is64Bit()) {
17271     // The EAX register is loaded with the low-order 32 bits. The EDX register
17272     // is loaded with the supported high-order bits of the counter.
17273     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17274                               DAG.getConstant(32, DL, MVT::i8));
17275     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17276     Results.push_back(Chain);
17277     return;
17278   }
17279
17280   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17281   SDValue Ops[] = { LO, HI };
17282   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17283   Results.push_back(Pair);
17284   Results.push_back(Chain);
17285 }
17286
17287 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17288 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17289 // also used to custom lower READCYCLECOUNTER nodes.
17290 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17291                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17292                               SmallVectorImpl<SDValue> &Results) {
17293   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17294   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17295   SDValue LO, HI;
17296
17297   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17298   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17299   // and the EAX register is loaded with the low-order 32 bits.
17300   if (Subtarget->is64Bit()) {
17301     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17302     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17303                             LO.getValue(2));
17304   } else {
17305     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17306     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17307                             LO.getValue(2));
17308   }
17309   SDValue Chain = HI.getValue(1);
17310
17311   if (Opcode == X86ISD::RDTSCP_DAG) {
17312     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17313
17314     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17315     // the ECX register. Add 'ecx' explicitly to the chain.
17316     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17317                                      HI.getValue(2));
17318     // Explicitly store the content of ECX at the location passed in input
17319     // to the 'rdtscp' intrinsic.
17320     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17321                          MachinePointerInfo(), false, false, 0);
17322   }
17323
17324   if (Subtarget->is64Bit()) {
17325     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17326     // the EAX register is loaded with the low-order 32 bits.
17327     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17328                               DAG.getConstant(32, DL, MVT::i8));
17329     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17330     Results.push_back(Chain);
17331     return;
17332   }
17333
17334   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17335   SDValue Ops[] = { LO, HI };
17336   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17337   Results.push_back(Pair);
17338   Results.push_back(Chain);
17339 }
17340
17341 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17342                                      SelectionDAG &DAG) {
17343   SmallVector<SDValue, 2> Results;
17344   SDLoc DL(Op);
17345   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17346                           Results);
17347   return DAG.getMergeValues(Results, DL);
17348 }
17349
17350 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17351   MachineFunction &MF = DAG.getMachineFunction();
17352   SDValue Chain = Op.getOperand(0);
17353   SDValue RegNode = Op.getOperand(2);
17354   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17355   if (!EHInfo)
17356     report_fatal_error("EH registrations only live in functions using WinEH");
17357
17358   // Cast the operand to an alloca, and remember the frame index.
17359   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17360   if (!FINode)
17361     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17362   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17363
17364   // Return the chain operand without making any DAG nodes.
17365   return Chain;
17366 }
17367
17368 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17369 /// return truncate Store/MaskedStore Node
17370 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17371                                                SelectionDAG &DAG,
17372                                                MVT ElementType) {
17373   SDLoc dl(Op);
17374   SDValue Mask = Op.getOperand(4);
17375   SDValue DataToTruncate = Op.getOperand(3);
17376   SDValue Addr = Op.getOperand(2);
17377   SDValue Chain = Op.getOperand(0);
17378
17379   MVT VT  = DataToTruncate.getSimpleValueType();
17380   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17381
17382   if (isAllOnesConstant(Mask)) // return just a truncate store
17383     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17384                              MachinePointerInfo(), SVT, false, false,
17385                              SVT.getScalarSizeInBits()/8);
17386
17387   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17388   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17389                                    Mask.getSimpleValueType().getSizeInBits());
17390   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17391   // are extracted by EXTRACT_SUBVECTOR.
17392   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17393                               DAG.getBitcast(BitcastVT, Mask),
17394                               DAG.getIntPtrConstant(0, dl));
17395
17396   MachineMemOperand *MMO = DAG.getMachineFunction().
17397     getMachineMemOperand(MachinePointerInfo(),
17398                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17399                          SVT.getScalarSizeInBits()/8);
17400
17401   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17402                             VMask, SVT, MMO, true);
17403 }
17404
17405 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17406                                       SelectionDAG &DAG) {
17407   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17408
17409   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17410   if (!IntrData) {
17411     if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17412       return MarkEHRegistrationNode(Op, DAG);
17413     if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17414         IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17415         IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17416         IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17417       // We need a frame pointer because this will get lowered to a PUSH/POP
17418       // sequence.
17419       MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17420       MFI->setHasOpaqueSPAdjustment(true);
17421       // Don't do anything here, we will expand these intrinsics out later
17422       // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17423       return SDValue();
17424     }
17425     return SDValue();
17426   }
17427
17428   SDLoc dl(Op);
17429   switch(IntrData->Type) {
17430   default: llvm_unreachable("Unknown Intrinsic Type");
17431   case RDSEED:
17432   case RDRAND: {
17433     // Emit the node with the right value type.
17434     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17435     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17436
17437     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17438     // Otherwise return the value from Rand, which is always 0, casted to i32.
17439     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17440                       DAG.getConstant(1, dl, Op->getValueType(1)),
17441                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17442                       SDValue(Result.getNode(), 1) };
17443     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17444                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17445                                   Ops);
17446
17447     // Return { result, isValid, chain }.
17448     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17449                        SDValue(Result.getNode(), 2));
17450   }
17451   case GATHER: {
17452   //gather(v1, mask, index, base, scale);
17453     SDValue Chain = Op.getOperand(0);
17454     SDValue Src   = Op.getOperand(2);
17455     SDValue Base  = Op.getOperand(3);
17456     SDValue Index = Op.getOperand(4);
17457     SDValue Mask  = Op.getOperand(5);
17458     SDValue Scale = Op.getOperand(6);
17459     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17460                          Chain, Subtarget);
17461   }
17462   case SCATTER: {
17463   //scatter(base, mask, index, v1, scale);
17464     SDValue Chain = Op.getOperand(0);
17465     SDValue Base  = Op.getOperand(2);
17466     SDValue Mask  = Op.getOperand(3);
17467     SDValue Index = Op.getOperand(4);
17468     SDValue Src   = Op.getOperand(5);
17469     SDValue Scale = Op.getOperand(6);
17470     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17471                           Scale, Chain);
17472   }
17473   case PREFETCH: {
17474     SDValue Hint = Op.getOperand(6);
17475     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17476     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17477     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17478     SDValue Chain = Op.getOperand(0);
17479     SDValue Mask  = Op.getOperand(2);
17480     SDValue Index = Op.getOperand(3);
17481     SDValue Base  = Op.getOperand(4);
17482     SDValue Scale = Op.getOperand(5);
17483     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17484   }
17485   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17486   case RDTSC: {
17487     SmallVector<SDValue, 2> Results;
17488     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17489                             Results);
17490     return DAG.getMergeValues(Results, dl);
17491   }
17492   // Read Performance Monitoring Counters.
17493   case RDPMC: {
17494     SmallVector<SDValue, 2> Results;
17495     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17496     return DAG.getMergeValues(Results, dl);
17497   }
17498   // XTEST intrinsics.
17499   case XTEST: {
17500     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17501     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17502     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17503                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17504                                 InTrans);
17505     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17506     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17507                        Ret, SDValue(InTrans.getNode(), 1));
17508   }
17509   // ADC/ADCX/SBB
17510   case ADX: {
17511     SmallVector<SDValue, 2> Results;
17512     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17513     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17514     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17515                                 DAG.getConstant(-1, dl, MVT::i8));
17516     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17517                               Op.getOperand(4), GenCF.getValue(1));
17518     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17519                                  Op.getOperand(5), MachinePointerInfo(),
17520                                  false, false, 0);
17521     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17522                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17523                                 Res.getValue(1));
17524     Results.push_back(SetCC);
17525     Results.push_back(Store);
17526     return DAG.getMergeValues(Results, dl);
17527   }
17528   case COMPRESS_TO_MEM: {
17529     SDLoc dl(Op);
17530     SDValue Mask = Op.getOperand(4);
17531     SDValue DataToCompress = Op.getOperand(3);
17532     SDValue Addr = Op.getOperand(2);
17533     SDValue Chain = Op.getOperand(0);
17534
17535     MVT VT = DataToCompress.getSimpleValueType();
17536     if (isAllOnesConstant(Mask)) // return just a store
17537       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17538                           MachinePointerInfo(), false, false,
17539                           VT.getScalarSizeInBits()/8);
17540
17541     SDValue Compressed =
17542       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17543                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17544     return DAG.getStore(Chain, dl, Compressed, Addr,
17545                         MachinePointerInfo(), false, false,
17546                         VT.getScalarSizeInBits()/8);
17547   }
17548   case TRUNCATE_TO_MEM_VI8:
17549     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17550   case TRUNCATE_TO_MEM_VI16:
17551     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17552   case TRUNCATE_TO_MEM_VI32:
17553     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17554   case EXPAND_FROM_MEM: {
17555     SDLoc dl(Op);
17556     SDValue Mask = Op.getOperand(4);
17557     SDValue PassThru = Op.getOperand(3);
17558     SDValue Addr = Op.getOperand(2);
17559     SDValue Chain = Op.getOperand(0);
17560     MVT VT = Op.getSimpleValueType();
17561
17562     if (isAllOnesConstant(Mask)) // return just a load
17563       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17564                          false, VT.getScalarSizeInBits()/8);
17565
17566     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17567                                        false, false, false,
17568                                        VT.getScalarSizeInBits()/8);
17569
17570     SDValue Results[] = {
17571       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17572                            Mask, PassThru, Subtarget, DAG), Chain};
17573     return DAG.getMergeValues(Results, dl);
17574   }
17575   }
17576 }
17577
17578 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17579                                            SelectionDAG &DAG) const {
17580   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17581   MFI->setReturnAddressIsTaken(true);
17582
17583   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17584     return SDValue();
17585
17586   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17587   SDLoc dl(Op);
17588   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17589
17590   if (Depth > 0) {
17591     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17592     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17593     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17594     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17595                        DAG.getNode(ISD::ADD, dl, PtrVT,
17596                                    FrameAddr, Offset),
17597                        MachinePointerInfo(), false, false, false, 0);
17598   }
17599
17600   // Just load the return address.
17601   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17602   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17603                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17604 }
17605
17606 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17607   MachineFunction &MF = DAG.getMachineFunction();
17608   MachineFrameInfo *MFI = MF.getFrameInfo();
17609   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17610   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17611   EVT VT = Op.getValueType();
17612
17613   MFI->setFrameAddressIsTaken(true);
17614
17615   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17616     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17617     // is not possible to crawl up the stack without looking at the unwind codes
17618     // simultaneously.
17619     int FrameAddrIndex = FuncInfo->getFAIndex();
17620     if (!FrameAddrIndex) {
17621       // Set up a frame object for the return address.
17622       unsigned SlotSize = RegInfo->getSlotSize();
17623       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17624           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17625       FuncInfo->setFAIndex(FrameAddrIndex);
17626     }
17627     return DAG.getFrameIndex(FrameAddrIndex, VT);
17628   }
17629
17630   unsigned FrameReg =
17631       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17632   SDLoc dl(Op);  // FIXME probably not meaningful
17633   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17634   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17635           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17636          "Invalid Frame Register!");
17637   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17638   while (Depth--)
17639     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17640                             MachinePointerInfo(),
17641                             false, false, false, 0);
17642   return FrameAddr;
17643 }
17644
17645 // FIXME? Maybe this could be a TableGen attribute on some registers and
17646 // this table could be generated automatically from RegInfo.
17647 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17648                                               SelectionDAG &DAG) const {
17649   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17650   const MachineFunction &MF = DAG.getMachineFunction();
17651
17652   unsigned Reg = StringSwitch<unsigned>(RegName)
17653                        .Case("esp", X86::ESP)
17654                        .Case("rsp", X86::RSP)
17655                        .Case("ebp", X86::EBP)
17656                        .Case("rbp", X86::RBP)
17657                        .Default(0);
17658
17659   if (Reg == X86::EBP || Reg == X86::RBP) {
17660     if (!TFI.hasFP(MF))
17661       report_fatal_error("register " + StringRef(RegName) +
17662                          " is allocatable: function has no frame pointer");
17663 #ifndef NDEBUG
17664     else {
17665       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17666       unsigned FrameReg =
17667           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17668       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17669              "Invalid Frame Register!");
17670     }
17671 #endif
17672   }
17673
17674   if (Reg)
17675     return Reg;
17676
17677   report_fatal_error("Invalid register name global variable");
17678 }
17679
17680 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17681                                                      SelectionDAG &DAG) const {
17682   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17683   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17684 }
17685
17686 unsigned X86TargetLowering::getExceptionPointerRegister(
17687     const Constant *PersonalityFn) const {
17688   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17689     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17690
17691   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17692 }
17693
17694 unsigned X86TargetLowering::getExceptionSelectorRegister(
17695     const Constant *PersonalityFn) const {
17696   // Funclet personalities don't use selectors (the runtime does the selection).
17697   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17698   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17699 }
17700
17701 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17702   SDValue Chain     = Op.getOperand(0);
17703   SDValue Offset    = Op.getOperand(1);
17704   SDValue Handler   = Op.getOperand(2);
17705   SDLoc dl      (Op);
17706
17707   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17708   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17709   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17710   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17711           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17712          "Invalid Frame Register!");
17713   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17714   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17715
17716   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17717                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17718                                                        dl));
17719   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17720   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17721                        false, false, 0);
17722   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17723
17724   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17725                      DAG.getRegister(StoreAddrReg, PtrVT));
17726 }
17727
17728 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17729                                                SelectionDAG &DAG) const {
17730   SDLoc DL(Op);
17731   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17732                      DAG.getVTList(MVT::i32, MVT::Other),
17733                      Op.getOperand(0), Op.getOperand(1));
17734 }
17735
17736 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17737                                                 SelectionDAG &DAG) const {
17738   SDLoc DL(Op);
17739   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17740                      Op.getOperand(0), Op.getOperand(1));
17741 }
17742
17743 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17744   return Op.getOperand(0);
17745 }
17746
17747 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17748                                                 SelectionDAG &DAG) const {
17749   SDValue Root = Op.getOperand(0);
17750   SDValue Trmp = Op.getOperand(1); // trampoline
17751   SDValue FPtr = Op.getOperand(2); // nested function
17752   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17753   SDLoc dl (Op);
17754
17755   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17756   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17757
17758   if (Subtarget->is64Bit()) {
17759     SDValue OutChains[6];
17760
17761     // Large code-model.
17762     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17763     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17764
17765     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17766     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17767
17768     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17769
17770     // Load the pointer to the nested function into R11.
17771     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17772     SDValue Addr = Trmp;
17773     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17774                                 Addr, MachinePointerInfo(TrmpAddr),
17775                                 false, false, 0);
17776
17777     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17778                        DAG.getConstant(2, dl, MVT::i64));
17779     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17780                                 MachinePointerInfo(TrmpAddr, 2),
17781                                 false, false, 2);
17782
17783     // Load the 'nest' parameter value into R10.
17784     // R10 is specified in X86CallingConv.td
17785     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17786     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17787                        DAG.getConstant(10, dl, MVT::i64));
17788     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17789                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17790                                 false, false, 0);
17791
17792     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17793                        DAG.getConstant(12, dl, MVT::i64));
17794     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17795                                 MachinePointerInfo(TrmpAddr, 12),
17796                                 false, false, 2);
17797
17798     // Jump to the nested function.
17799     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17800     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17801                        DAG.getConstant(20, dl, MVT::i64));
17802     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17803                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17804                                 false, false, 0);
17805
17806     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17807     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17808                        DAG.getConstant(22, dl, MVT::i64));
17809     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17810                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17811                                 false, false, 0);
17812
17813     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17814   } else {
17815     const Function *Func =
17816       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17817     CallingConv::ID CC = Func->getCallingConv();
17818     unsigned NestReg;
17819
17820     switch (CC) {
17821     default:
17822       llvm_unreachable("Unsupported calling convention");
17823     case CallingConv::C:
17824     case CallingConv::X86_StdCall: {
17825       // Pass 'nest' parameter in ECX.
17826       // Must be kept in sync with X86CallingConv.td
17827       NestReg = X86::ECX;
17828
17829       // Check that ECX wasn't needed by an 'inreg' parameter.
17830       FunctionType *FTy = Func->getFunctionType();
17831       const AttributeSet &Attrs = Func->getAttributes();
17832
17833       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17834         unsigned InRegCount = 0;
17835         unsigned Idx = 1;
17836
17837         for (FunctionType::param_iterator I = FTy->param_begin(),
17838              E = FTy->param_end(); I != E; ++I, ++Idx)
17839           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17840             auto &DL = DAG.getDataLayout();
17841             // FIXME: should only count parameters that are lowered to integers.
17842             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17843           }
17844
17845         if (InRegCount > 2) {
17846           report_fatal_error("Nest register in use - reduce number of inreg"
17847                              " parameters!");
17848         }
17849       }
17850       break;
17851     }
17852     case CallingConv::X86_FastCall:
17853     case CallingConv::X86_ThisCall:
17854     case CallingConv::Fast:
17855       // Pass 'nest' parameter in EAX.
17856       // Must be kept in sync with X86CallingConv.td
17857       NestReg = X86::EAX;
17858       break;
17859     }
17860
17861     SDValue OutChains[4];
17862     SDValue Addr, Disp;
17863
17864     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17865                        DAG.getConstant(10, dl, MVT::i32));
17866     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17867
17868     // This is storing the opcode for MOV32ri.
17869     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17870     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17871     OutChains[0] = DAG.getStore(Root, dl,
17872                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17873                                 Trmp, MachinePointerInfo(TrmpAddr),
17874                                 false, false, 0);
17875
17876     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17877                        DAG.getConstant(1, dl, MVT::i32));
17878     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17879                                 MachinePointerInfo(TrmpAddr, 1),
17880                                 false, false, 1);
17881
17882     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17883     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17884                        DAG.getConstant(5, dl, MVT::i32));
17885     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17886                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17887                                 false, false, 1);
17888
17889     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17890                        DAG.getConstant(6, dl, MVT::i32));
17891     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17892                                 MachinePointerInfo(TrmpAddr, 6),
17893                                 false, false, 1);
17894
17895     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17896   }
17897 }
17898
17899 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17900                                             SelectionDAG &DAG) const {
17901   /*
17902    The rounding mode is in bits 11:10 of FPSR, and has the following
17903    settings:
17904      00 Round to nearest
17905      01 Round to -inf
17906      10 Round to +inf
17907      11 Round to 0
17908
17909   FLT_ROUNDS, on the other hand, expects the following:
17910     -1 Undefined
17911      0 Round to 0
17912      1 Round to nearest
17913      2 Round to +inf
17914      3 Round to -inf
17915
17916   To perform the conversion, we do:
17917     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17918   */
17919
17920   MachineFunction &MF = DAG.getMachineFunction();
17921   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17922   unsigned StackAlignment = TFI.getStackAlignment();
17923   MVT VT = Op.getSimpleValueType();
17924   SDLoc DL(Op);
17925
17926   // Save FP Control Word to stack slot
17927   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17928   SDValue StackSlot =
17929       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17930
17931   MachineMemOperand *MMO =
17932       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17933                               MachineMemOperand::MOStore, 2, 2);
17934
17935   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17936   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17937                                           DAG.getVTList(MVT::Other),
17938                                           Ops, MVT::i16, MMO);
17939
17940   // Load FP Control Word from stack slot
17941   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17942                             MachinePointerInfo(), false, false, false, 0);
17943
17944   // Transform as necessary
17945   SDValue CWD1 =
17946     DAG.getNode(ISD::SRL, DL, MVT::i16,
17947                 DAG.getNode(ISD::AND, DL, MVT::i16,
17948                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17949                 DAG.getConstant(11, DL, MVT::i8));
17950   SDValue CWD2 =
17951     DAG.getNode(ISD::SRL, DL, MVT::i16,
17952                 DAG.getNode(ISD::AND, DL, MVT::i16,
17953                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17954                 DAG.getConstant(9, DL, MVT::i8));
17955
17956   SDValue RetVal =
17957     DAG.getNode(ISD::AND, DL, MVT::i16,
17958                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17959                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17960                             DAG.getConstant(1, DL, MVT::i16)),
17961                 DAG.getConstant(3, DL, MVT::i16));
17962
17963   return DAG.getNode((VT.getSizeInBits() < 16 ?
17964                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17965 }
17966
17967 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17968 //
17969 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17970 //    to 512-bit vector.
17971 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17972 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17973 //    split the vector, perform operation on it's Lo a Hi part and
17974 //    concatenate the results.
17975 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17976   SDLoc dl(Op);
17977   MVT VT = Op.getSimpleValueType();
17978   MVT EltVT = VT.getVectorElementType();
17979   unsigned NumElems = VT.getVectorNumElements();
17980
17981   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17982     // Extend to 512 bit vector.
17983     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17984               "Unsupported value type for operation");
17985
17986     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17987     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17988                                  DAG.getUNDEF(NewVT),
17989                                  Op.getOperand(0),
17990                                  DAG.getIntPtrConstant(0, dl));
17991     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17992
17993     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17994                        DAG.getIntPtrConstant(0, dl));
17995   }
17996
17997   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17998           "Unsupported element type");
17999
18000   if (16 < NumElems) {
18001     // Split vector, it's Lo and Hi parts will be handled in next iteration.
18002     SDValue Lo, Hi;
18003     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
18004     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
18005
18006     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
18007     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
18008
18009     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
18010   }
18011
18012   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
18013
18014   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
18015           "Unsupported value type for operation");
18016
18017   // Use native supported vector instruction vplzcntd.
18018   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
18019   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
18020   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
18021   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
18022
18023   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
18024 }
18025
18026 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
18027                          SelectionDAG &DAG) {
18028   MVT VT = Op.getSimpleValueType();
18029   MVT OpVT = VT;
18030   unsigned NumBits = VT.getSizeInBits();
18031   SDLoc dl(Op);
18032
18033   if (VT.isVector() && Subtarget->hasAVX512())
18034     return LowerVectorCTLZ_AVX512(Op, DAG);
18035
18036   Op = Op.getOperand(0);
18037   if (VT == MVT::i8) {
18038     // Zero extend to i32 since there is not an i8 bsr.
18039     OpVT = MVT::i32;
18040     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18041   }
18042
18043   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18044   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18045   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18046
18047   // If src is zero (i.e. bsr sets ZF), returns NumBits.
18048   SDValue Ops[] = {
18049     Op,
18050     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18051     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18052     Op.getValue(1)
18053   };
18054   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18055
18056   // Finally xor with NumBits-1.
18057   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18058                    DAG.getConstant(NumBits - 1, dl, OpVT));
18059
18060   if (VT == MVT::i8)
18061     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18062   return Op;
18063 }
18064
18065 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18066                                     SelectionDAG &DAG) {
18067   MVT VT = Op.getSimpleValueType();
18068   EVT OpVT = VT;
18069   unsigned NumBits = VT.getSizeInBits();
18070   SDLoc dl(Op);
18071
18072   Op = Op.getOperand(0);
18073   if (VT == MVT::i8) {
18074     // Zero extend to i32 since there is not an i8 bsr.
18075     OpVT = MVT::i32;
18076     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18077   }
18078
18079   // Issue a bsr (scan bits in reverse).
18080   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18081   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18082
18083   // And xor with NumBits-1.
18084   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18085                    DAG.getConstant(NumBits - 1, dl, OpVT));
18086
18087   if (VT == MVT::i8)
18088     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18089   return Op;
18090 }
18091
18092 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18093   MVT VT = Op.getSimpleValueType();
18094   unsigned NumBits = VT.getScalarSizeInBits();
18095   SDLoc dl(Op);
18096
18097   if (VT.isVector()) {
18098     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18099
18100     SDValue N0 = Op.getOperand(0);
18101     SDValue Zero = DAG.getConstant(0, dl, VT);
18102
18103     // lsb(x) = (x & -x)
18104     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18105                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18106
18107     // cttz_undef(x) = (width - 1) - ctlz(lsb)
18108     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18109         TLI.isOperationLegal(ISD::CTLZ, VT)) {
18110       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18111       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18112                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18113     }
18114
18115     // cttz(x) = ctpop(lsb - 1)
18116     SDValue One = DAG.getConstant(1, dl, VT);
18117     return DAG.getNode(ISD::CTPOP, dl, VT,
18118                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18119   }
18120
18121   assert(Op.getOpcode() == ISD::CTTZ &&
18122          "Only scalar CTTZ requires custom lowering");
18123
18124   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18125   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18126   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18127
18128   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18129   SDValue Ops[] = {
18130     Op,
18131     DAG.getConstant(NumBits, dl, VT),
18132     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18133     Op.getValue(1)
18134   };
18135   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18136 }
18137
18138 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18139 // ones, and then concatenate the result back.
18140 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18141   MVT VT = Op.getSimpleValueType();
18142
18143   assert(VT.is256BitVector() && VT.isInteger() &&
18144          "Unsupported value type for operation");
18145
18146   unsigned NumElems = VT.getVectorNumElements();
18147   SDLoc dl(Op);
18148
18149   // Extract the LHS vectors
18150   SDValue LHS = Op.getOperand(0);
18151   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18152   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18153
18154   // Extract the RHS vectors
18155   SDValue RHS = Op.getOperand(1);
18156   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18157   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18158
18159   MVT EltVT = VT.getVectorElementType();
18160   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18161
18162   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18163                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18164                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18165 }
18166
18167 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18168   if (Op.getValueType() == MVT::i1)
18169     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18170                        Op.getOperand(0), Op.getOperand(1));
18171   assert(Op.getSimpleValueType().is256BitVector() &&
18172          Op.getSimpleValueType().isInteger() &&
18173          "Only handle AVX 256-bit vector integer operation");
18174   return Lower256IntArith(Op, DAG);
18175 }
18176
18177 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18178   if (Op.getValueType() == MVT::i1)
18179     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18180                        Op.getOperand(0), Op.getOperand(1));
18181   assert(Op.getSimpleValueType().is256BitVector() &&
18182          Op.getSimpleValueType().isInteger() &&
18183          "Only handle AVX 256-bit vector integer operation");
18184   return Lower256IntArith(Op, DAG);
18185 }
18186
18187 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18188   assert(Op.getSimpleValueType().is256BitVector() &&
18189          Op.getSimpleValueType().isInteger() &&
18190          "Only handle AVX 256-bit vector integer operation");
18191   return Lower256IntArith(Op, DAG);
18192 }
18193
18194 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18195                         SelectionDAG &DAG) {
18196   SDLoc dl(Op);
18197   MVT VT = Op.getSimpleValueType();
18198
18199   if (VT == MVT::i1)
18200     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18201
18202   // Decompose 256-bit ops into smaller 128-bit ops.
18203   if (VT.is256BitVector() && !Subtarget->hasInt256())
18204     return Lower256IntArith(Op, DAG);
18205
18206   SDValue A = Op.getOperand(0);
18207   SDValue B = Op.getOperand(1);
18208
18209   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18210   // pairs, multiply and truncate.
18211   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18212     if (Subtarget->hasInt256()) {
18213       if (VT == MVT::v32i8) {
18214         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18215         SDValue Lo = DAG.getIntPtrConstant(0, dl);
18216         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18217         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18218         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18219         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18220         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18221         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18222                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18223                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18224       }
18225
18226       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18227       return DAG.getNode(
18228           ISD::TRUNCATE, dl, VT,
18229           DAG.getNode(ISD::MUL, dl, ExVT,
18230                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18231                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18232     }
18233
18234     assert(VT == MVT::v16i8 &&
18235            "Pre-AVX2 support only supports v16i8 multiplication");
18236     MVT ExVT = MVT::v8i16;
18237
18238     // Extract the lo parts and sign extend to i16
18239     SDValue ALo, BLo;
18240     if (Subtarget->hasSSE41()) {
18241       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18242       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18243     } else {
18244       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18245                               -1, 4, -1, 5, -1, 6, -1, 7};
18246       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18247       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18248       ALo = DAG.getBitcast(ExVT, ALo);
18249       BLo = DAG.getBitcast(ExVT, BLo);
18250       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18251       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18252     }
18253
18254     // Extract the hi parts and sign extend to i16
18255     SDValue AHi, BHi;
18256     if (Subtarget->hasSSE41()) {
18257       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
18258                               -1, -1, -1, -1, -1, -1, -1, -1};
18259       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18260       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18261       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18262       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18263     } else {
18264       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
18265                               -1, 12, -1, 13, -1, 14, -1, 15};
18266       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18267       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18268       AHi = DAG.getBitcast(ExVT, AHi);
18269       BHi = DAG.getBitcast(ExVT, BHi);
18270       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18271       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18272     }
18273
18274     // Multiply, mask the lower 8bits of the lo/hi results and pack
18275     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18276     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18277     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18278     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18279     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18280   }
18281
18282   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18283   if (VT == MVT::v4i32) {
18284     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18285            "Should not custom lower when pmuldq is available!");
18286
18287     // Extract the odd parts.
18288     static const int UnpackMask[] = { 1, -1, 3, -1 };
18289     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18290     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18291
18292     // Multiply the even parts.
18293     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18294     // Now multiply odd parts.
18295     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18296
18297     Evens = DAG.getBitcast(VT, Evens);
18298     Odds = DAG.getBitcast(VT, Odds);
18299
18300     // Merge the two vectors back together with a shuffle. This expands into 2
18301     // shuffles.
18302     static const int ShufMask[] = { 0, 4, 2, 6 };
18303     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18304   }
18305
18306   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18307          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18308
18309   //  Ahi = psrlqi(a, 32);
18310   //  Bhi = psrlqi(b, 32);
18311   //
18312   //  AloBlo = pmuludq(a, b);
18313   //  AloBhi = pmuludq(a, Bhi);
18314   //  AhiBlo = pmuludq(Ahi, b);
18315
18316   //  AloBhi = psllqi(AloBhi, 32);
18317   //  AhiBlo = psllqi(AhiBlo, 32);
18318   //  return AloBlo + AloBhi + AhiBlo;
18319
18320   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18321   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18322
18323   SDValue AhiBlo = Ahi;
18324   SDValue AloBhi = Bhi;
18325   // Bit cast to 32-bit vectors for MULUDQ
18326   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18327                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18328   A = DAG.getBitcast(MulVT, A);
18329   B = DAG.getBitcast(MulVT, B);
18330   Ahi = DAG.getBitcast(MulVT, Ahi);
18331   Bhi = DAG.getBitcast(MulVT, Bhi);
18332
18333   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18334   // After shifting right const values the result may be all-zero.
18335   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18336     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18337     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18338   }
18339   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18340     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18341     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18342   }
18343
18344   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18345   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18346 }
18347
18348 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18349   assert(Subtarget->isTargetWin64() && "Unexpected target");
18350   EVT VT = Op.getValueType();
18351   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18352          "Unexpected return type for lowering");
18353
18354   RTLIB::Libcall LC;
18355   bool isSigned;
18356   switch (Op->getOpcode()) {
18357   default: llvm_unreachable("Unexpected request for libcall!");
18358   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18359   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18360   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18361   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18362   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18363   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18364   }
18365
18366   SDLoc dl(Op);
18367   SDValue InChain = DAG.getEntryNode();
18368
18369   TargetLowering::ArgListTy Args;
18370   TargetLowering::ArgListEntry Entry;
18371   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18372     EVT ArgVT = Op->getOperand(i).getValueType();
18373     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18374            "Unexpected argument type for lowering");
18375     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18376     Entry.Node = StackPtr;
18377     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18378                            false, false, 16);
18379     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18380     Entry.Ty = PointerType::get(ArgTy,0);
18381     Entry.isSExt = false;
18382     Entry.isZExt = false;
18383     Args.push_back(Entry);
18384   }
18385
18386   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18387                                          getPointerTy(DAG.getDataLayout()));
18388
18389   TargetLowering::CallLoweringInfo CLI(DAG);
18390   CLI.setDebugLoc(dl).setChain(InChain)
18391     .setCallee(getLibcallCallingConv(LC),
18392                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18393                Callee, std::move(Args), 0)
18394     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18395
18396   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18397   return DAG.getBitcast(VT, CallInfo.first);
18398 }
18399
18400 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18401                              SelectionDAG &DAG) {
18402   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18403   MVT VT = Op0.getSimpleValueType();
18404   SDLoc dl(Op);
18405
18406   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18407          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18408
18409   // PMULxD operations multiply each even value (starting at 0) of LHS with
18410   // the related value of RHS and produce a widen result.
18411   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18412   // => <2 x i64> <ae|cg>
18413   //
18414   // In other word, to have all the results, we need to perform two PMULxD:
18415   // 1. one with the even values.
18416   // 2. one with the odd values.
18417   // To achieve #2, with need to place the odd values at an even position.
18418   //
18419   // Place the odd value at an even position (basically, shift all values 1
18420   // step to the left):
18421   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18422   // <a|b|c|d> => <b|undef|d|undef>
18423   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18424   // <e|f|g|h> => <f|undef|h|undef>
18425   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18426
18427   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18428   // ints.
18429   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18430   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18431   unsigned Opcode =
18432       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18433   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18434   // => <2 x i64> <ae|cg>
18435   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18436   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18437   // => <2 x i64> <bf|dh>
18438   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18439
18440   // Shuffle it back into the right order.
18441   SDValue Highs, Lows;
18442   if (VT == MVT::v8i32) {
18443     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18444     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18445     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18446     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18447   } else {
18448     const int HighMask[] = {1, 5, 3, 7};
18449     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18450     const int LowMask[] = {0, 4, 2, 6};
18451     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18452   }
18453
18454   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18455   // unsigned multiply.
18456   if (IsSigned && !Subtarget->hasSSE41()) {
18457     SDValue ShAmt = DAG.getConstant(
18458         31, dl,
18459         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18460     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18461                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18462     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18463                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18464
18465     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18466     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18467   }
18468
18469   // The first result of MUL_LOHI is actually the low value, followed by the
18470   // high value.
18471   SDValue Ops[] = {Lows, Highs};
18472   return DAG.getMergeValues(Ops, dl);
18473 }
18474
18475 // Return true if the required (according to Opcode) shift-imm form is natively
18476 // supported by the Subtarget
18477 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18478                                         unsigned Opcode) {
18479   if (VT.getScalarSizeInBits() < 16)
18480     return false;
18481
18482   if (VT.is512BitVector() &&
18483       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18484     return true;
18485
18486   bool LShift = VT.is128BitVector() ||
18487     (VT.is256BitVector() && Subtarget->hasInt256());
18488
18489   bool AShift = LShift && (Subtarget->hasVLX() ||
18490     (VT != MVT::v2i64 && VT != MVT::v4i64));
18491   return (Opcode == ISD::SRA) ? AShift : LShift;
18492 }
18493
18494 // The shift amount is a variable, but it is the same for all vector lanes.
18495 // These instructions are defined together with shift-immediate.
18496 static
18497 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18498                                       unsigned Opcode) {
18499   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18500 }
18501
18502 // Return true if the required (according to Opcode) variable-shift form is
18503 // natively supported by the Subtarget
18504 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18505                                     unsigned Opcode) {
18506
18507   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18508     return false;
18509
18510   // vXi16 supported only on AVX-512, BWI
18511   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18512     return false;
18513
18514   if (VT.is512BitVector() || Subtarget->hasVLX())
18515     return true;
18516
18517   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18518   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18519   return (Opcode == ISD::SRA) ? AShift : LShift;
18520 }
18521
18522 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18523                                          const X86Subtarget *Subtarget) {
18524   MVT VT = Op.getSimpleValueType();
18525   SDLoc dl(Op);
18526   SDValue R = Op.getOperand(0);
18527   SDValue Amt = Op.getOperand(1);
18528
18529   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18530     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18531
18532   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18533     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18534     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18535     SDValue Ex = DAG.getBitcast(ExVT, R);
18536
18537     if (ShiftAmt >= 32) {
18538       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18539       SDValue Upper =
18540           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18541       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18542                                                  ShiftAmt - 32, DAG);
18543       if (VT == MVT::v2i64)
18544         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18545       if (VT == MVT::v4i64)
18546         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18547                                   {9, 1, 11, 3, 13, 5, 15, 7});
18548     } else {
18549       // SRA upper i32, SHL whole i64 and select lower i32.
18550       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18551                                                  ShiftAmt, DAG);
18552       SDValue Lower =
18553           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18554       Lower = DAG.getBitcast(ExVT, Lower);
18555       if (VT == MVT::v2i64)
18556         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18557       if (VT == MVT::v4i64)
18558         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18559                                   {8, 1, 10, 3, 12, 5, 14, 7});
18560     }
18561     return DAG.getBitcast(VT, Ex);
18562   };
18563
18564   // Optimize shl/srl/sra with constant shift amount.
18565   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18566     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18567       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18568
18569       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18570         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18571
18572       // i64 SRA needs to be performed as partial shifts.
18573       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18574           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18575         return ArithmeticShiftRight64(ShiftAmt);
18576
18577       if (VT == MVT::v16i8 ||
18578           (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18579           VT == MVT::v64i8) {
18580         unsigned NumElts = VT.getVectorNumElements();
18581         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18582
18583         // Simple i8 add case
18584         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18585           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18586
18587         // ashr(R, 7)  === cmp_slt(R, 0)
18588         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18589           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18590           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18591         }
18592
18593         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18594         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18595           return SDValue();
18596
18597         if (Op.getOpcode() == ISD::SHL) {
18598           // Make a large shift.
18599           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18600                                                    R, ShiftAmt, DAG);
18601           SHL = DAG.getBitcast(VT, SHL);
18602           // Zero out the rightmost bits.
18603           return DAG.getNode(ISD::AND, dl, VT, SHL,
18604                              DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18605         }
18606         if (Op.getOpcode() == ISD::SRL) {
18607           // Make a large shift.
18608           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18609                                                    R, ShiftAmt, DAG);
18610           SRL = DAG.getBitcast(VT, SRL);
18611           // Zero out the leftmost bits.
18612           return DAG.getNode(ISD::AND, dl, VT, SRL,
18613                              DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18614         }
18615         if (Op.getOpcode() == ISD::SRA) {
18616           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18617           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18618
18619           SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18620           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18621           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18622           return Res;
18623         }
18624         llvm_unreachable("Unknown shift opcode.");
18625       }
18626     }
18627   }
18628
18629   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18630   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18631       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18632
18633     // Peek through any splat that was introduced for i64 shift vectorization.
18634     int SplatIndex = -1;
18635     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18636       if (SVN->isSplat()) {
18637         SplatIndex = SVN->getSplatIndex();
18638         Amt = Amt.getOperand(0);
18639         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18640                "Splat shuffle referencing second operand");
18641       }
18642
18643     if (Amt.getOpcode() != ISD::BITCAST ||
18644         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18645       return SDValue();
18646
18647     Amt = Amt.getOperand(0);
18648     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18649                      VT.getVectorNumElements();
18650     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18651     uint64_t ShiftAmt = 0;
18652     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18653     for (unsigned i = 0; i != Ratio; ++i) {
18654       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18655       if (!C)
18656         return SDValue();
18657       // 6 == Log2(64)
18658       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18659     }
18660
18661     // Check remaining shift amounts (if not a splat).
18662     if (SplatIndex < 0) {
18663       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18664         uint64_t ShAmt = 0;
18665         for (unsigned j = 0; j != Ratio; ++j) {
18666           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18667           if (!C)
18668             return SDValue();
18669           // 6 == Log2(64)
18670           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18671         }
18672         if (ShAmt != ShiftAmt)
18673           return SDValue();
18674       }
18675     }
18676
18677     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18678       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18679
18680     if (Op.getOpcode() == ISD::SRA)
18681       return ArithmeticShiftRight64(ShiftAmt);
18682   }
18683
18684   return SDValue();
18685 }
18686
18687 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18688                                         const X86Subtarget* Subtarget) {
18689   MVT VT = Op.getSimpleValueType();
18690   SDLoc dl(Op);
18691   SDValue R = Op.getOperand(0);
18692   SDValue Amt = Op.getOperand(1);
18693
18694   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18695     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18696
18697   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18698     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18699
18700   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18701     SDValue BaseShAmt;
18702     MVT EltVT = VT.getVectorElementType();
18703
18704     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18705       // Check if this build_vector node is doing a splat.
18706       // If so, then set BaseShAmt equal to the splat value.
18707       BaseShAmt = BV->getSplatValue();
18708       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18709         BaseShAmt = SDValue();
18710     } else {
18711       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18712         Amt = Amt.getOperand(0);
18713
18714       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18715       if (SVN && SVN->isSplat()) {
18716         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18717         SDValue InVec = Amt.getOperand(0);
18718         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18719           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18720                  "Unexpected shuffle index found!");
18721           BaseShAmt = InVec.getOperand(SplatIdx);
18722         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18723            if (ConstantSDNode *C =
18724                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18725              if (C->getZExtValue() == SplatIdx)
18726                BaseShAmt = InVec.getOperand(1);
18727            }
18728         }
18729
18730         if (!BaseShAmt)
18731           // Avoid introducing an extract element from a shuffle.
18732           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18733                                   DAG.getIntPtrConstant(SplatIdx, dl));
18734       }
18735     }
18736
18737     if (BaseShAmt.getNode()) {
18738       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18739       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18740         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18741       else if (EltVT.bitsLT(MVT::i32))
18742         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18743
18744       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18745     }
18746   }
18747
18748   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18749   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18750       Amt.getOpcode() == ISD::BITCAST &&
18751       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18752     Amt = Amt.getOperand(0);
18753     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18754                      VT.getVectorNumElements();
18755     std::vector<SDValue> Vals(Ratio);
18756     for (unsigned i = 0; i != Ratio; ++i)
18757       Vals[i] = Amt.getOperand(i);
18758     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18759       for (unsigned j = 0; j != Ratio; ++j)
18760         if (Vals[j] != Amt.getOperand(i + j))
18761           return SDValue();
18762     }
18763
18764     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18765       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18766   }
18767   return SDValue();
18768 }
18769
18770 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18771                           SelectionDAG &DAG) {
18772   MVT VT = Op.getSimpleValueType();
18773   SDLoc dl(Op);
18774   SDValue R = Op.getOperand(0);
18775   SDValue Amt = Op.getOperand(1);
18776
18777   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18778   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18779
18780   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18781     return V;
18782
18783   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18784     return V;
18785
18786   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18787     return Op;
18788
18789   // XOP has 128-bit variable logical/arithmetic shifts.
18790   // +ve/-ve Amt = shift left/right.
18791   if (Subtarget->hasXOP() &&
18792       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18793        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18794     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18795       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18796       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18797     }
18798     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18799       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18800     if (Op.getOpcode() == ISD::SRA)
18801       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18802   }
18803
18804   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18805   // shifts per-lane and then shuffle the partial results back together.
18806   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18807     // Splat the shift amounts so the scalar shifts above will catch it.
18808     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18809     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18810     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18811     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18812     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18813   }
18814
18815   // i64 vector arithmetic shift can be emulated with the transform:
18816   // M = lshr(SIGN_BIT, Amt)
18817   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18818   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18819       Op.getOpcode() == ISD::SRA) {
18820     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18821     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18822     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18823     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18824     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18825     return R;
18826   }
18827
18828   // If possible, lower this packed shift into a vector multiply instead of
18829   // expanding it into a sequence of scalar shifts.
18830   // Do this only if the vector shift count is a constant build_vector.
18831   if (Op.getOpcode() == ISD::SHL &&
18832       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18833        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18834       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18835     SmallVector<SDValue, 8> Elts;
18836     MVT SVT = VT.getVectorElementType();
18837     unsigned SVTBits = SVT.getSizeInBits();
18838     APInt One(SVTBits, 1);
18839     unsigned NumElems = VT.getVectorNumElements();
18840
18841     for (unsigned i=0; i !=NumElems; ++i) {
18842       SDValue Op = Amt->getOperand(i);
18843       if (Op->getOpcode() == ISD::UNDEF) {
18844         Elts.push_back(Op);
18845         continue;
18846       }
18847
18848       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18849       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18850       uint64_t ShAmt = C.getZExtValue();
18851       if (ShAmt >= SVTBits) {
18852         Elts.push_back(DAG.getUNDEF(SVT));
18853         continue;
18854       }
18855       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18856     }
18857     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18858     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18859   }
18860
18861   // Lower SHL with variable shift amount.
18862   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18863     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18864
18865     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18866                      DAG.getConstant(0x3f800000U, dl, VT));
18867     Op = DAG.getBitcast(MVT::v4f32, Op);
18868     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18869     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18870   }
18871
18872   // If possible, lower this shift as a sequence of two shifts by
18873   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18874   // Example:
18875   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18876   //
18877   // Could be rewritten as:
18878   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18879   //
18880   // The advantage is that the two shifts from the example would be
18881   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18882   // the vector shift into four scalar shifts plus four pairs of vector
18883   // insert/extract.
18884   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18885       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18886     unsigned TargetOpcode = X86ISD::MOVSS;
18887     bool CanBeSimplified;
18888     // The splat value for the first packed shift (the 'X' from the example).
18889     SDValue Amt1 = Amt->getOperand(0);
18890     // The splat value for the second packed shift (the 'Y' from the example).
18891     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18892                                         Amt->getOperand(2);
18893
18894     // See if it is possible to replace this node with a sequence of
18895     // two shifts followed by a MOVSS/MOVSD
18896     if (VT == MVT::v4i32) {
18897       // Check if it is legal to use a MOVSS.
18898       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18899                         Amt2 == Amt->getOperand(3);
18900       if (!CanBeSimplified) {
18901         // Otherwise, check if we can still simplify this node using a MOVSD.
18902         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18903                           Amt->getOperand(2) == Amt->getOperand(3);
18904         TargetOpcode = X86ISD::MOVSD;
18905         Amt2 = Amt->getOperand(2);
18906       }
18907     } else {
18908       // Do similar checks for the case where the machine value type
18909       // is MVT::v8i16.
18910       CanBeSimplified = Amt1 == Amt->getOperand(1);
18911       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18912         CanBeSimplified = Amt2 == Amt->getOperand(i);
18913
18914       if (!CanBeSimplified) {
18915         TargetOpcode = X86ISD::MOVSD;
18916         CanBeSimplified = true;
18917         Amt2 = Amt->getOperand(4);
18918         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18919           CanBeSimplified = Amt1 == Amt->getOperand(i);
18920         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18921           CanBeSimplified = Amt2 == Amt->getOperand(j);
18922       }
18923     }
18924
18925     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18926         isa<ConstantSDNode>(Amt2)) {
18927       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18928       MVT CastVT = MVT::v4i32;
18929       SDValue Splat1 =
18930         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18931       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18932       SDValue Splat2 =
18933         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18934       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18935       if (TargetOpcode == X86ISD::MOVSD)
18936         CastVT = MVT::v2i64;
18937       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18938       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18939       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18940                                             BitCast1, DAG);
18941       return DAG.getBitcast(VT, Result);
18942     }
18943   }
18944
18945   // v4i32 Non Uniform Shifts.
18946   // If the shift amount is constant we can shift each lane using the SSE2
18947   // immediate shifts, else we need to zero-extend each lane to the lower i64
18948   // and shift using the SSE2 variable shifts.
18949   // The separate results can then be blended together.
18950   if (VT == MVT::v4i32) {
18951     unsigned Opc = Op.getOpcode();
18952     SDValue Amt0, Amt1, Amt2, Amt3;
18953     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18954       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18955       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18956       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18957       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18958     } else {
18959       // ISD::SHL is handled above but we include it here for completeness.
18960       switch (Opc) {
18961       default:
18962         llvm_unreachable("Unknown target vector shift node");
18963       case ISD::SHL:
18964         Opc = X86ISD::VSHL;
18965         break;
18966       case ISD::SRL:
18967         Opc = X86ISD::VSRL;
18968         break;
18969       case ISD::SRA:
18970         Opc = X86ISD::VSRA;
18971         break;
18972       }
18973       // The SSE2 shifts use the lower i64 as the same shift amount for
18974       // all lanes and the upper i64 is ignored. These shuffle masks
18975       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18976       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18977       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18978       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18979       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18980       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18981     }
18982
18983     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18984     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18985     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18986     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18987     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18988     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18989     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18990   }
18991
18992   if (VT == MVT::v16i8 ||
18993       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18994     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18995     unsigned ShiftOpcode = Op->getOpcode();
18996
18997     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18998       // On SSE41 targets we make use of the fact that VSELECT lowers
18999       // to PBLENDVB which selects bytes based just on the sign bit.
19000       if (Subtarget->hasSSE41()) {
19001         V0 = DAG.getBitcast(VT, V0);
19002         V1 = DAG.getBitcast(VT, V1);
19003         Sel = DAG.getBitcast(VT, Sel);
19004         return DAG.getBitcast(SelVT,
19005                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
19006       }
19007       // On pre-SSE41 targets we test for the sign bit by comparing to
19008       // zero - a negative value will set all bits of the lanes to true
19009       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
19010       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
19011       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
19012       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
19013     };
19014
19015     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
19016     // We can safely do this using i16 shifts as we're only interested in
19017     // the 3 lower bits of each byte.
19018     Amt = DAG.getBitcast(ExtVT, Amt);
19019     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
19020     Amt = DAG.getBitcast(VT, Amt);
19021
19022     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
19023       // r = VSELECT(r, shift(r, 4), a);
19024       SDValue M =
19025           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19026       R = SignBitSelect(VT, Amt, M, R);
19027
19028       // a += a
19029       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19030
19031       // r = VSELECT(r, shift(r, 2), a);
19032       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19033       R = SignBitSelect(VT, Amt, M, R);
19034
19035       // a += a
19036       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19037
19038       // return VSELECT(r, shift(r, 1), a);
19039       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19040       R = SignBitSelect(VT, Amt, M, R);
19041       return R;
19042     }
19043
19044     if (Op->getOpcode() == ISD::SRA) {
19045       // For SRA we need to unpack each byte to the higher byte of a i16 vector
19046       // so we can correctly sign extend. We don't care what happens to the
19047       // lower byte.
19048       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19049       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19050       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19051       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19052       ALo = DAG.getBitcast(ExtVT, ALo);
19053       AHi = DAG.getBitcast(ExtVT, AHi);
19054       RLo = DAG.getBitcast(ExtVT, RLo);
19055       RHi = DAG.getBitcast(ExtVT, RHi);
19056
19057       // r = VSELECT(r, shift(r, 4), a);
19058       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19059                                 DAG.getConstant(4, dl, ExtVT));
19060       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19061                                 DAG.getConstant(4, dl, ExtVT));
19062       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19063       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19064
19065       // a += a
19066       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19067       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19068
19069       // r = VSELECT(r, shift(r, 2), a);
19070       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19071                         DAG.getConstant(2, dl, ExtVT));
19072       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19073                         DAG.getConstant(2, 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, 1), a);
19082       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19083                         DAG.getConstant(1, dl, ExtVT));
19084       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19085                         DAG.getConstant(1, dl, ExtVT));
19086       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19087       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19088
19089       // Logical shift the result back to the lower byte, leaving a zero upper
19090       // byte
19091       // meaning that we can safely pack with PACKUSWB.
19092       RLo =
19093           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19094       RHi =
19095           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19096       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19097     }
19098   }
19099
19100   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19101   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19102   // solution better.
19103   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19104     MVT ExtVT = MVT::v8i32;
19105     unsigned ExtOpc =
19106         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19107     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19108     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19109     return DAG.getNode(ISD::TRUNCATE, dl, VT,
19110                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19111   }
19112
19113   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19114     MVT ExtVT = MVT::v8i32;
19115     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19116     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19117     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19118     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19119     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19120     ALo = DAG.getBitcast(ExtVT, ALo);
19121     AHi = DAG.getBitcast(ExtVT, AHi);
19122     RLo = DAG.getBitcast(ExtVT, RLo);
19123     RHi = DAG.getBitcast(ExtVT, RHi);
19124     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19125     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19126     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19127     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19128     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19129   }
19130
19131   if (VT == MVT::v8i16) {
19132     unsigned ShiftOpcode = Op->getOpcode();
19133
19134     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19135       // On SSE41 targets we make use of the fact that VSELECT lowers
19136       // to PBLENDVB which selects bytes based just on the sign bit.
19137       if (Subtarget->hasSSE41()) {
19138         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19139         V0 = DAG.getBitcast(ExtVT, V0);
19140         V1 = DAG.getBitcast(ExtVT, V1);
19141         Sel = DAG.getBitcast(ExtVT, Sel);
19142         return DAG.getBitcast(
19143             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19144       }
19145       // On pre-SSE41 targets we splat the sign bit - a negative value will
19146       // set all bits of the lanes to true and VSELECT uses that in
19147       // its OR(AND(V0,C),AND(V1,~C)) lowering.
19148       SDValue C =
19149           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19150       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19151     };
19152
19153     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19154     if (Subtarget->hasSSE41()) {
19155       // On SSE41 targets we need to replicate the shift mask in both
19156       // bytes for PBLENDVB.
19157       Amt = DAG.getNode(
19158           ISD::OR, dl, VT,
19159           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19160           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19161     } else {
19162       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19163     }
19164
19165     // r = VSELECT(r, shift(r, 8), a);
19166     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19167     R = SignBitSelect(Amt, M, R);
19168
19169     // a += a
19170     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19171
19172     // r = VSELECT(r, shift(r, 4), a);
19173     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19174     R = SignBitSelect(Amt, M, R);
19175
19176     // a += a
19177     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19178
19179     // r = VSELECT(r, shift(r, 2), a);
19180     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19181     R = SignBitSelect(Amt, M, R);
19182
19183     // a += a
19184     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19185
19186     // return VSELECT(r, shift(r, 1), a);
19187     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19188     R = SignBitSelect(Amt, M, R);
19189     return R;
19190   }
19191
19192   // Decompose 256-bit shifts into smaller 128-bit shifts.
19193   if (VT.is256BitVector()) {
19194     unsigned NumElems = VT.getVectorNumElements();
19195     MVT EltVT = VT.getVectorElementType();
19196     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19197
19198     // Extract the two vectors
19199     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19200     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19201
19202     // Recreate the shift amount vectors
19203     SDValue Amt1, Amt2;
19204     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19205       // Constant shift amount
19206       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19207       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19208       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19209
19210       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19211       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19212     } else {
19213       // Variable shift amount
19214       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19215       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19216     }
19217
19218     // Issue new vector shifts for the smaller types
19219     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19220     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19221
19222     // Concatenate the result back
19223     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19224   }
19225
19226   return SDValue();
19227 }
19228
19229 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19230                            SelectionDAG &DAG) {
19231   MVT VT = Op.getSimpleValueType();
19232   SDLoc DL(Op);
19233   SDValue R = Op.getOperand(0);
19234   SDValue Amt = Op.getOperand(1);
19235
19236   assert(VT.isVector() && "Custom lowering only for vector rotates!");
19237   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19238   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19239
19240   // XOP has 128-bit vector variable + immediate rotates.
19241   // +ve/-ve Amt = rotate left/right.
19242
19243   // Split 256-bit integers.
19244   if (VT.is256BitVector())
19245     return Lower256IntArith(Op, DAG);
19246
19247   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19248
19249   // Attempt to rotate by immediate.
19250   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19251     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19252       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19253       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19254       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19255                          DAG.getConstant(RotateAmt, DL, MVT::i8));
19256     }
19257   }
19258
19259   // Use general rotate by variable (per-element).
19260   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19261 }
19262
19263 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19264   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19265   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19266   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19267   // has only one use.
19268   SDNode *N = Op.getNode();
19269   SDValue LHS = N->getOperand(0);
19270   SDValue RHS = N->getOperand(1);
19271   unsigned BaseOp = 0;
19272   unsigned Cond = 0;
19273   SDLoc DL(Op);
19274   switch (Op.getOpcode()) {
19275   default: llvm_unreachable("Unknown ovf instruction!");
19276   case ISD::SADDO:
19277     // A subtract of one will be selected as a INC. Note that INC doesn't
19278     // set CF, so we can't do this for UADDO.
19279     if (isOneConstant(RHS)) {
19280         BaseOp = X86ISD::INC;
19281         Cond = X86::COND_O;
19282         break;
19283       }
19284     BaseOp = X86ISD::ADD;
19285     Cond = X86::COND_O;
19286     break;
19287   case ISD::UADDO:
19288     BaseOp = X86ISD::ADD;
19289     Cond = X86::COND_B;
19290     break;
19291   case ISD::SSUBO:
19292     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19293     // set CF, so we can't do this for USUBO.
19294     if (isOneConstant(RHS)) {
19295         BaseOp = X86ISD::DEC;
19296         Cond = X86::COND_O;
19297         break;
19298       }
19299     BaseOp = X86ISD::SUB;
19300     Cond = X86::COND_O;
19301     break;
19302   case ISD::USUBO:
19303     BaseOp = X86ISD::SUB;
19304     Cond = X86::COND_B;
19305     break;
19306   case ISD::SMULO:
19307     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19308     Cond = X86::COND_O;
19309     break;
19310   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19311     if (N->getValueType(0) == MVT::i8) {
19312       BaseOp = X86ISD::UMUL8;
19313       Cond = X86::COND_O;
19314       break;
19315     }
19316     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19317                                  MVT::i32);
19318     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19319
19320     SDValue SetCC =
19321       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19322                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19323                   SDValue(Sum.getNode(), 2));
19324
19325     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19326   }
19327   }
19328
19329   // Also sets EFLAGS.
19330   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19331   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19332
19333   SDValue SetCC =
19334     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19335                 DAG.getConstant(Cond, DL, MVT::i32),
19336                 SDValue(Sum.getNode(), 1));
19337
19338   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19339 }
19340
19341 /// Returns true if the operand type is exactly twice the native width, and
19342 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19343 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19344 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19345 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19346   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19347
19348   if (OpWidth == 64)
19349     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19350   else if (OpWidth == 128)
19351     return Subtarget->hasCmpxchg16b();
19352   else
19353     return false;
19354 }
19355
19356 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19357   return needsCmpXchgNb(SI->getValueOperand()->getType());
19358 }
19359
19360 // Note: this turns large loads into lock cmpxchg8b/16b.
19361 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19362 TargetLowering::AtomicExpansionKind
19363 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19364   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19365   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19366                                                : AtomicExpansionKind::None;
19367 }
19368
19369 TargetLowering::AtomicExpansionKind
19370 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19371   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19372   Type *MemType = AI->getType();
19373
19374   // If the operand is too big, we must see if cmpxchg8/16b is available
19375   // and default to library calls otherwise.
19376   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19377     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19378                                    : AtomicExpansionKind::None;
19379   }
19380
19381   AtomicRMWInst::BinOp Op = AI->getOperation();
19382   switch (Op) {
19383   default:
19384     llvm_unreachable("Unknown atomic operation");
19385   case AtomicRMWInst::Xchg:
19386   case AtomicRMWInst::Add:
19387   case AtomicRMWInst::Sub:
19388     // It's better to use xadd, xsub or xchg for these in all cases.
19389     return AtomicExpansionKind::None;
19390   case AtomicRMWInst::Or:
19391   case AtomicRMWInst::And:
19392   case AtomicRMWInst::Xor:
19393     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19394     // prefix to a normal instruction for these operations.
19395     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19396                             : AtomicExpansionKind::None;
19397   case AtomicRMWInst::Nand:
19398   case AtomicRMWInst::Max:
19399   case AtomicRMWInst::Min:
19400   case AtomicRMWInst::UMax:
19401   case AtomicRMWInst::UMin:
19402     // These always require a non-trivial set of data operations on x86. We must
19403     // use a cmpxchg loop.
19404     return AtomicExpansionKind::CmpXChg;
19405   }
19406 }
19407
19408 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19409   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19410   // no-sse2). There isn't any reason to disable it if the target processor
19411   // supports it.
19412   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19413 }
19414
19415 LoadInst *
19416 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19417   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19418   Type *MemType = AI->getType();
19419   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19420   // there is no benefit in turning such RMWs into loads, and it is actually
19421   // harmful as it introduces a mfence.
19422   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19423     return nullptr;
19424
19425   auto Builder = IRBuilder<>(AI);
19426   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19427   auto SynchScope = AI->getSynchScope();
19428   // We must restrict the ordering to avoid generating loads with Release or
19429   // ReleaseAcquire orderings.
19430   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19431   auto Ptr = AI->getPointerOperand();
19432
19433   // Before the load we need a fence. Here is an example lifted from
19434   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19435   // is required:
19436   // Thread 0:
19437   //   x.store(1, relaxed);
19438   //   r1 = y.fetch_add(0, release);
19439   // Thread 1:
19440   //   y.fetch_add(42, acquire);
19441   //   r2 = x.load(relaxed);
19442   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19443   // lowered to just a load without a fence. A mfence flushes the store buffer,
19444   // making the optimization clearly correct.
19445   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19446   // otherwise, we might be able to be more aggressive on relaxed idempotent
19447   // rmw. In practice, they do not look useful, so we don't try to be
19448   // especially clever.
19449   if (SynchScope == SingleThread)
19450     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19451     // the IR level, so we must wrap it in an intrinsic.
19452     return nullptr;
19453
19454   if (!hasMFENCE(*Subtarget))
19455     // FIXME: it might make sense to use a locked operation here but on a
19456     // different cache-line to prevent cache-line bouncing. In practice it
19457     // is probably a small win, and x86 processors without mfence are rare
19458     // enough that we do not bother.
19459     return nullptr;
19460
19461   Function *MFence =
19462       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19463   Builder.CreateCall(MFence, {});
19464
19465   // Finally we can emit the atomic load.
19466   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19467           AI->getType()->getPrimitiveSizeInBits());
19468   Loaded->setAtomic(Order, SynchScope);
19469   AI->replaceAllUsesWith(Loaded);
19470   AI->eraseFromParent();
19471   return Loaded;
19472 }
19473
19474 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19475                                  SelectionDAG &DAG) {
19476   SDLoc dl(Op);
19477   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19478     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19479   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19480     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19481
19482   // The only fence that needs an instruction is a sequentially-consistent
19483   // cross-thread fence.
19484   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19485     if (hasMFENCE(*Subtarget))
19486       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19487
19488     SDValue Chain = Op.getOperand(0);
19489     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19490     SDValue Ops[] = {
19491       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19492       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19493       DAG.getRegister(0, MVT::i32),            // Index
19494       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19495       DAG.getRegister(0, MVT::i32),            // Segment.
19496       Zero,
19497       Chain
19498     };
19499     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19500     return SDValue(Res, 0);
19501   }
19502
19503   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19504   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19505 }
19506
19507 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19508                              SelectionDAG &DAG) {
19509   MVT T = Op.getSimpleValueType();
19510   SDLoc DL(Op);
19511   unsigned Reg = 0;
19512   unsigned size = 0;
19513   switch(T.SimpleTy) {
19514   default: llvm_unreachable("Invalid value type!");
19515   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19516   case MVT::i16: Reg = X86::AX;  size = 2; break;
19517   case MVT::i32: Reg = X86::EAX; size = 4; break;
19518   case MVT::i64:
19519     assert(Subtarget->is64Bit() && "Node not type legal!");
19520     Reg = X86::RAX; size = 8;
19521     break;
19522   }
19523   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19524                                   Op.getOperand(2), SDValue());
19525   SDValue Ops[] = { cpIn.getValue(0),
19526                     Op.getOperand(1),
19527                     Op.getOperand(3),
19528                     DAG.getTargetConstant(size, DL, MVT::i8),
19529                     cpIn.getValue(1) };
19530   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19531   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19532   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19533                                            Ops, T, MMO);
19534
19535   SDValue cpOut =
19536     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19537   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19538                                       MVT::i32, cpOut.getValue(2));
19539   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19540                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19541                                 EFLAGS);
19542
19543   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19544   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19545   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19546   return SDValue();
19547 }
19548
19549 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19550                             SelectionDAG &DAG) {
19551   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19552   MVT DstVT = Op.getSimpleValueType();
19553
19554   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
19555       SrcVT == MVT::i64) {
19556     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19557     if (DstVT != MVT::f64)
19558       // This conversion needs to be expanded.
19559       return SDValue();
19560
19561     SDValue Op0 = Op->getOperand(0);
19562     SmallVector<SDValue, 16> Elts;
19563     SDLoc dl(Op);
19564     unsigned NumElts;
19565     MVT SVT;
19566     if (SrcVT.isVector()) {
19567       NumElts = SrcVT.getVectorNumElements();
19568       SVT = SrcVT.getVectorElementType();
19569
19570       // Widen the vector in input in the case of MVT::v2i32.
19571       // Example: from MVT::v2i32 to MVT::v4i32.
19572       for (unsigned i = 0, e = NumElts; i != e; ++i)
19573         Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, Op0,
19574                                    DAG.getIntPtrConstant(i, dl)));
19575     } else {
19576       assert(SrcVT == MVT::i64 && !Subtarget->is64Bit() &&
19577              "Unexpected source type in LowerBITCAST");
19578       Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19579                                  DAG.getIntPtrConstant(0, dl)));
19580       Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19581                                  DAG.getIntPtrConstant(1, dl)));
19582       NumElts = 2;
19583       SVT = MVT::i32;
19584     }
19585     // Explicitly mark the extra elements as Undef.
19586     Elts.append(NumElts, DAG.getUNDEF(SVT));
19587
19588     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19589     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19590     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19591     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19592                        DAG.getIntPtrConstant(0, dl));
19593   }
19594
19595   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19596          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19597   assert((DstVT == MVT::i64 ||
19598           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19599          "Unexpected custom BITCAST");
19600   // i64 <=> MMX conversions are Legal.
19601   if (SrcVT==MVT::i64 && DstVT.isVector())
19602     return Op;
19603   if (DstVT==MVT::i64 && SrcVT.isVector())
19604     return Op;
19605   // MMX <=> MMX conversions are Legal.
19606   if (SrcVT.isVector() && DstVT.isVector())
19607     return Op;
19608   // All other conversions need to be expanded.
19609   return SDValue();
19610 }
19611
19612 /// Compute the horizontal sum of bytes in V for the elements of VT.
19613 ///
19614 /// Requires V to be a byte vector and VT to be an integer vector type with
19615 /// wider elements than V's type. The width of the elements of VT determines
19616 /// how many bytes of V are summed horizontally to produce each element of the
19617 /// result.
19618 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19619                                       const X86Subtarget *Subtarget,
19620                                       SelectionDAG &DAG) {
19621   SDLoc DL(V);
19622   MVT ByteVecVT = V.getSimpleValueType();
19623   MVT EltVT = VT.getVectorElementType();
19624   int NumElts = VT.getVectorNumElements();
19625   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19626          "Expected value to have byte element type.");
19627   assert(EltVT != MVT::i8 &&
19628          "Horizontal byte sum only makes sense for wider elements!");
19629   unsigned VecSize = VT.getSizeInBits();
19630   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19631
19632   // PSADBW instruction horizontally add all bytes and leave the result in i64
19633   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19634   if (EltVT == MVT::i64) {
19635     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19636     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19637     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19638     return DAG.getBitcast(VT, V);
19639   }
19640
19641   if (EltVT == MVT::i32) {
19642     // We unpack the low half and high half into i32s interleaved with zeros so
19643     // that we can use PSADBW to horizontally sum them. The most useful part of
19644     // this is that it lines up the results of two PSADBW instructions to be
19645     // two v2i64 vectors which concatenated are the 4 population counts. We can
19646     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19647     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19648     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19649     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19650
19651     // Do the horizontal sums into two v2i64s.
19652     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19653     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19654     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19655                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19656     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19657                        DAG.getBitcast(ByteVecVT, High), Zeros);
19658
19659     // Merge them together.
19660     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19661     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19662                     DAG.getBitcast(ShortVecVT, Low),
19663                     DAG.getBitcast(ShortVecVT, High));
19664
19665     return DAG.getBitcast(VT, V);
19666   }
19667
19668   // The only element type left is i16.
19669   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19670
19671   // To obtain pop count for each i16 element starting from the pop count for
19672   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19673   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19674   // directly supported.
19675   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19676   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19677   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19678   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19679                   DAG.getBitcast(ByteVecVT, V));
19680   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19681 }
19682
19683 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19684                                         const X86Subtarget *Subtarget,
19685                                         SelectionDAG &DAG) {
19686   MVT VT = Op.getSimpleValueType();
19687   MVT EltVT = VT.getVectorElementType();
19688   unsigned VecSize = VT.getSizeInBits();
19689
19690   // Implement a lookup table in register by using an algorithm based on:
19691   // http://wm.ite.pl/articles/sse-popcount.html
19692   //
19693   // The general idea is that every lower byte nibble in the input vector is an
19694   // index into a in-register pre-computed pop count table. We then split up the
19695   // input vector in two new ones: (1) a vector with only the shifted-right
19696   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19697   // masked out higher ones) for each byte. PSHUB is used separately with both
19698   // to index the in-register table. Next, both are added and the result is a
19699   // i8 vector where each element contains the pop count for input byte.
19700   //
19701   // To obtain the pop count for elements != i8, we follow up with the same
19702   // approach and use additional tricks as described below.
19703   //
19704   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19705                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19706                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19707                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19708
19709   int NumByteElts = VecSize / 8;
19710   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19711   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19712   SmallVector<SDValue, 16> LUTVec;
19713   for (int i = 0; i < NumByteElts; ++i)
19714     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19715   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19716   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19717                                   DAG.getConstant(0x0F, DL, MVT::i8));
19718   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19719
19720   // High nibbles
19721   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19722   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19723   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19724
19725   // Low nibbles
19726   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19727
19728   // The input vector is used as the shuffle mask that index elements into the
19729   // LUT. After counting low and high nibbles, add the vector to obtain the
19730   // final pop count per i8 element.
19731   SDValue HighPopCnt =
19732       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19733   SDValue LowPopCnt =
19734       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19735   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19736
19737   if (EltVT == MVT::i8)
19738     return PopCnt;
19739
19740   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19741 }
19742
19743 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19744                                        const X86Subtarget *Subtarget,
19745                                        SelectionDAG &DAG) {
19746   MVT VT = Op.getSimpleValueType();
19747   assert(VT.is128BitVector() &&
19748          "Only 128-bit vector bitmath lowering supported.");
19749
19750   int VecSize = VT.getSizeInBits();
19751   MVT EltVT = VT.getVectorElementType();
19752   int Len = EltVT.getSizeInBits();
19753
19754   // This is the vectorized version of the "best" algorithm from
19755   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19756   // with a minor tweak to use a series of adds + shifts instead of vector
19757   // multiplications. Implemented for all integer vector types. We only use
19758   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19759   // much faster, even faster than using native popcnt instructions.
19760
19761   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19762     MVT VT = V.getSimpleValueType();
19763     SmallVector<SDValue, 32> Shifters(
19764         VT.getVectorNumElements(),
19765         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19766     return DAG.getNode(OpCode, DL, VT, V,
19767                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19768   };
19769   auto GetMask = [&](SDValue V, APInt Mask) {
19770     MVT VT = V.getSimpleValueType();
19771     SmallVector<SDValue, 32> Masks(
19772         VT.getVectorNumElements(),
19773         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19774     return DAG.getNode(ISD::AND, DL, VT, V,
19775                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19776   };
19777
19778   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19779   // x86, so set the SRL type to have elements at least i16 wide. This is
19780   // correct because all of our SRLs are followed immediately by a mask anyways
19781   // that handles any bits that sneak into the high bits of the byte elements.
19782   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19783
19784   SDValue V = Op;
19785
19786   // v = v - ((v >> 1) & 0x55555555...)
19787   SDValue Srl =
19788       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19789   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19790   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19791
19792   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19793   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19794   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19795   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19796   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19797
19798   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19799   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19800   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19801   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19802
19803   // At this point, V contains the byte-wise population count, and we are
19804   // merely doing a horizontal sum if necessary to get the wider element
19805   // counts.
19806   if (EltVT == MVT::i8)
19807     return V;
19808
19809   return LowerHorizontalByteSum(
19810       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19811       DAG);
19812 }
19813
19814 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19815                                 SelectionDAG &DAG) {
19816   MVT VT = Op.getSimpleValueType();
19817   // FIXME: Need to add AVX-512 support here!
19818   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19819          "Unknown CTPOP type to handle");
19820   SDLoc DL(Op.getNode());
19821   SDValue Op0 = Op.getOperand(0);
19822
19823   if (!Subtarget->hasSSSE3()) {
19824     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19825     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19826     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19827   }
19828
19829   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19830     unsigned NumElems = VT.getVectorNumElements();
19831
19832     // Extract each 128-bit vector, compute pop count and concat the result.
19833     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19834     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19835
19836     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19837                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19838                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19839   }
19840
19841   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19842 }
19843
19844 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19845                           SelectionDAG &DAG) {
19846   assert(Op.getSimpleValueType().isVector() &&
19847          "We only do custom lowering for vector population count.");
19848   return LowerVectorCTPOP(Op, Subtarget, DAG);
19849 }
19850
19851 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19852   SDNode *Node = Op.getNode();
19853   SDLoc dl(Node);
19854   EVT T = Node->getValueType(0);
19855   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19856                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19857   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19858                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19859                        Node->getOperand(0),
19860                        Node->getOperand(1), negOp,
19861                        cast<AtomicSDNode>(Node)->getMemOperand(),
19862                        cast<AtomicSDNode>(Node)->getOrdering(),
19863                        cast<AtomicSDNode>(Node)->getSynchScope());
19864 }
19865
19866 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19867   SDNode *Node = Op.getNode();
19868   SDLoc dl(Node);
19869   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19870
19871   // Convert seq_cst store -> xchg
19872   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19873   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19874   //        (The only way to get a 16-byte store is cmpxchg16b)
19875   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19876   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19877       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19878     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19879                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19880                                  Node->getOperand(0),
19881                                  Node->getOperand(1), Node->getOperand(2),
19882                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19883                                  cast<AtomicSDNode>(Node)->getOrdering(),
19884                                  cast<AtomicSDNode>(Node)->getSynchScope());
19885     return Swap.getValue(1);
19886   }
19887   // Other atomic stores have a simple pattern.
19888   return Op;
19889 }
19890
19891 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19892   MVT VT = Op.getNode()->getSimpleValueType(0);
19893
19894   // Let legalize expand this if it isn't a legal type yet.
19895   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19896     return SDValue();
19897
19898   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19899
19900   unsigned Opc;
19901   bool ExtraOp = false;
19902   switch (Op.getOpcode()) {
19903   default: llvm_unreachable("Invalid code");
19904   case ISD::ADDC: Opc = X86ISD::ADD; break;
19905   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19906   case ISD::SUBC: Opc = X86ISD::SUB; break;
19907   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19908   }
19909
19910   if (!ExtraOp)
19911     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19912                        Op.getOperand(1));
19913   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19914                      Op.getOperand(1), Op.getOperand(2));
19915 }
19916
19917 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19918                             SelectionDAG &DAG) {
19919   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19920
19921   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19922   // which returns the values as { float, float } (in XMM0) or
19923   // { double, double } (which is returned in XMM0, XMM1).
19924   SDLoc dl(Op);
19925   SDValue Arg = Op.getOperand(0);
19926   EVT ArgVT = Arg.getValueType();
19927   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19928
19929   TargetLowering::ArgListTy Args;
19930   TargetLowering::ArgListEntry Entry;
19931
19932   Entry.Node = Arg;
19933   Entry.Ty = ArgTy;
19934   Entry.isSExt = false;
19935   Entry.isZExt = false;
19936   Args.push_back(Entry);
19937
19938   bool isF64 = ArgVT == MVT::f64;
19939   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19940   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19941   // the results are returned via SRet in memory.
19942   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19943   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19944   SDValue Callee =
19945       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19946
19947   Type *RetTy = isF64
19948     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19949     : (Type*)VectorType::get(ArgTy, 4);
19950
19951   TargetLowering::CallLoweringInfo CLI(DAG);
19952   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19953     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19954
19955   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19956
19957   if (isF64)
19958     // Returned in xmm0 and xmm1.
19959     return CallResult.first;
19960
19961   // Returned in bits 0:31 and 32:64 xmm0.
19962   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19963                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19964   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19965                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19966   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19967   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19968 }
19969
19970 /// Widen a vector input to a vector of NVT.  The
19971 /// input vector must have the same element type as NVT.
19972 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19973                             bool FillWithZeroes = false) {
19974   // Check if InOp already has the right width.
19975   MVT InVT = InOp.getSimpleValueType();
19976   if (InVT == NVT)
19977     return InOp;
19978
19979   if (InOp.isUndef())
19980     return DAG.getUNDEF(NVT);
19981
19982   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19983          "input and widen element type must match");
19984
19985   unsigned InNumElts = InVT.getVectorNumElements();
19986   unsigned WidenNumElts = NVT.getVectorNumElements();
19987   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
19988          "Unexpected request for vector widening");
19989
19990   EVT EltVT = NVT.getVectorElementType();
19991
19992   SDLoc dl(InOp);
19993   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
19994       InOp.getNumOperands() == 2) {
19995     SDValue N1 = InOp.getOperand(1);
19996     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
19997         N1.isUndef()) {
19998       InOp = InOp.getOperand(0);
19999       InVT = InOp.getSimpleValueType();
20000       InNumElts = InVT.getVectorNumElements();
20001     }
20002   }
20003   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
20004       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
20005     SmallVector<SDValue, 16> Ops;
20006     for (unsigned i = 0; i < InNumElts; ++i)
20007       Ops.push_back(InOp.getOperand(i));
20008
20009     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
20010       DAG.getUNDEF(EltVT);
20011     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
20012       Ops.push_back(FillVal);
20013     return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
20014   }
20015   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
20016     DAG.getUNDEF(NVT);
20017   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
20018                      InOp, DAG.getIntPtrConstant(0, dl));
20019 }
20020
20021 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
20022                              SelectionDAG &DAG) {
20023   assert(Subtarget->hasAVX512() &&
20024          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20025
20026   // X86 scatter kills mask register, so its type should be added to
20027   // the list of return values.
20028   // If the "scatter" has 2 return values, it is already handled.
20029   if (Op.getNode()->getNumValues() == 2)
20030     return Op;
20031
20032   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
20033   SDValue Src = N->getValue();
20034   MVT VT = Src.getSimpleValueType();
20035   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
20036   SDLoc dl(Op);
20037
20038   SDValue NewScatter;
20039   SDValue Index = N->getIndex();
20040   SDValue Mask = N->getMask();
20041   SDValue Chain = N->getChain();
20042   SDValue BasePtr = N->getBasePtr();
20043   MVT MemVT = N->getMemoryVT().getSimpleVT();
20044   MVT IndexVT = Index.getSimpleValueType();
20045   MVT MaskVT = Mask.getSimpleValueType();
20046
20047   if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
20048     // The v2i32 value was promoted to v2i64.
20049     // Now we "redo" the type legalizer's work and widen the original
20050     // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20051     // with a shuffle.
20052     assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20053            "Unexpected memory type");
20054     int ShuffleMask[] = {0, 2, -1, -1};
20055     Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20056                                DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20057     // Now we have 4 elements instead of 2.
20058     // Expand the index.
20059     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20060     Index = ExtendToType(Index, NewIndexVT, DAG);
20061
20062     // Expand the mask with zeroes
20063     // Mask may be <2 x i64> or <2 x i1> at this moment
20064     assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20065            "Unexpected mask type");
20066     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20067     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20068     VT = MVT::v4i32;
20069   }
20070
20071   unsigned NumElts = VT.getVectorNumElements();
20072   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20073       !Index.getSimpleValueType().is512BitVector()) {
20074     // AVX512F supports only 512-bit vectors. Or data or index should
20075     // be 512 bit wide. If now the both index and data are 256-bit, but
20076     // the vector contains 8 elements, we just sign-extend the index
20077     if (IndexVT == MVT::v8i32)
20078       // Just extend index
20079       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20080     else {
20081       // The minimal number of elts in scatter is 8
20082       NumElts = 8;
20083       // Index
20084       MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20085       // Use original index here, do not modify the index twice
20086       Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20087       if (IndexVT.getScalarType() == MVT::i32)
20088         Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20089
20090       // Mask
20091       // At this point we have promoted mask operand
20092       assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20093       MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20094       // Use the original mask here, do not modify the mask twice
20095       Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20096
20097       // The value that should be stored
20098       MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20099       Src = ExtendToType(Src, NewVT, DAG);
20100     }
20101   }
20102   // If the mask is "wide" at this point - truncate it to i1 vector
20103   MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20104   Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20105
20106   // The mask is killed by scatter, add it to the values
20107   SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20108   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20109   NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20110                                     N->getMemOperand());
20111   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20112   return SDValue(NewScatter.getNode(), 0);
20113 }
20114
20115 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20116                           SelectionDAG &DAG) {
20117
20118   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20119   MVT VT = Op.getSimpleValueType();
20120   SDValue Mask = N->getMask();
20121   SDLoc dl(Op);
20122
20123   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20124       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20125     // This operation is legal for targets with VLX, but without
20126     // VLX the vector should be widened to 512 bit
20127     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20128     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20129     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20130     SDValue Src0 = N->getSrc0();
20131     Src0 = ExtendToType(Src0, WideDataVT, DAG);
20132     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20133     SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20134                                         N->getBasePtr(), Mask, Src0,
20135                                         N->getMemoryVT(), N->getMemOperand(),
20136                                         N->getExtensionType());
20137
20138     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20139                                  NewLoad.getValue(0),
20140                                  DAG.getIntPtrConstant(0, dl));
20141     SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20142     return DAG.getMergeValues(RetOps, dl);
20143   }
20144   return Op;
20145 }
20146
20147 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20148                            SelectionDAG &DAG) {
20149   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20150   SDValue DataToStore = N->getValue();
20151   MVT VT = DataToStore.getSimpleValueType();
20152   SDValue Mask = N->getMask();
20153   SDLoc dl(Op);
20154
20155   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20156       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20157     // This operation is legal for targets with VLX, but without
20158     // VLX the vector should be widened to 512 bit
20159     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20160     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20161     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20162     DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20163     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20164     return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20165                               Mask, N->getMemoryVT(), N->getMemOperand(),
20166                               N->isTruncatingStore());
20167   }
20168   return Op;
20169 }
20170
20171 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20172                             SelectionDAG &DAG) {
20173   assert(Subtarget->hasAVX512() &&
20174          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20175
20176   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20177   SDLoc dl(Op);
20178   MVT VT = Op.getSimpleValueType();
20179   SDValue Index = N->getIndex();
20180   SDValue Mask = N->getMask();
20181   SDValue Src0 = N->getValue();
20182   MVT IndexVT = Index.getSimpleValueType();
20183   MVT MaskVT = Mask.getSimpleValueType();
20184
20185   unsigned NumElts = VT.getVectorNumElements();
20186   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20187
20188   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20189       !Index.getSimpleValueType().is512BitVector()) {
20190     // AVX512F supports only 512-bit vectors. Or data or index should
20191     // be 512 bit wide. If now the both index and data are 256-bit, but
20192     // the vector contains 8 elements, we just sign-extend the index
20193     if (NumElts == 8) {
20194       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20195       SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
20196                         N->getOperand(3), Index };
20197       DAG.UpdateNodeOperands(N, Ops);
20198       return Op;
20199     }
20200
20201     // Minimal number of elements in Gather
20202     NumElts = 8;
20203     // Index
20204     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20205     Index = ExtendToType(Index, NewIndexVT, DAG);
20206     if (IndexVT.getScalarType() == MVT::i32)
20207       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20208
20209     // Mask
20210     MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20211     // At this point we have promoted mask operand
20212     assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20213     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20214     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20215     Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20216
20217     // The pass-thru value
20218     MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20219     Src0 = ExtendToType(Src0, NewVT, DAG);
20220
20221     SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20222     SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20223                                             N->getMemoryVT(), dl, Ops,
20224                                             N->getMemOperand());
20225     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20226                                  NewGather.getValue(0),
20227                                  DAG.getIntPtrConstant(0, dl));
20228     SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20229     return DAG.getMergeValues(RetOps, dl);
20230   }
20231   return Op;
20232 }
20233
20234 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20235                                                     SelectionDAG &DAG) const {
20236   // TODO: Eventually, the lowering of these nodes should be informed by or
20237   // deferred to the GC strategy for the function in which they appear. For
20238   // now, however, they must be lowered to something. Since they are logically
20239   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20240   // require special handling for these nodes), lower them as literal NOOPs for
20241   // the time being.
20242   SmallVector<SDValue, 2> Ops;
20243
20244   Ops.push_back(Op.getOperand(0));
20245   if (Op->getGluedNode())
20246     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20247
20248   SDLoc OpDL(Op);
20249   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20250   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20251
20252   return NOOP;
20253 }
20254
20255 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20256                                                   SelectionDAG &DAG) const {
20257   // TODO: Eventually, the lowering of these nodes should be informed by or
20258   // deferred to the GC strategy for the function in which they appear. For
20259   // now, however, they must be lowered to something. Since they are logically
20260   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20261   // require special handling for these nodes), lower them as literal NOOPs for
20262   // the time being.
20263   SmallVector<SDValue, 2> Ops;
20264
20265   Ops.push_back(Op.getOperand(0));
20266   if (Op->getGluedNode())
20267     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20268
20269   SDLoc OpDL(Op);
20270   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20271   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20272
20273   return NOOP;
20274 }
20275
20276 /// LowerOperation - Provide custom lowering hooks for some operations.
20277 ///
20278 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20279   switch (Op.getOpcode()) {
20280   default: llvm_unreachable("Should not custom lower this!");
20281   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20282   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20283     return LowerCMP_SWAP(Op, Subtarget, DAG);
20284   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
20285   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
20286   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
20287   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
20288   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20289   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
20290   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
20291   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20292   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
20293   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20294   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20295   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
20296   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
20297   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
20298   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
20299   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
20300   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
20301   case ISD::SHL_PARTS:
20302   case ISD::SRA_PARTS:
20303   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
20304   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
20305   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
20306   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
20307   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
20308   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20309   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
20310   case ISD::SIGN_EXTEND_VECTOR_INREG:
20311     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20312   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
20313   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
20314   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
20315   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
20316   case ISD::FABS:
20317   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
20318   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
20319   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
20320   case ISD::SETCC:              return LowerSETCC(Op, DAG);
20321   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
20322   case ISD::SELECT:             return LowerSELECT(Op, DAG);
20323   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
20324   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
20325   case ISD::VASTART:            return LowerVASTART(Op, DAG);
20326   case ISD::VAARG:              return LowerVAARG(Op, DAG);
20327   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
20328   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20329   case ISD::INTRINSIC_VOID:
20330   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20331   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
20332   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
20333   case ISD::FRAME_TO_ARGS_OFFSET:
20334                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20335   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20336   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
20337   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
20338   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
20339   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
20340   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
20341   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
20342   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
20343   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20344   case ISD::CTTZ:
20345   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
20346   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
20347   case ISD::UMUL_LOHI:
20348   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
20349   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
20350   case ISD::SRA:
20351   case ISD::SRL:
20352   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
20353   case ISD::SADDO:
20354   case ISD::UADDO:
20355   case ISD::SSUBO:
20356   case ISD::USUBO:
20357   case ISD::SMULO:
20358   case ISD::UMULO:              return LowerXALUO(Op, DAG);
20359   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20360   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
20361   case ISD::ADDC:
20362   case ISD::ADDE:
20363   case ISD::SUBC:
20364   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20365   case ISD::ADD:                return LowerADD(Op, DAG);
20366   case ISD::SUB:                return LowerSUB(Op, DAG);
20367   case ISD::SMAX:
20368   case ISD::SMIN:
20369   case ISD::UMAX:
20370   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
20371   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
20372   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
20373   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
20374   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
20375   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
20376   case ISD::GC_TRANSITION_START:
20377                                 return LowerGC_TRANSITION_START(Op, DAG);
20378   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
20379   }
20380 }
20381
20382 /// ReplaceNodeResults - Replace a node with an illegal result type
20383 /// with a new node built out of custom code.
20384 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20385                                            SmallVectorImpl<SDValue>&Results,
20386                                            SelectionDAG &DAG) const {
20387   SDLoc dl(N);
20388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20389   switch (N->getOpcode()) {
20390   default:
20391     llvm_unreachable("Do not know how to custom type legalize this operation!");
20392   case X86ISD::AVG: {
20393     // Legalize types for X86ISD::AVG by expanding vectors.
20394     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20395
20396     auto InVT = N->getValueType(0);
20397     auto InVTSize = InVT.getSizeInBits();
20398     const unsigned RegSize =
20399         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20400     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20401            "512-bit vector requires AVX512");
20402     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20403            "256-bit vector requires AVX2");
20404
20405     auto ElemVT = InVT.getVectorElementType();
20406     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20407                                   RegSize / ElemVT.getSizeInBits());
20408     assert(RegSize % InVT.getSizeInBits() == 0);
20409     unsigned NumConcat = RegSize / InVT.getSizeInBits();
20410
20411     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20412     Ops[0] = N->getOperand(0);
20413     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20414     Ops[0] = N->getOperand(1);
20415     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20416
20417     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20418     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20419                                   DAG.getIntPtrConstant(0, dl)));
20420     return;
20421   }
20422   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20423   case X86ISD::FMINC:
20424   case X86ISD::FMIN:
20425   case X86ISD::FMAXC:
20426   case X86ISD::FMAX: {
20427     EVT VT = N->getValueType(0);
20428     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20429     SDValue UNDEF = DAG.getUNDEF(VT);
20430     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20431                               N->getOperand(0), UNDEF);
20432     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20433                               N->getOperand(1), UNDEF);
20434     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20435     return;
20436   }
20437   case ISD::SIGN_EXTEND_INREG:
20438   case ISD::ADDC:
20439   case ISD::ADDE:
20440   case ISD::SUBC:
20441   case ISD::SUBE:
20442     // We don't want to expand or promote these.
20443     return;
20444   case ISD::SDIV:
20445   case ISD::UDIV:
20446   case ISD::SREM:
20447   case ISD::UREM:
20448   case ISD::SDIVREM:
20449   case ISD::UDIVREM: {
20450     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20451     Results.push_back(V);
20452     return;
20453   }
20454   case ISD::FP_TO_SINT:
20455   case ISD::FP_TO_UINT: {
20456     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20457
20458     std::pair<SDValue,SDValue> Vals =
20459         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20460     SDValue FIST = Vals.first, StackSlot = Vals.second;
20461     if (FIST.getNode()) {
20462       EVT VT = N->getValueType(0);
20463       // Return a load from the stack slot.
20464       if (StackSlot.getNode())
20465         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20466                                       MachinePointerInfo(),
20467                                       false, false, false, 0));
20468       else
20469         Results.push_back(FIST);
20470     }
20471     return;
20472   }
20473   case ISD::UINT_TO_FP: {
20474     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20475     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20476         N->getValueType(0) != MVT::v2f32)
20477       return;
20478     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20479                                  N->getOperand(0));
20480     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20481                                      MVT::f64);
20482     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20483     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20484                              DAG.getBitcast(MVT::v2i64, VBias));
20485     Or = DAG.getBitcast(MVT::v2f64, Or);
20486     // TODO: Are there any fast-math-flags to propagate here?
20487     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20488     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20489     return;
20490   }
20491   case ISD::FP_ROUND: {
20492     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20493         return;
20494     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20495     Results.push_back(V);
20496     return;
20497   }
20498   case ISD::FP_EXTEND: {
20499     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20500     // No other ValueType for FP_EXTEND should reach this point.
20501     assert(N->getValueType(0) == MVT::v2f32 &&
20502            "Do not know how to legalize this Node");
20503     return;
20504   }
20505   case ISD::INTRINSIC_W_CHAIN: {
20506     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20507     switch (IntNo) {
20508     default : llvm_unreachable("Do not know how to custom type "
20509                                "legalize this intrinsic operation!");
20510     case Intrinsic::x86_rdtsc:
20511       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20512                                      Results);
20513     case Intrinsic::x86_rdtscp:
20514       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20515                                      Results);
20516     case Intrinsic::x86_rdpmc:
20517       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20518     }
20519   }
20520   case ISD::INTRINSIC_WO_CHAIN: {
20521     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20522       Results.push_back(V);
20523     return;
20524   }
20525   case ISD::READCYCLECOUNTER: {
20526     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20527                                    Results);
20528   }
20529   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20530     EVT T = N->getValueType(0);
20531     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20532     bool Regs64bit = T == MVT::i128;
20533     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20534     SDValue cpInL, cpInH;
20535     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20536                         DAG.getConstant(0, dl, HalfT));
20537     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20538                         DAG.getConstant(1, dl, HalfT));
20539     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20540                              Regs64bit ? X86::RAX : X86::EAX,
20541                              cpInL, SDValue());
20542     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20543                              Regs64bit ? X86::RDX : X86::EDX,
20544                              cpInH, cpInL.getValue(1));
20545     SDValue swapInL, swapInH;
20546     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20547                           DAG.getConstant(0, dl, HalfT));
20548     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20549                           DAG.getConstant(1, dl, HalfT));
20550     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20551                                Regs64bit ? X86::RBX : X86::EBX,
20552                                swapInL, cpInH.getValue(1));
20553     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20554                                Regs64bit ? X86::RCX : X86::ECX,
20555                                swapInH, swapInL.getValue(1));
20556     SDValue Ops[] = { swapInH.getValue(0),
20557                       N->getOperand(1),
20558                       swapInH.getValue(1) };
20559     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20560     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20561     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20562                                   X86ISD::LCMPXCHG8_DAG;
20563     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20564     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20565                                         Regs64bit ? X86::RAX : X86::EAX,
20566                                         HalfT, Result.getValue(1));
20567     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20568                                         Regs64bit ? X86::RDX : X86::EDX,
20569                                         HalfT, cpOutL.getValue(2));
20570     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20571
20572     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20573                                         MVT::i32, cpOutH.getValue(2));
20574     SDValue Success =
20575         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20576                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20577     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20578
20579     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20580     Results.push_back(Success);
20581     Results.push_back(EFLAGS.getValue(1));
20582     return;
20583   }
20584   case ISD::ATOMIC_SWAP:
20585   case ISD::ATOMIC_LOAD_ADD:
20586   case ISD::ATOMIC_LOAD_SUB:
20587   case ISD::ATOMIC_LOAD_AND:
20588   case ISD::ATOMIC_LOAD_OR:
20589   case ISD::ATOMIC_LOAD_XOR:
20590   case ISD::ATOMIC_LOAD_NAND:
20591   case ISD::ATOMIC_LOAD_MIN:
20592   case ISD::ATOMIC_LOAD_MAX:
20593   case ISD::ATOMIC_LOAD_UMIN:
20594   case ISD::ATOMIC_LOAD_UMAX:
20595   case ISD::ATOMIC_LOAD: {
20596     // Delegate to generic TypeLegalization. Situations we can really handle
20597     // should have already been dealt with by AtomicExpandPass.cpp.
20598     break;
20599   }
20600   case ISD::BITCAST: {
20601     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20602     EVT DstVT = N->getValueType(0);
20603     EVT SrcVT = N->getOperand(0)->getValueType(0);
20604
20605     if (SrcVT != MVT::f64 ||
20606         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20607       return;
20608
20609     unsigned NumElts = DstVT.getVectorNumElements();
20610     EVT SVT = DstVT.getVectorElementType();
20611     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20612     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20613                                    MVT::v2f64, N->getOperand(0));
20614     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20615
20616     if (ExperimentalVectorWideningLegalization) {
20617       // If we are legalizing vectors by widening, we already have the desired
20618       // legal vector type, just return it.
20619       Results.push_back(ToVecInt);
20620       return;
20621     }
20622
20623     SmallVector<SDValue, 8> Elts;
20624     for (unsigned i = 0, e = NumElts; i != e; ++i)
20625       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20626                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20627
20628     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20629   }
20630   }
20631 }
20632
20633 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20634   switch ((X86ISD::NodeType)Opcode) {
20635   case X86ISD::FIRST_NUMBER:       break;
20636   case X86ISD::BSF:                return "X86ISD::BSF";
20637   case X86ISD::BSR:                return "X86ISD::BSR";
20638   case X86ISD::SHLD:               return "X86ISD::SHLD";
20639   case X86ISD::SHRD:               return "X86ISD::SHRD";
20640   case X86ISD::FAND:               return "X86ISD::FAND";
20641   case X86ISD::FANDN:              return "X86ISD::FANDN";
20642   case X86ISD::FOR:                return "X86ISD::FOR";
20643   case X86ISD::FXOR:               return "X86ISD::FXOR";
20644   case X86ISD::FILD:               return "X86ISD::FILD";
20645   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20646   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20647   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20648   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20649   case X86ISD::FLD:                return "X86ISD::FLD";
20650   case X86ISD::FST:                return "X86ISD::FST";
20651   case X86ISD::CALL:               return "X86ISD::CALL";
20652   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20653   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20654   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20655   case X86ISD::BT:                 return "X86ISD::BT";
20656   case X86ISD::CMP:                return "X86ISD::CMP";
20657   case X86ISD::COMI:               return "X86ISD::COMI";
20658   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20659   case X86ISD::CMPM:               return "X86ISD::CMPM";
20660   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20661   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20662   case X86ISD::SETCC:              return "X86ISD::SETCC";
20663   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20664   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20665   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20666   case X86ISD::CMOV:               return "X86ISD::CMOV";
20667   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20668   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20669   case X86ISD::IRET:               return "X86ISD::IRET";
20670   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20671   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20672   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20673   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20674   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20675   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20676   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20677   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20678   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20679   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20680   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20681   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20682   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20683   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20684   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20685   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20686   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20687   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20688   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20689   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20690   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20691   case X86ISD::HADD:               return "X86ISD::HADD";
20692   case X86ISD::HSUB:               return "X86ISD::HSUB";
20693   case X86ISD::FHADD:              return "X86ISD::FHADD";
20694   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20695   case X86ISD::ABS:                return "X86ISD::ABS";
20696   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20697   case X86ISD::FMAX:               return "X86ISD::FMAX";
20698   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20699   case X86ISD::FMIN:               return "X86ISD::FMIN";
20700   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20701   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20702   case X86ISD::FMINC:              return "X86ISD::FMINC";
20703   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20704   case X86ISD::FRCP:               return "X86ISD::FRCP";
20705   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20706   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20707   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20708   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20709   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20710   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20711   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20712   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20713   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20714   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20715   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20716   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20717   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20718   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20719   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20720   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20721   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20722   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20723   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20724   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20725   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20726   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20727   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20728   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20729   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20730   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20731   case X86ISD::CVT2MASK:           return "X86ISD::CVT2MASK";
20732   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20733   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20734   case X86ISD::VSHL:               return "X86ISD::VSHL";
20735   case X86ISD::VSRL:               return "X86ISD::VSRL";
20736   case X86ISD::VSRA:               return "X86ISD::VSRA";
20737   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20738   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20739   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20740   case X86ISD::CMPP:               return "X86ISD::CMPP";
20741   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20742   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20743   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20744   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20745   case X86ISD::ADD:                return "X86ISD::ADD";
20746   case X86ISD::SUB:                return "X86ISD::SUB";
20747   case X86ISD::ADC:                return "X86ISD::ADC";
20748   case X86ISD::SBB:                return "X86ISD::SBB";
20749   case X86ISD::SMUL:               return "X86ISD::SMUL";
20750   case X86ISD::UMUL:               return "X86ISD::UMUL";
20751   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20752   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20753   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20754   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20755   case X86ISD::INC:                return "X86ISD::INC";
20756   case X86ISD::DEC:                return "X86ISD::DEC";
20757   case X86ISD::OR:                 return "X86ISD::OR";
20758   case X86ISD::XOR:                return "X86ISD::XOR";
20759   case X86ISD::AND:                return "X86ISD::AND";
20760   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20761   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20762   case X86ISD::PTEST:              return "X86ISD::PTEST";
20763   case X86ISD::TESTP:              return "X86ISD::TESTP";
20764   case X86ISD::TESTM:              return "X86ISD::TESTM";
20765   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20766   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20767   case X86ISD::KTEST:              return "X86ISD::KTEST";
20768   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20769   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20770   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20771   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20772   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20773   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20774   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20775   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20776   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20777   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20778   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20779   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20780   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20781   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20782   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20783   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20784   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20785   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20786   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20787   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20788   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20789   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20790   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20791   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20792   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20793   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20794   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20795   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20796   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20797   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20798   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20799   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20800   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20801   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20802   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20803   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20804   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20805   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20806   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20807   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20808   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20809   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20810   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20811   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20812   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20813   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20814   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20815   case X86ISD::SAHF:               return "X86ISD::SAHF";
20816   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20817   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20818   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20819   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20820   case X86ISD::VPROT:              return "X86ISD::VPROT";
20821   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20822   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20823   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20824   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20825   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20826   case X86ISD::FMADD:              return "X86ISD::FMADD";
20827   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20828   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20829   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20830   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20831   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20832   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20833   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20834   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20835   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20836   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20837   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20838   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20839   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20840   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20841   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20842   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20843   case X86ISD::XTEST:              return "X86ISD::XTEST";
20844   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20845   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20846   case X86ISD::SELECT:             return "X86ISD::SELECT";
20847   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20848   case X86ISD::RCP28:              return "X86ISD::RCP28";
20849   case X86ISD::EXP2:               return "X86ISD::EXP2";
20850   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20851   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20852   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20853   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20854   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20855   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20856   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20857   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20858   case X86ISD::ADDS:               return "X86ISD::ADDS";
20859   case X86ISD::SUBS:               return "X86ISD::SUBS";
20860   case X86ISD::AVG:                return "X86ISD::AVG";
20861   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20862   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20863   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20864   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20865   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20866   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20867   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
20868   }
20869   return nullptr;
20870 }
20871
20872 // isLegalAddressingMode - Return true if the addressing mode represented
20873 // by AM is legal for this target, for a load/store of the specified type.
20874 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20875                                               const AddrMode &AM, Type *Ty,
20876                                               unsigned AS) const {
20877   // X86 supports extremely general addressing modes.
20878   CodeModel::Model M = getTargetMachine().getCodeModel();
20879   Reloc::Model R = getTargetMachine().getRelocationModel();
20880
20881   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20882   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20883     return false;
20884
20885   if (AM.BaseGV) {
20886     unsigned GVFlags =
20887       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20888
20889     // If a reference to this global requires an extra load, we can't fold it.
20890     if (isGlobalStubReference(GVFlags))
20891       return false;
20892
20893     // If BaseGV requires a register for the PIC base, we cannot also have a
20894     // BaseReg specified.
20895     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20896       return false;
20897
20898     // If lower 4G is not available, then we must use rip-relative addressing.
20899     if ((M != CodeModel::Small || R != Reloc::Static) &&
20900         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20901       return false;
20902   }
20903
20904   switch (AM.Scale) {
20905   case 0:
20906   case 1:
20907   case 2:
20908   case 4:
20909   case 8:
20910     // These scales always work.
20911     break;
20912   case 3:
20913   case 5:
20914   case 9:
20915     // These scales are formed with basereg+scalereg.  Only accept if there is
20916     // no basereg yet.
20917     if (AM.HasBaseReg)
20918       return false;
20919     break;
20920   default:  // Other stuff never works.
20921     return false;
20922   }
20923
20924   return true;
20925 }
20926
20927 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20928   unsigned Bits = Ty->getScalarSizeInBits();
20929
20930   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20931   // particularly cheaper than those without.
20932   if (Bits == 8)
20933     return false;
20934
20935   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20936   // variable shifts just as cheap as scalar ones.
20937   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20938     return false;
20939
20940   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20941   // fully general vector.
20942   return true;
20943 }
20944
20945 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20946   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20947     return false;
20948   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20949   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20950   return NumBits1 > NumBits2;
20951 }
20952
20953 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20954   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20955     return false;
20956
20957   if (!isTypeLegal(EVT::getEVT(Ty1)))
20958     return false;
20959
20960   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20961
20962   // Assuming the caller doesn't have a zeroext or signext return parameter,
20963   // truncation all the way down to i1 is valid.
20964   return true;
20965 }
20966
20967 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20968   return isInt<32>(Imm);
20969 }
20970
20971 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20972   // Can also use sub to handle negated immediates.
20973   return isInt<32>(Imm);
20974 }
20975
20976 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20977   if (!VT1.isInteger() || !VT2.isInteger())
20978     return false;
20979   unsigned NumBits1 = VT1.getSizeInBits();
20980   unsigned NumBits2 = VT2.getSizeInBits();
20981   return NumBits1 > NumBits2;
20982 }
20983
20984 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20985   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20986   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20987 }
20988
20989 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20990   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20991   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20992 }
20993
20994 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20995   EVT VT1 = Val.getValueType();
20996   if (isZExtFree(VT1, VT2))
20997     return true;
20998
20999   if (Val.getOpcode() != ISD::LOAD)
21000     return false;
21001
21002   if (!VT1.isSimple() || !VT1.isInteger() ||
21003       !VT2.isSimple() || !VT2.isInteger())
21004     return false;
21005
21006   switch (VT1.getSimpleVT().SimpleTy) {
21007   default: break;
21008   case MVT::i8:
21009   case MVT::i16:
21010   case MVT::i32:
21011     // X86 has 8, 16, and 32-bit zero-extending loads.
21012     return true;
21013   }
21014
21015   return false;
21016 }
21017
21018 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
21019
21020 bool
21021 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
21022   if (!Subtarget->hasAnyFMA())
21023     return false;
21024
21025   VT = VT.getScalarType();
21026
21027   if (!VT.isSimple())
21028     return false;
21029
21030   switch (VT.getSimpleVT().SimpleTy) {
21031   case MVT::f32:
21032   case MVT::f64:
21033     return true;
21034   default:
21035     break;
21036   }
21037
21038   return false;
21039 }
21040
21041 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
21042   // i16 instructions are longer (0x66 prefix) and potentially slower.
21043   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
21044 }
21045
21046 /// isShuffleMaskLegal - Targets can use this to indicate that they only
21047 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
21048 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21049 /// are assumed to be legal.
21050 bool
21051 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21052                                       EVT VT) const {
21053   if (!VT.isSimple())
21054     return false;
21055
21056   // Not for i1 vectors
21057   if (VT.getSimpleVT().getScalarType() == MVT::i1)
21058     return false;
21059
21060   // Very little shuffling can be done for 64-bit vectors right now.
21061   if (VT.getSimpleVT().getSizeInBits() == 64)
21062     return false;
21063
21064   // We only care that the types being shuffled are legal. The lowering can
21065   // handle any possible shuffle mask that results.
21066   return isTypeLegal(VT.getSimpleVT());
21067 }
21068
21069 bool
21070 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21071                                           EVT VT) const {
21072   // Just delegate to the generic legality, clear masks aren't special.
21073   return isShuffleMaskLegal(Mask, VT);
21074 }
21075
21076 //===----------------------------------------------------------------------===//
21077 //                           X86 Scheduler Hooks
21078 //===----------------------------------------------------------------------===//
21079
21080 /// Utility function to emit xbegin specifying the start of an RTM region.
21081 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21082                                      const TargetInstrInfo *TII) {
21083   DebugLoc DL = MI->getDebugLoc();
21084
21085   const BasicBlock *BB = MBB->getBasicBlock();
21086   MachineFunction::iterator I = ++MBB->getIterator();
21087
21088   // For the v = xbegin(), we generate
21089   //
21090   // thisMBB:
21091   //  xbegin sinkMBB
21092   //
21093   // mainMBB:
21094   //  eax = -1
21095   //
21096   // sinkMBB:
21097   //  v = eax
21098
21099   MachineBasicBlock *thisMBB = MBB;
21100   MachineFunction *MF = MBB->getParent();
21101   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21102   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21103   MF->insert(I, mainMBB);
21104   MF->insert(I, sinkMBB);
21105
21106   // Transfer the remainder of BB and its successor edges to sinkMBB.
21107   sinkMBB->splice(sinkMBB->begin(), MBB,
21108                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21109   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21110
21111   // thisMBB:
21112   //  xbegin sinkMBB
21113   //  # fallthrough to mainMBB
21114   //  # abortion to sinkMBB
21115   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21116   thisMBB->addSuccessor(mainMBB);
21117   thisMBB->addSuccessor(sinkMBB);
21118
21119   // mainMBB:
21120   //  EAX = -1
21121   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21122   mainMBB->addSuccessor(sinkMBB);
21123
21124   // sinkMBB:
21125   // EAX is live into the sinkMBB
21126   sinkMBB->addLiveIn(X86::EAX);
21127   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21128           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21129     .addReg(X86::EAX);
21130
21131   MI->eraseFromParent();
21132   return sinkMBB;
21133 }
21134
21135 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21136 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21137 // in the .td file.
21138 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21139                                        const TargetInstrInfo *TII) {
21140   unsigned Opc;
21141   switch (MI->getOpcode()) {
21142   default: llvm_unreachable("illegal opcode!");
21143   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
21144   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21145   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
21146   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21147   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
21148   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21149   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
21150   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21151   }
21152
21153   DebugLoc dl = MI->getDebugLoc();
21154   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21155
21156   unsigned NumArgs = MI->getNumOperands();
21157   for (unsigned i = 1; i < NumArgs; ++i) {
21158     MachineOperand &Op = MI->getOperand(i);
21159     if (!(Op.isReg() && Op.isImplicit()))
21160       MIB.addOperand(Op);
21161   }
21162   if (MI->hasOneMemOperand())
21163     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21164
21165   BuildMI(*BB, MI, dl,
21166     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21167     .addReg(X86::XMM0);
21168
21169   MI->eraseFromParent();
21170   return BB;
21171 }
21172
21173 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21174 // defs in an instruction pattern
21175 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21176                                        const TargetInstrInfo *TII) {
21177   unsigned Opc;
21178   switch (MI->getOpcode()) {
21179   default: llvm_unreachable("illegal opcode!");
21180   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
21181   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21182   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
21183   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21184   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
21185   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21186   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
21187   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21188   }
21189
21190   DebugLoc dl = MI->getDebugLoc();
21191   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21192
21193   unsigned NumArgs = MI->getNumOperands(); // remove the results
21194   for (unsigned i = 1; i < NumArgs; ++i) {
21195     MachineOperand &Op = MI->getOperand(i);
21196     if (!(Op.isReg() && Op.isImplicit()))
21197       MIB.addOperand(Op);
21198   }
21199   if (MI->hasOneMemOperand())
21200     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21201
21202   BuildMI(*BB, MI, dl,
21203     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21204     .addReg(X86::ECX);
21205
21206   MI->eraseFromParent();
21207   return BB;
21208 }
21209
21210 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21211                                      const X86Subtarget *Subtarget) {
21212   DebugLoc dl = MI->getDebugLoc();
21213   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21214
21215   // insert input VAL into EAX
21216   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21217                            .addReg(MI->getOperand(0).getReg());
21218   // insert zero to ECX
21219   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21220                            .addReg(X86::ECX)
21221                            .addReg(X86::ECX);
21222   // insert zero to EDX
21223   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21224                            .addReg(X86::EDX)
21225                            .addReg(X86::EDX);
21226   // insert WRPKRU instruction
21227   BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21228
21229   MI->eraseFromParent(); // The pseudo is gone now.
21230   return BB;
21231 }
21232
21233 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21234                                      const X86Subtarget *Subtarget) {
21235   DebugLoc dl = MI->getDebugLoc();
21236   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21237
21238   // insert zero to ECX
21239   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21240                            .addReg(X86::ECX)
21241                            .addReg(X86::ECX);
21242   // insert RDPKRU instruction
21243   BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21244   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21245                            .addReg(X86::EAX);
21246
21247   MI->eraseFromParent(); // The pseudo is gone now.
21248   return BB;
21249 }
21250
21251 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21252                                       const X86Subtarget *Subtarget) {
21253   DebugLoc dl = MI->getDebugLoc();
21254   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21255   // Address into RAX/EAX, other two args into ECX, EDX.
21256   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21257   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21258   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21259   for (int i = 0; i < X86::AddrNumOperands; ++i)
21260     MIB.addOperand(MI->getOperand(i));
21261
21262   unsigned ValOps = X86::AddrNumOperands;
21263   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21264     .addReg(MI->getOperand(ValOps).getReg());
21265   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21266     .addReg(MI->getOperand(ValOps+1).getReg());
21267
21268   // The instruction doesn't actually take any operands though.
21269   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21270
21271   MI->eraseFromParent(); // The pseudo is gone now.
21272   return BB;
21273 }
21274
21275 MachineBasicBlock *
21276 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21277                                                  MachineBasicBlock *MBB) const {
21278   // Emit va_arg instruction on X86-64.
21279
21280   // Operands to this pseudo-instruction:
21281   // 0  ) Output        : destination address (reg)
21282   // 1-5) Input         : va_list address (addr, i64mem)
21283   // 6  ) ArgSize       : Size (in bytes) of vararg type
21284   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21285   // 8  ) Align         : Alignment of type
21286   // 9  ) EFLAGS (implicit-def)
21287
21288   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21289   static_assert(X86::AddrNumOperands == 5,
21290                 "VAARG_64 assumes 5 address operands");
21291
21292   unsigned DestReg = MI->getOperand(0).getReg();
21293   MachineOperand &Base = MI->getOperand(1);
21294   MachineOperand &Scale = MI->getOperand(2);
21295   MachineOperand &Index = MI->getOperand(3);
21296   MachineOperand &Disp = MI->getOperand(4);
21297   MachineOperand &Segment = MI->getOperand(5);
21298   unsigned ArgSize = MI->getOperand(6).getImm();
21299   unsigned ArgMode = MI->getOperand(7).getImm();
21300   unsigned Align = MI->getOperand(8).getImm();
21301
21302   // Memory Reference
21303   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21304   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21305   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21306
21307   // Machine Information
21308   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21309   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21310   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21311   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21312   DebugLoc DL = MI->getDebugLoc();
21313
21314   // struct va_list {
21315   //   i32   gp_offset
21316   //   i32   fp_offset
21317   //   i64   overflow_area (address)
21318   //   i64   reg_save_area (address)
21319   // }
21320   // sizeof(va_list) = 24
21321   // alignment(va_list) = 8
21322
21323   unsigned TotalNumIntRegs = 6;
21324   unsigned TotalNumXMMRegs = 8;
21325   bool UseGPOffset = (ArgMode == 1);
21326   bool UseFPOffset = (ArgMode == 2);
21327   unsigned MaxOffset = TotalNumIntRegs * 8 +
21328                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21329
21330   /* Align ArgSize to a multiple of 8 */
21331   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21332   bool NeedsAlign = (Align > 8);
21333
21334   MachineBasicBlock *thisMBB = MBB;
21335   MachineBasicBlock *overflowMBB;
21336   MachineBasicBlock *offsetMBB;
21337   MachineBasicBlock *endMBB;
21338
21339   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
21340   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
21341   unsigned OffsetReg = 0;
21342
21343   if (!UseGPOffset && !UseFPOffset) {
21344     // If we only pull from the overflow region, we don't create a branch.
21345     // We don't need to alter control flow.
21346     OffsetDestReg = 0; // unused
21347     OverflowDestReg = DestReg;
21348
21349     offsetMBB = nullptr;
21350     overflowMBB = thisMBB;
21351     endMBB = thisMBB;
21352   } else {
21353     // First emit code to check if gp_offset (or fp_offset) is below the bound.
21354     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21355     // If not, pull from overflow_area. (branch to overflowMBB)
21356     //
21357     //       thisMBB
21358     //         |     .
21359     //         |        .
21360     //     offsetMBB   overflowMBB
21361     //         |        .
21362     //         |     .
21363     //        endMBB
21364
21365     // Registers for the PHI in endMBB
21366     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21367     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21368
21369     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21370     MachineFunction *MF = MBB->getParent();
21371     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21372     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21373     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21374
21375     MachineFunction::iterator MBBIter = ++MBB->getIterator();
21376
21377     // Insert the new basic blocks
21378     MF->insert(MBBIter, offsetMBB);
21379     MF->insert(MBBIter, overflowMBB);
21380     MF->insert(MBBIter, endMBB);
21381
21382     // Transfer the remainder of MBB and its successor edges to endMBB.
21383     endMBB->splice(endMBB->begin(), thisMBB,
21384                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21385     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21386
21387     // Make offsetMBB and overflowMBB successors of thisMBB
21388     thisMBB->addSuccessor(offsetMBB);
21389     thisMBB->addSuccessor(overflowMBB);
21390
21391     // endMBB is a successor of both offsetMBB and overflowMBB
21392     offsetMBB->addSuccessor(endMBB);
21393     overflowMBB->addSuccessor(endMBB);
21394
21395     // Load the offset value into a register
21396     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21397     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21398       .addOperand(Base)
21399       .addOperand(Scale)
21400       .addOperand(Index)
21401       .addDisp(Disp, UseFPOffset ? 4 : 0)
21402       .addOperand(Segment)
21403       .setMemRefs(MMOBegin, MMOEnd);
21404
21405     // Check if there is enough room left to pull this argument.
21406     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21407       .addReg(OffsetReg)
21408       .addImm(MaxOffset + 8 - ArgSizeA8);
21409
21410     // Branch to "overflowMBB" if offset >= max
21411     // Fall through to "offsetMBB" otherwise
21412     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21413       .addMBB(overflowMBB);
21414   }
21415
21416   // In offsetMBB, emit code to use the reg_save_area.
21417   if (offsetMBB) {
21418     assert(OffsetReg != 0);
21419
21420     // Read the reg_save_area address.
21421     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21422     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21423       .addOperand(Base)
21424       .addOperand(Scale)
21425       .addOperand(Index)
21426       .addDisp(Disp, 16)
21427       .addOperand(Segment)
21428       .setMemRefs(MMOBegin, MMOEnd);
21429
21430     // Zero-extend the offset
21431     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21432       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21433         .addImm(0)
21434         .addReg(OffsetReg)
21435         .addImm(X86::sub_32bit);
21436
21437     // Add the offset to the reg_save_area to get the final address.
21438     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21439       .addReg(OffsetReg64)
21440       .addReg(RegSaveReg);
21441
21442     // Compute the offset for the next argument
21443     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21444     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21445       .addReg(OffsetReg)
21446       .addImm(UseFPOffset ? 16 : 8);
21447
21448     // Store it back into the va_list.
21449     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21450       .addOperand(Base)
21451       .addOperand(Scale)
21452       .addOperand(Index)
21453       .addDisp(Disp, UseFPOffset ? 4 : 0)
21454       .addOperand(Segment)
21455       .addReg(NextOffsetReg)
21456       .setMemRefs(MMOBegin, MMOEnd);
21457
21458     // Jump to endMBB
21459     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21460       .addMBB(endMBB);
21461   }
21462
21463   //
21464   // Emit code to use overflow area
21465   //
21466
21467   // Load the overflow_area address into a register.
21468   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21469   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21470     .addOperand(Base)
21471     .addOperand(Scale)
21472     .addOperand(Index)
21473     .addDisp(Disp, 8)
21474     .addOperand(Segment)
21475     .setMemRefs(MMOBegin, MMOEnd);
21476
21477   // If we need to align it, do so. Otherwise, just copy the address
21478   // to OverflowDestReg.
21479   if (NeedsAlign) {
21480     // Align the overflow address
21481     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21482     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21483
21484     // aligned_addr = (addr + (align-1)) & ~(align-1)
21485     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21486       .addReg(OverflowAddrReg)
21487       .addImm(Align-1);
21488
21489     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21490       .addReg(TmpReg)
21491       .addImm(~(uint64_t)(Align-1));
21492   } else {
21493     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21494       .addReg(OverflowAddrReg);
21495   }
21496
21497   // Compute the next overflow address after this argument.
21498   // (the overflow address should be kept 8-byte aligned)
21499   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21500   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21501     .addReg(OverflowDestReg)
21502     .addImm(ArgSizeA8);
21503
21504   // Store the new overflow address.
21505   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21506     .addOperand(Base)
21507     .addOperand(Scale)
21508     .addOperand(Index)
21509     .addDisp(Disp, 8)
21510     .addOperand(Segment)
21511     .addReg(NextAddrReg)
21512     .setMemRefs(MMOBegin, MMOEnd);
21513
21514   // If we branched, emit the PHI to the front of endMBB.
21515   if (offsetMBB) {
21516     BuildMI(*endMBB, endMBB->begin(), DL,
21517             TII->get(X86::PHI), DestReg)
21518       .addReg(OffsetDestReg).addMBB(offsetMBB)
21519       .addReg(OverflowDestReg).addMBB(overflowMBB);
21520   }
21521
21522   // Erase the pseudo instruction
21523   MI->eraseFromParent();
21524
21525   return endMBB;
21526 }
21527
21528 MachineBasicBlock *
21529 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21530                                                  MachineInstr *MI,
21531                                                  MachineBasicBlock *MBB) const {
21532   // Emit code to save XMM registers to the stack. The ABI says that the
21533   // number of registers to save is given in %al, so it's theoretically
21534   // possible to do an indirect jump trick to avoid saving all of them,
21535   // however this code takes a simpler approach and just executes all
21536   // of the stores if %al is non-zero. It's less code, and it's probably
21537   // easier on the hardware branch predictor, and stores aren't all that
21538   // expensive anyway.
21539
21540   // Create the new basic blocks. One block contains all the XMM stores,
21541   // and one block is the final destination regardless of whether any
21542   // stores were performed.
21543   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21544   MachineFunction *F = MBB->getParent();
21545   MachineFunction::iterator MBBIter = ++MBB->getIterator();
21546   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21547   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21548   F->insert(MBBIter, XMMSaveMBB);
21549   F->insert(MBBIter, EndMBB);
21550
21551   // Transfer the remainder of MBB and its successor edges to EndMBB.
21552   EndMBB->splice(EndMBB->begin(), MBB,
21553                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21554   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21555
21556   // The original block will now fall through to the XMM save block.
21557   MBB->addSuccessor(XMMSaveMBB);
21558   // The XMMSaveMBB will fall through to the end block.
21559   XMMSaveMBB->addSuccessor(EndMBB);
21560
21561   // Now add the instructions.
21562   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21563   DebugLoc DL = MI->getDebugLoc();
21564
21565   unsigned CountReg = MI->getOperand(0).getReg();
21566   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21567   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21568
21569   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21570     // If %al is 0, branch around the XMM save block.
21571     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21572     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21573     MBB->addSuccessor(EndMBB);
21574   }
21575
21576   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21577   // that was just emitted, but clearly shouldn't be "saved".
21578   assert((MI->getNumOperands() <= 3 ||
21579           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21580           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21581          && "Expected last argument to be EFLAGS");
21582   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21583   // In the XMM save block, save all the XMM argument registers.
21584   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21585     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21586     MachineMemOperand *MMO = F->getMachineMemOperand(
21587         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21588         MachineMemOperand::MOStore,
21589         /*Size=*/16, /*Align=*/16);
21590     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21591       .addFrameIndex(RegSaveFrameIndex)
21592       .addImm(/*Scale=*/1)
21593       .addReg(/*IndexReg=*/0)
21594       .addImm(/*Disp=*/Offset)
21595       .addReg(/*Segment=*/0)
21596       .addReg(MI->getOperand(i).getReg())
21597       .addMemOperand(MMO);
21598   }
21599
21600   MI->eraseFromParent();   // The pseudo instruction is gone now.
21601
21602   return EndMBB;
21603 }
21604
21605 // The EFLAGS operand of SelectItr might be missing a kill marker
21606 // because there were multiple uses of EFLAGS, and ISel didn't know
21607 // which to mark. Figure out whether SelectItr should have had a
21608 // kill marker, and set it if it should. Returns the correct kill
21609 // marker value.
21610 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21611                                      MachineBasicBlock* BB,
21612                                      const TargetRegisterInfo* TRI) {
21613   // Scan forward through BB for a use/def of EFLAGS.
21614   MachineBasicBlock::iterator miI(std::next(SelectItr));
21615   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21616     const MachineInstr& mi = *miI;
21617     if (mi.readsRegister(X86::EFLAGS))
21618       return false;
21619     if (mi.definesRegister(X86::EFLAGS))
21620       break; // Should have kill-flag - update below.
21621   }
21622
21623   // If we hit the end of the block, check whether EFLAGS is live into a
21624   // successor.
21625   if (miI == BB->end()) {
21626     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21627                                           sEnd = BB->succ_end();
21628          sItr != sEnd; ++sItr) {
21629       MachineBasicBlock* succ = *sItr;
21630       if (succ->isLiveIn(X86::EFLAGS))
21631         return false;
21632     }
21633   }
21634
21635   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21636   // out. SelectMI should have a kill flag on EFLAGS.
21637   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21638   return true;
21639 }
21640
21641 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21642 // together with other CMOV pseudo-opcodes into a single basic-block with
21643 // conditional jump around it.
21644 static bool isCMOVPseudo(MachineInstr *MI) {
21645   switch (MI->getOpcode()) {
21646   case X86::CMOV_FR32:
21647   case X86::CMOV_FR64:
21648   case X86::CMOV_GR8:
21649   case X86::CMOV_GR16:
21650   case X86::CMOV_GR32:
21651   case X86::CMOV_RFP32:
21652   case X86::CMOV_RFP64:
21653   case X86::CMOV_RFP80:
21654   case X86::CMOV_V2F64:
21655   case X86::CMOV_V2I64:
21656   case X86::CMOV_V4F32:
21657   case X86::CMOV_V4F64:
21658   case X86::CMOV_V4I64:
21659   case X86::CMOV_V16F32:
21660   case X86::CMOV_V8F32:
21661   case X86::CMOV_V8F64:
21662   case X86::CMOV_V8I64:
21663   case X86::CMOV_V8I1:
21664   case X86::CMOV_V16I1:
21665   case X86::CMOV_V32I1:
21666   case X86::CMOV_V64I1:
21667     return true;
21668
21669   default:
21670     return false;
21671   }
21672 }
21673
21674 MachineBasicBlock *
21675 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21676                                      MachineBasicBlock *BB) const {
21677   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21678   DebugLoc DL = MI->getDebugLoc();
21679
21680   // To "insert" a SELECT_CC instruction, we actually have to insert the
21681   // diamond control-flow pattern.  The incoming instruction knows the
21682   // destination vreg to set, the condition code register to branch on, the
21683   // true/false values to select between, and a branch opcode to use.
21684   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21685   MachineFunction::iterator It = ++BB->getIterator();
21686
21687   //  thisMBB:
21688   //  ...
21689   //   TrueVal = ...
21690   //   cmpTY ccX, r1, r2
21691   //   bCC copy1MBB
21692   //   fallthrough --> copy0MBB
21693   MachineBasicBlock *thisMBB = BB;
21694   MachineFunction *F = BB->getParent();
21695
21696   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21697   // as described above, by inserting a BB, and then making a PHI at the join
21698   // point to select the true and false operands of the CMOV in the PHI.
21699   //
21700   // The code also handles two different cases of multiple CMOV opcodes
21701   // in a row.
21702   //
21703   // Case 1:
21704   // In this case, there are multiple CMOVs in a row, all which are based on
21705   // the same condition setting (or the exact opposite condition setting).
21706   // In this case we can lower all the CMOVs using a single inserted BB, and
21707   // then make a number of PHIs at the join point to model the CMOVs. The only
21708   // trickiness here, is that in a case like:
21709   //
21710   // t2 = CMOV cond1 t1, f1
21711   // t3 = CMOV cond1 t2, f2
21712   //
21713   // when rewriting this into PHIs, we have to perform some renaming on the
21714   // temps since you cannot have a PHI operand refer to a PHI result earlier
21715   // in the same block.  The "simple" but wrong lowering would be:
21716   //
21717   // t2 = PHI t1(BB1), f1(BB2)
21718   // t3 = PHI t2(BB1), f2(BB2)
21719   //
21720   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21721   // renaming is to note that on the path through BB1, t2 is really just a
21722   // copy of t1, and do that renaming, properly generating:
21723   //
21724   // t2 = PHI t1(BB1), f1(BB2)
21725   // t3 = PHI t1(BB1), f2(BB2)
21726   //
21727   // Case 2, we lower cascaded CMOVs such as
21728   //
21729   //   (CMOV (CMOV F, T, cc1), T, cc2)
21730   //
21731   // to two successives branches.  For that, we look for another CMOV as the
21732   // following instruction.
21733   //
21734   // Without this, we would add a PHI between the two jumps, which ends up
21735   // creating a few copies all around. For instance, for
21736   //
21737   //    (sitofp (zext (fcmp une)))
21738   //
21739   // we would generate:
21740   //
21741   //         ucomiss %xmm1, %xmm0
21742   //         movss  <1.0f>, %xmm0
21743   //         movaps  %xmm0, %xmm1
21744   //         jne     .LBB5_2
21745   //         xorps   %xmm1, %xmm1
21746   // .LBB5_2:
21747   //         jp      .LBB5_4
21748   //         movaps  %xmm1, %xmm0
21749   // .LBB5_4:
21750   //         retq
21751   //
21752   // because this custom-inserter would have generated:
21753   //
21754   //   A
21755   //   | \
21756   //   |  B
21757   //   | /
21758   //   C
21759   //   | \
21760   //   |  D
21761   //   | /
21762   //   E
21763   //
21764   // A: X = ...; Y = ...
21765   // B: empty
21766   // C: Z = PHI [X, A], [Y, B]
21767   // D: empty
21768   // E: PHI [X, C], [Z, D]
21769   //
21770   // If we lower both CMOVs in a single step, we can instead generate:
21771   //
21772   //   A
21773   //   | \
21774   //   |  C
21775   //   | /|
21776   //   |/ |
21777   //   |  |
21778   //   |  D
21779   //   | /
21780   //   E
21781   //
21782   // A: X = ...; Y = ...
21783   // D: empty
21784   // E: PHI [X, A], [X, C], [Y, D]
21785   //
21786   // Which, in our sitofp/fcmp example, gives us something like:
21787   //
21788   //         ucomiss %xmm1, %xmm0
21789   //         movss  <1.0f>, %xmm0
21790   //         jne     .LBB5_4
21791   //         jp      .LBB5_4
21792   //         xorps   %xmm0, %xmm0
21793   // .LBB5_4:
21794   //         retq
21795   //
21796   MachineInstr *CascadedCMOV = nullptr;
21797   MachineInstr *LastCMOV = MI;
21798   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21799   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21800   MachineBasicBlock::iterator NextMIIt =
21801       std::next(MachineBasicBlock::iterator(MI));
21802
21803   // Check for case 1, where there are multiple CMOVs with the same condition
21804   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21805   // number of jumps the most.
21806
21807   if (isCMOVPseudo(MI)) {
21808     // See if we have a string of CMOVS with the same condition.
21809     while (NextMIIt != BB->end() &&
21810            isCMOVPseudo(NextMIIt) &&
21811            (NextMIIt->getOperand(3).getImm() == CC ||
21812             NextMIIt->getOperand(3).getImm() == OppCC)) {
21813       LastCMOV = &*NextMIIt;
21814       ++NextMIIt;
21815     }
21816   }
21817
21818   // This checks for case 2, but only do this if we didn't already find
21819   // case 1, as indicated by LastCMOV == MI.
21820   if (LastCMOV == MI &&
21821       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21822       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21823       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21824     CascadedCMOV = &*NextMIIt;
21825   }
21826
21827   MachineBasicBlock *jcc1MBB = nullptr;
21828
21829   // If we have a cascaded CMOV, we lower it to two successive branches to
21830   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21831   if (CascadedCMOV) {
21832     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21833     F->insert(It, jcc1MBB);
21834     jcc1MBB->addLiveIn(X86::EFLAGS);
21835   }
21836
21837   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21838   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21839   F->insert(It, copy0MBB);
21840   F->insert(It, sinkMBB);
21841
21842   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21843   // live into the sink and copy blocks.
21844   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21845
21846   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21847   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21848       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21849     copy0MBB->addLiveIn(X86::EFLAGS);
21850     sinkMBB->addLiveIn(X86::EFLAGS);
21851   }
21852
21853   // Transfer the remainder of BB and its successor edges to sinkMBB.
21854   sinkMBB->splice(sinkMBB->begin(), BB,
21855                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21856   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21857
21858   // Add the true and fallthrough blocks as its successors.
21859   if (CascadedCMOV) {
21860     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21861     BB->addSuccessor(jcc1MBB);
21862
21863     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21864     // jump to the sinkMBB.
21865     jcc1MBB->addSuccessor(copy0MBB);
21866     jcc1MBB->addSuccessor(sinkMBB);
21867   } else {
21868     BB->addSuccessor(copy0MBB);
21869   }
21870
21871   // The true block target of the first (or only) branch is always sinkMBB.
21872   BB->addSuccessor(sinkMBB);
21873
21874   // Create the conditional branch instruction.
21875   unsigned Opc = X86::GetCondBranchFromCond(CC);
21876   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21877
21878   if (CascadedCMOV) {
21879     unsigned Opc2 = X86::GetCondBranchFromCond(
21880         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21881     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21882   }
21883
21884   //  copy0MBB:
21885   //   %FalseValue = ...
21886   //   # fallthrough to sinkMBB
21887   copy0MBB->addSuccessor(sinkMBB);
21888
21889   //  sinkMBB:
21890   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21891   //  ...
21892   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21893   MachineBasicBlock::iterator MIItEnd =
21894     std::next(MachineBasicBlock::iterator(LastCMOV));
21895   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21896   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21897   MachineInstrBuilder MIB;
21898
21899   // As we are creating the PHIs, we have to be careful if there is more than
21900   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21901   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21902   // That also means that PHI construction must work forward from earlier to
21903   // later, and that the code must maintain a mapping from earlier PHI's
21904   // destination registers, and the registers that went into the PHI.
21905
21906   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21907     unsigned DestReg = MIIt->getOperand(0).getReg();
21908     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21909     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21910
21911     // If this CMOV we are generating is the opposite condition from
21912     // the jump we generated, then we have to swap the operands for the
21913     // PHI that is going to be generated.
21914     if (MIIt->getOperand(3).getImm() == OppCC)
21915         std::swap(Op1Reg, Op2Reg);
21916
21917     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21918       Op1Reg = RegRewriteTable[Op1Reg].first;
21919
21920     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21921       Op2Reg = RegRewriteTable[Op2Reg].second;
21922
21923     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21924                   TII->get(X86::PHI), DestReg)
21925           .addReg(Op1Reg).addMBB(copy0MBB)
21926           .addReg(Op2Reg).addMBB(thisMBB);
21927
21928     // Add this PHI to the rewrite table.
21929     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21930   }
21931
21932   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21933   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21934   if (CascadedCMOV) {
21935     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21936     // Copy the PHI result to the register defined by the second CMOV.
21937     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21938             DL, TII->get(TargetOpcode::COPY),
21939             CascadedCMOV->getOperand(0).getReg())
21940         .addReg(MI->getOperand(0).getReg());
21941     CascadedCMOV->eraseFromParent();
21942   }
21943
21944   // Now remove the CMOV(s).
21945   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21946     (MIIt++)->eraseFromParent();
21947
21948   return sinkMBB;
21949 }
21950
21951 MachineBasicBlock *
21952 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21953                                        MachineBasicBlock *BB) const {
21954   // Combine the following atomic floating-point modification pattern:
21955   //   a.store(reg OP a.load(acquire), release)
21956   // Transform them into:
21957   //   OPss (%gpr), %xmm
21958   //   movss %xmm, (%gpr)
21959   // Or sd equivalent for 64-bit operations.
21960   unsigned MOp, FOp;
21961   switch (MI->getOpcode()) {
21962   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21963   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21964   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21965   }
21966   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21967   DebugLoc DL = MI->getDebugLoc();
21968   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21969   MachineOperand MSrc = MI->getOperand(0);
21970   unsigned VSrc = MI->getOperand(5).getReg();
21971   const MachineOperand &Disp = MI->getOperand(3);
21972   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21973   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21974   if (hasDisp && MSrc.isReg())
21975     MSrc.setIsKill(false);
21976   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21977                                 .addOperand(/*Base=*/MSrc)
21978                                 .addImm(/*Scale=*/1)
21979                                 .addReg(/*Index=*/0)
21980                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21981                                 .addReg(0);
21982   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21983                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21984                           .addReg(VSrc)
21985                           .addOperand(/*Base=*/MSrc)
21986                           .addImm(/*Scale=*/1)
21987                           .addReg(/*Index=*/0)
21988                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21989                           .addReg(/*Segment=*/0);
21990   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21991   MI->eraseFromParent(); // The pseudo instruction is gone now.
21992   return BB;
21993 }
21994
21995 MachineBasicBlock *
21996 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21997                                         MachineBasicBlock *BB) const {
21998   MachineFunction *MF = BB->getParent();
21999   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22000   DebugLoc DL = MI->getDebugLoc();
22001   const BasicBlock *LLVM_BB = BB->getBasicBlock();
22002
22003   assert(MF->shouldSplitStack());
22004
22005   const bool Is64Bit = Subtarget->is64Bit();
22006   const bool IsLP64 = Subtarget->isTarget64BitLP64();
22007
22008   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
22009   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
22010
22011   // BB:
22012   //  ... [Till the alloca]
22013   // If stacklet is not large enough, jump to mallocMBB
22014   //
22015   // bumpMBB:
22016   //  Allocate by subtracting from RSP
22017   //  Jump to continueMBB
22018   //
22019   // mallocMBB:
22020   //  Allocate by call to runtime
22021   //
22022   // continueMBB:
22023   //  ...
22024   //  [rest of original BB]
22025   //
22026
22027   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22028   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22029   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22030
22031   MachineRegisterInfo &MRI = MF->getRegInfo();
22032   const TargetRegisterClass *AddrRegClass =
22033       getRegClassFor(getPointerTy(MF->getDataLayout()));
22034
22035   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22036     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22037     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
22038     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
22039     sizeVReg = MI->getOperand(1).getReg(),
22040     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
22041
22042   MachineFunction::iterator MBBIter = ++BB->getIterator();
22043
22044   MF->insert(MBBIter, bumpMBB);
22045   MF->insert(MBBIter, mallocMBB);
22046   MF->insert(MBBIter, continueMBB);
22047
22048   continueMBB->splice(continueMBB->begin(), BB,
22049                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
22050   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22051
22052   // Add code to the main basic block to check if the stack limit has been hit,
22053   // and if so, jump to mallocMBB otherwise to bumpMBB.
22054   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22055   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22056     .addReg(tmpSPVReg).addReg(sizeVReg);
22057   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22058     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22059     .addReg(SPLimitVReg);
22060   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22061
22062   // bumpMBB simply decreases the stack pointer, since we know the current
22063   // stacklet has enough space.
22064   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22065     .addReg(SPLimitVReg);
22066   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22067     .addReg(SPLimitVReg);
22068   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22069
22070   // Calls into a routine in libgcc to allocate more space from the heap.
22071   const uint32_t *RegMask =
22072       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22073   if (IsLP64) {
22074     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22075       .addReg(sizeVReg);
22076     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22077       .addExternalSymbol("__morestack_allocate_stack_space")
22078       .addRegMask(RegMask)
22079       .addReg(X86::RDI, RegState::Implicit)
22080       .addReg(X86::RAX, RegState::ImplicitDefine);
22081   } else if (Is64Bit) {
22082     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22083       .addReg(sizeVReg);
22084     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22085       .addExternalSymbol("__morestack_allocate_stack_space")
22086       .addRegMask(RegMask)
22087       .addReg(X86::EDI, RegState::Implicit)
22088       .addReg(X86::EAX, RegState::ImplicitDefine);
22089   } else {
22090     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22091       .addImm(12);
22092     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22093     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22094       .addExternalSymbol("__morestack_allocate_stack_space")
22095       .addRegMask(RegMask)
22096       .addReg(X86::EAX, RegState::ImplicitDefine);
22097   }
22098
22099   if (!Is64Bit)
22100     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22101       .addImm(16);
22102
22103   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22104     .addReg(IsLP64 ? X86::RAX : X86::EAX);
22105   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22106
22107   // Set up the CFG correctly.
22108   BB->addSuccessor(bumpMBB);
22109   BB->addSuccessor(mallocMBB);
22110   mallocMBB->addSuccessor(continueMBB);
22111   bumpMBB->addSuccessor(continueMBB);
22112
22113   // Take care of the PHI nodes.
22114   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22115           MI->getOperand(0).getReg())
22116     .addReg(mallocPtrVReg).addMBB(mallocMBB)
22117     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22118
22119   // Delete the original pseudo instruction.
22120   MI->eraseFromParent();
22121
22122   // And we're done.
22123   return continueMBB;
22124 }
22125
22126 MachineBasicBlock *
22127 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22128                                         MachineBasicBlock *BB) const {
22129   assert(!Subtarget->isTargetMachO());
22130   DebugLoc DL = MI->getDebugLoc();
22131   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22132       *BB->getParent(), *BB, MI, DL, false);
22133   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22134   MI->eraseFromParent(); // The pseudo instruction is gone now.
22135   return ResumeBB;
22136 }
22137
22138 MachineBasicBlock *
22139 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22140                                        MachineBasicBlock *BB) const {
22141   MachineFunction *MF = BB->getParent();
22142   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22143   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22144   DebugLoc DL = MI->getDebugLoc();
22145
22146   assert(!isAsynchronousEHPersonality(
22147              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22148          "SEH does not use catchret!");
22149
22150   // Only 32-bit EH needs to worry about manually restoring stack pointers.
22151   if (!Subtarget->is32Bit())
22152     return BB;
22153
22154   // C++ EH creates a new target block to hold the restore code, and wires up
22155   // the new block to the return destination with a normal JMP_4.
22156   MachineBasicBlock *RestoreMBB =
22157       MF->CreateMachineBasicBlock(BB->getBasicBlock());
22158   assert(BB->succ_size() == 1);
22159   MF->insert(std::next(BB->getIterator()), RestoreMBB);
22160   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22161   BB->addSuccessor(RestoreMBB);
22162   MI->getOperand(0).setMBB(RestoreMBB);
22163
22164   auto RestoreMBBI = RestoreMBB->begin();
22165   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22166   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22167   return BB;
22168 }
22169
22170 MachineBasicBlock *
22171 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22172                                        MachineBasicBlock *BB) const {
22173   MachineFunction *MF = BB->getParent();
22174   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22175   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22176   // Only 32-bit SEH requires special handling for catchpad.
22177   if (IsSEH && Subtarget->is32Bit()) {
22178     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22179     DebugLoc DL = MI->getDebugLoc();
22180     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22181   }
22182   MI->eraseFromParent();
22183   return BB;
22184 }
22185
22186 MachineBasicBlock *
22187 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22188                                       MachineBasicBlock *BB) const {
22189   // This is pretty easy.  We're taking the value that we received from
22190   // our load from the relocation, sticking it in either RDI (x86-64)
22191   // or EAX and doing an indirect call.  The return value will then
22192   // be in the normal return register.
22193   MachineFunction *F = BB->getParent();
22194   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22195   DebugLoc DL = MI->getDebugLoc();
22196
22197   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22198   assert(MI->getOperand(3).isGlobal() && "This should be a global");
22199
22200   // Get a register mask for the lowered call.
22201   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22202   // proper register mask.
22203   const uint32_t *RegMask =
22204       Subtarget->is64Bit() ?
22205       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22206       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22207   if (Subtarget->is64Bit()) {
22208     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22209                                       TII->get(X86::MOV64rm), X86::RDI)
22210     .addReg(X86::RIP)
22211     .addImm(0).addReg(0)
22212     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22213                       MI->getOperand(3).getTargetFlags())
22214     .addReg(0);
22215     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22216     addDirectMem(MIB, X86::RDI);
22217     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22218   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22219     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22220                                       TII->get(X86::MOV32rm), X86::EAX)
22221     .addReg(0)
22222     .addImm(0).addReg(0)
22223     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22224                       MI->getOperand(3).getTargetFlags())
22225     .addReg(0);
22226     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22227     addDirectMem(MIB, X86::EAX);
22228     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22229   } else {
22230     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22231                                       TII->get(X86::MOV32rm), X86::EAX)
22232     .addReg(TII->getGlobalBaseReg(F))
22233     .addImm(0).addReg(0)
22234     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22235                       MI->getOperand(3).getTargetFlags())
22236     .addReg(0);
22237     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22238     addDirectMem(MIB, X86::EAX);
22239     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22240   }
22241
22242   MI->eraseFromParent(); // The pseudo instruction is gone now.
22243   return BB;
22244 }
22245
22246 MachineBasicBlock *
22247 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22248                                     MachineBasicBlock *MBB) const {
22249   DebugLoc DL = MI->getDebugLoc();
22250   MachineFunction *MF = MBB->getParent();
22251   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22252   MachineRegisterInfo &MRI = MF->getRegInfo();
22253
22254   const BasicBlock *BB = MBB->getBasicBlock();
22255   MachineFunction::iterator I = ++MBB->getIterator();
22256
22257   // Memory Reference
22258   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22259   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22260
22261   unsigned DstReg;
22262   unsigned MemOpndSlot = 0;
22263
22264   unsigned CurOp = 0;
22265
22266   DstReg = MI->getOperand(CurOp++).getReg();
22267   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22268   assert(RC->hasType(MVT::i32) && "Invalid destination!");
22269   unsigned mainDstReg = MRI.createVirtualRegister(RC);
22270   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22271
22272   MemOpndSlot = CurOp;
22273
22274   MVT PVT = getPointerTy(MF->getDataLayout());
22275   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22276          "Invalid Pointer Size!");
22277
22278   // For v = setjmp(buf), we generate
22279   //
22280   // thisMBB:
22281   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22282   //  SjLjSetup restoreMBB
22283   //
22284   // mainMBB:
22285   //  v_main = 0
22286   //
22287   // sinkMBB:
22288   //  v = phi(main, restore)
22289   //
22290   // restoreMBB:
22291   //  if base pointer being used, load it from frame
22292   //  v_restore = 1
22293
22294   MachineBasicBlock *thisMBB = MBB;
22295   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22296   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22297   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22298   MF->insert(I, mainMBB);
22299   MF->insert(I, sinkMBB);
22300   MF->push_back(restoreMBB);
22301   restoreMBB->setHasAddressTaken();
22302
22303   MachineInstrBuilder MIB;
22304
22305   // Transfer the remainder of BB and its successor edges to sinkMBB.
22306   sinkMBB->splice(sinkMBB->begin(), MBB,
22307                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22308   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22309
22310   // thisMBB:
22311   unsigned PtrStoreOpc = 0;
22312   unsigned LabelReg = 0;
22313   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22314   Reloc::Model RM = MF->getTarget().getRelocationModel();
22315   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22316                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22317
22318   // Prepare IP either in reg or imm.
22319   if (!UseImmLabel) {
22320     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22321     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22322     LabelReg = MRI.createVirtualRegister(PtrRC);
22323     if (Subtarget->is64Bit()) {
22324       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22325               .addReg(X86::RIP)
22326               .addImm(0)
22327               .addReg(0)
22328               .addMBB(restoreMBB)
22329               .addReg(0);
22330     } else {
22331       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22332       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22333               .addReg(XII->getGlobalBaseReg(MF))
22334               .addImm(0)
22335               .addReg(0)
22336               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22337               .addReg(0);
22338     }
22339   } else
22340     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22341   // Store IP
22342   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22343   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22344     if (i == X86::AddrDisp)
22345       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22346     else
22347       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22348   }
22349   if (!UseImmLabel)
22350     MIB.addReg(LabelReg);
22351   else
22352     MIB.addMBB(restoreMBB);
22353   MIB.setMemRefs(MMOBegin, MMOEnd);
22354   // Setup
22355   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22356           .addMBB(restoreMBB);
22357
22358   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22359   MIB.addRegMask(RegInfo->getNoPreservedMask());
22360   thisMBB->addSuccessor(mainMBB);
22361   thisMBB->addSuccessor(restoreMBB);
22362
22363   // mainMBB:
22364   //  EAX = 0
22365   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22366   mainMBB->addSuccessor(sinkMBB);
22367
22368   // sinkMBB:
22369   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22370           TII->get(X86::PHI), DstReg)
22371     .addReg(mainDstReg).addMBB(mainMBB)
22372     .addReg(restoreDstReg).addMBB(restoreMBB);
22373
22374   // restoreMBB:
22375   if (RegInfo->hasBasePointer(*MF)) {
22376     const bool Uses64BitFramePtr =
22377         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22378     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22379     X86FI->setRestoreBasePointer(MF);
22380     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22381     unsigned BasePtr = RegInfo->getBaseRegister();
22382     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22383     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22384                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
22385       .setMIFlag(MachineInstr::FrameSetup);
22386   }
22387   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22388   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22389   restoreMBB->addSuccessor(sinkMBB);
22390
22391   MI->eraseFromParent();
22392   return sinkMBB;
22393 }
22394
22395 MachineBasicBlock *
22396 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22397                                      MachineBasicBlock *MBB) const {
22398   DebugLoc DL = MI->getDebugLoc();
22399   MachineFunction *MF = MBB->getParent();
22400   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22401   MachineRegisterInfo &MRI = MF->getRegInfo();
22402
22403   // Memory Reference
22404   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22405   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22406
22407   MVT PVT = getPointerTy(MF->getDataLayout());
22408   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22409          "Invalid Pointer Size!");
22410
22411   const TargetRegisterClass *RC =
22412     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22413   unsigned Tmp = MRI.createVirtualRegister(RC);
22414   // Since FP is only updated here but NOT referenced, it's treated as GPR.
22415   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22416   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22417   unsigned SP = RegInfo->getStackRegister();
22418
22419   MachineInstrBuilder MIB;
22420
22421   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22422   const int64_t SPOffset = 2 * PVT.getStoreSize();
22423
22424   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22425   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22426
22427   // Reload FP
22428   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22429   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22430     MIB.addOperand(MI->getOperand(i));
22431   MIB.setMemRefs(MMOBegin, MMOEnd);
22432   // Reload IP
22433   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22434   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22435     if (i == X86::AddrDisp)
22436       MIB.addDisp(MI->getOperand(i), LabelOffset);
22437     else
22438       MIB.addOperand(MI->getOperand(i));
22439   }
22440   MIB.setMemRefs(MMOBegin, MMOEnd);
22441   // Reload SP
22442   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22443   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22444     if (i == X86::AddrDisp)
22445       MIB.addDisp(MI->getOperand(i), SPOffset);
22446     else
22447       MIB.addOperand(MI->getOperand(i));
22448   }
22449   MIB.setMemRefs(MMOBegin, MMOEnd);
22450   // Jump
22451   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22452
22453   MI->eraseFromParent();
22454   return MBB;
22455 }
22456
22457 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22458 // accumulator loops. Writing back to the accumulator allows the coalescer
22459 // to remove extra copies in the loop.
22460 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
22461 MachineBasicBlock *
22462 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22463                                  MachineBasicBlock *MBB) const {
22464   MachineOperand &AddendOp = MI->getOperand(3);
22465
22466   // Bail out early if the addend isn't a register - we can't switch these.
22467   if (!AddendOp.isReg())
22468     return MBB;
22469
22470   MachineFunction &MF = *MBB->getParent();
22471   MachineRegisterInfo &MRI = MF.getRegInfo();
22472
22473   // Check whether the addend is defined by a PHI:
22474   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22475   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22476   if (!AddendDef.isPHI())
22477     return MBB;
22478
22479   // Look for the following pattern:
22480   // loop:
22481   //   %addend = phi [%entry, 0], [%loop, %result]
22482   //   ...
22483   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22484
22485   // Replace with:
22486   //   loop:
22487   //   %addend = phi [%entry, 0], [%loop, %result]
22488   //   ...
22489   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22490
22491   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22492     assert(AddendDef.getOperand(i).isReg());
22493     MachineOperand PHISrcOp = AddendDef.getOperand(i);
22494     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22495     if (&PHISrcInst == MI) {
22496       // Found a matching instruction.
22497       unsigned NewFMAOpc = 0;
22498       switch (MI->getOpcode()) {
22499         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22500         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22501         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22502         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22503         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22504         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22505         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22506         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22507         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22508         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22509         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22510         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22511         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22512         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22513         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22514         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22515         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22516         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22517         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22518         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22519
22520         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22521         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22522         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22523         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22524         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22525         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22526         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22527         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22528         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22529         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22530         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22531         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22532         default: llvm_unreachable("Unrecognized FMA variant.");
22533       }
22534
22535       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22536       MachineInstrBuilder MIB =
22537         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22538         .addOperand(MI->getOperand(0))
22539         .addOperand(MI->getOperand(3))
22540         .addOperand(MI->getOperand(2))
22541         .addOperand(MI->getOperand(1));
22542       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22543       MI->eraseFromParent();
22544     }
22545   }
22546
22547   return MBB;
22548 }
22549
22550 MachineBasicBlock *
22551 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22552                                                MachineBasicBlock *BB) const {
22553   switch (MI->getOpcode()) {
22554   default: llvm_unreachable("Unexpected instr type to insert");
22555   case X86::TAILJMPd64:
22556   case X86::TAILJMPr64:
22557   case X86::TAILJMPm64:
22558   case X86::TAILJMPd64_REX:
22559   case X86::TAILJMPr64_REX:
22560   case X86::TAILJMPm64_REX:
22561     llvm_unreachable("TAILJMP64 would not be touched here.");
22562   case X86::TCRETURNdi64:
22563   case X86::TCRETURNri64:
22564   case X86::TCRETURNmi64:
22565     return BB;
22566   case X86::WIN_ALLOCA:
22567     return EmitLoweredWinAlloca(MI, BB);
22568   case X86::CATCHRET:
22569     return EmitLoweredCatchRet(MI, BB);
22570   case X86::CATCHPAD:
22571     return EmitLoweredCatchPad(MI, BB);
22572   case X86::SEG_ALLOCA_32:
22573   case X86::SEG_ALLOCA_64:
22574     return EmitLoweredSegAlloca(MI, BB);
22575   case X86::TLSCall_32:
22576   case X86::TLSCall_64:
22577     return EmitLoweredTLSCall(MI, BB);
22578   case X86::CMOV_FR32:
22579   case X86::CMOV_FR64:
22580   case X86::CMOV_FR128:
22581   case X86::CMOV_GR8:
22582   case X86::CMOV_GR16:
22583   case X86::CMOV_GR32:
22584   case X86::CMOV_RFP32:
22585   case X86::CMOV_RFP64:
22586   case X86::CMOV_RFP80:
22587   case X86::CMOV_V2F64:
22588   case X86::CMOV_V2I64:
22589   case X86::CMOV_V4F32:
22590   case X86::CMOV_V4F64:
22591   case X86::CMOV_V4I64:
22592   case X86::CMOV_V16F32:
22593   case X86::CMOV_V8F32:
22594   case X86::CMOV_V8F64:
22595   case X86::CMOV_V8I64:
22596   case X86::CMOV_V8I1:
22597   case X86::CMOV_V16I1:
22598   case X86::CMOV_V32I1:
22599   case X86::CMOV_V64I1:
22600     return EmitLoweredSelect(MI, BB);
22601
22602   case X86::RDFLAGS32:
22603   case X86::RDFLAGS64: {
22604     DebugLoc DL = MI->getDebugLoc();
22605     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22606     unsigned PushF =
22607         MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22608     unsigned Pop =
22609         MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22610     BuildMI(*BB, MI, DL, TII->get(PushF));
22611     BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22612
22613     MI->eraseFromParent(); // The pseudo is gone now.
22614     return BB;
22615   }
22616
22617   case X86::WRFLAGS32:
22618   case X86::WRFLAGS64: {
22619     DebugLoc DL = MI->getDebugLoc();
22620     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22621     unsigned Push =
22622         MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22623     unsigned PopF =
22624         MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22625     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22626     BuildMI(*BB, MI, DL, TII->get(PopF));
22627
22628     MI->eraseFromParent(); // The pseudo is gone now.
22629     return BB;
22630   }
22631
22632   case X86::RELEASE_FADD32mr:
22633   case X86::RELEASE_FADD64mr:
22634     return EmitLoweredAtomicFP(MI, BB);
22635
22636   case X86::FP32_TO_INT16_IN_MEM:
22637   case X86::FP32_TO_INT32_IN_MEM:
22638   case X86::FP32_TO_INT64_IN_MEM:
22639   case X86::FP64_TO_INT16_IN_MEM:
22640   case X86::FP64_TO_INT32_IN_MEM:
22641   case X86::FP64_TO_INT64_IN_MEM:
22642   case X86::FP80_TO_INT16_IN_MEM:
22643   case X86::FP80_TO_INT32_IN_MEM:
22644   case X86::FP80_TO_INT64_IN_MEM: {
22645     MachineFunction *F = BB->getParent();
22646     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22647     DebugLoc DL = MI->getDebugLoc();
22648
22649     // Change the floating point control register to use "round towards zero"
22650     // mode when truncating to an integer value.
22651     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22652     addFrameReference(BuildMI(*BB, MI, DL,
22653                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22654
22655     // Load the old value of the high byte of the control word...
22656     unsigned OldCW =
22657       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22658     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22659                       CWFrameIdx);
22660
22661     // Set the high part to be round to zero...
22662     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22663       .addImm(0xC7F);
22664
22665     // Reload the modified control word now...
22666     addFrameReference(BuildMI(*BB, MI, DL,
22667                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22668
22669     // Restore the memory image of control word to original value
22670     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22671       .addReg(OldCW);
22672
22673     // Get the X86 opcode to use.
22674     unsigned Opc;
22675     switch (MI->getOpcode()) {
22676     default: llvm_unreachable("illegal opcode!");
22677     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22678     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22679     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22680     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22681     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22682     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22683     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22684     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22685     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22686     }
22687
22688     X86AddressMode AM;
22689     MachineOperand &Op = MI->getOperand(0);
22690     if (Op.isReg()) {
22691       AM.BaseType = X86AddressMode::RegBase;
22692       AM.Base.Reg = Op.getReg();
22693     } else {
22694       AM.BaseType = X86AddressMode::FrameIndexBase;
22695       AM.Base.FrameIndex = Op.getIndex();
22696     }
22697     Op = MI->getOperand(1);
22698     if (Op.isImm())
22699       AM.Scale = Op.getImm();
22700     Op = MI->getOperand(2);
22701     if (Op.isImm())
22702       AM.IndexReg = Op.getImm();
22703     Op = MI->getOperand(3);
22704     if (Op.isGlobal()) {
22705       AM.GV = Op.getGlobal();
22706     } else {
22707       AM.Disp = Op.getImm();
22708     }
22709     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22710                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22711
22712     // Reload the original control word now.
22713     addFrameReference(BuildMI(*BB, MI, DL,
22714                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22715
22716     MI->eraseFromParent();   // The pseudo instruction is gone now.
22717     return BB;
22718   }
22719     // String/text processing lowering.
22720   case X86::PCMPISTRM128REG:
22721   case X86::VPCMPISTRM128REG:
22722   case X86::PCMPISTRM128MEM:
22723   case X86::VPCMPISTRM128MEM:
22724   case X86::PCMPESTRM128REG:
22725   case X86::VPCMPESTRM128REG:
22726   case X86::PCMPESTRM128MEM:
22727   case X86::VPCMPESTRM128MEM:
22728     assert(Subtarget->hasSSE42() &&
22729            "Target must have SSE4.2 or AVX features enabled");
22730     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22731
22732   // String/text processing lowering.
22733   case X86::PCMPISTRIREG:
22734   case X86::VPCMPISTRIREG:
22735   case X86::PCMPISTRIMEM:
22736   case X86::VPCMPISTRIMEM:
22737   case X86::PCMPESTRIREG:
22738   case X86::VPCMPESTRIREG:
22739   case X86::PCMPESTRIMEM:
22740   case X86::VPCMPESTRIMEM:
22741     assert(Subtarget->hasSSE42() &&
22742            "Target must have SSE4.2 or AVX features enabled");
22743     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22744
22745   // Thread synchronization.
22746   case X86::MONITOR:
22747     return EmitMonitor(MI, BB, Subtarget);
22748   // PKU feature
22749   case X86::WRPKRU:
22750     return EmitWRPKRU(MI, BB, Subtarget);
22751   case X86::RDPKRU:
22752     return EmitRDPKRU(MI, BB, Subtarget);
22753   // xbegin
22754   case X86::XBEGIN:
22755     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22756
22757   case X86::VASTART_SAVE_XMM_REGS:
22758     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22759
22760   case X86::VAARG_64:
22761     return EmitVAARG64WithCustomInserter(MI, BB);
22762
22763   case X86::EH_SjLj_SetJmp32:
22764   case X86::EH_SjLj_SetJmp64:
22765     return emitEHSjLjSetJmp(MI, BB);
22766
22767   case X86::EH_SjLj_LongJmp32:
22768   case X86::EH_SjLj_LongJmp64:
22769     return emitEHSjLjLongJmp(MI, BB);
22770
22771   case TargetOpcode::STATEPOINT:
22772     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22773     // this point in the process.  We diverge later.
22774     return emitPatchPoint(MI, BB);
22775
22776   case TargetOpcode::STACKMAP:
22777   case TargetOpcode::PATCHPOINT:
22778     return emitPatchPoint(MI, BB);
22779
22780   case X86::VFMADDPDr213r:
22781   case X86::VFMADDPSr213r:
22782   case X86::VFMADDSDr213r:
22783   case X86::VFMADDSSr213r:
22784   case X86::VFMSUBPDr213r:
22785   case X86::VFMSUBPSr213r:
22786   case X86::VFMSUBSDr213r:
22787   case X86::VFMSUBSSr213r:
22788   case X86::VFNMADDPDr213r:
22789   case X86::VFNMADDPSr213r:
22790   case X86::VFNMADDSDr213r:
22791   case X86::VFNMADDSSr213r:
22792   case X86::VFNMSUBPDr213r:
22793   case X86::VFNMSUBPSr213r:
22794   case X86::VFNMSUBSDr213r:
22795   case X86::VFNMSUBSSr213r:
22796   case X86::VFMADDSUBPDr213r:
22797   case X86::VFMADDSUBPSr213r:
22798   case X86::VFMSUBADDPDr213r:
22799   case X86::VFMSUBADDPSr213r:
22800   case X86::VFMADDPDr213rY:
22801   case X86::VFMADDPSr213rY:
22802   case X86::VFMSUBPDr213rY:
22803   case X86::VFMSUBPSr213rY:
22804   case X86::VFNMADDPDr213rY:
22805   case X86::VFNMADDPSr213rY:
22806   case X86::VFNMSUBPDr213rY:
22807   case X86::VFNMSUBPSr213rY:
22808   case X86::VFMADDSUBPDr213rY:
22809   case X86::VFMADDSUBPSr213rY:
22810   case X86::VFMSUBADDPDr213rY:
22811   case X86::VFMSUBADDPSr213rY:
22812     return emitFMA3Instr(MI, BB);
22813   }
22814 }
22815
22816 //===----------------------------------------------------------------------===//
22817 //                           X86 Optimization Hooks
22818 //===----------------------------------------------------------------------===//
22819
22820 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22821                                                       APInt &KnownZero,
22822                                                       APInt &KnownOne,
22823                                                       const SelectionDAG &DAG,
22824                                                       unsigned Depth) const {
22825   unsigned BitWidth = KnownZero.getBitWidth();
22826   unsigned Opc = Op.getOpcode();
22827   assert((Opc >= ISD::BUILTIN_OP_END ||
22828           Opc == ISD::INTRINSIC_WO_CHAIN ||
22829           Opc == ISD::INTRINSIC_W_CHAIN ||
22830           Opc == ISD::INTRINSIC_VOID) &&
22831          "Should use MaskedValueIsZero if you don't know whether Op"
22832          " is a target node!");
22833
22834   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22835   switch (Opc) {
22836   default: break;
22837   case X86ISD::ADD:
22838   case X86ISD::SUB:
22839   case X86ISD::ADC:
22840   case X86ISD::SBB:
22841   case X86ISD::SMUL:
22842   case X86ISD::UMUL:
22843   case X86ISD::INC:
22844   case X86ISD::DEC:
22845   case X86ISD::OR:
22846   case X86ISD::XOR:
22847   case X86ISD::AND:
22848     // These nodes' second result is a boolean.
22849     if (Op.getResNo() == 0)
22850       break;
22851     // Fallthrough
22852   case X86ISD::SETCC:
22853     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22854     break;
22855   case ISD::INTRINSIC_WO_CHAIN: {
22856     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22857     unsigned NumLoBits = 0;
22858     switch (IntId) {
22859     default: break;
22860     case Intrinsic::x86_sse_movmsk_ps:
22861     case Intrinsic::x86_avx_movmsk_ps_256:
22862     case Intrinsic::x86_sse2_movmsk_pd:
22863     case Intrinsic::x86_avx_movmsk_pd_256:
22864     case Intrinsic::x86_mmx_pmovmskb:
22865     case Intrinsic::x86_sse2_pmovmskb_128:
22866     case Intrinsic::x86_avx2_pmovmskb: {
22867       // High bits of movmskp{s|d}, pmovmskb are known zero.
22868       switch (IntId) {
22869         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22870         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22871         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22872         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22873         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22874         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22875         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22876         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22877       }
22878       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22879       break;
22880     }
22881     }
22882     break;
22883   }
22884   }
22885 }
22886
22887 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22888   SDValue Op,
22889   const SelectionDAG &,
22890   unsigned Depth) const {
22891   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22892   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22893     return Op.getValueType().getScalarSizeInBits();
22894
22895   // Fallback case.
22896   return 1;
22897 }
22898
22899 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22900 /// node is a GlobalAddress + offset.
22901 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22902                                        const GlobalValue* &GA,
22903                                        int64_t &Offset) const {
22904   if (N->getOpcode() == X86ISD::Wrapper) {
22905     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22906       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22907       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22908       return true;
22909     }
22910   }
22911   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22912 }
22913
22914 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22915 /// FIXME: This could be expanded to support 512 bit vectors as well.
22916 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22917                                         TargetLowering::DAGCombinerInfo &DCI,
22918                                         const X86Subtarget* Subtarget) {
22919   SDLoc dl(N);
22920   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22921   SDValue V1 = SVOp->getOperand(0);
22922   SDValue V2 = SVOp->getOperand(1);
22923   MVT VT = SVOp->getSimpleValueType(0);
22924   unsigned NumElems = VT.getVectorNumElements();
22925
22926   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22927       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22928     //
22929     //                   0,0,0,...
22930     //                      |
22931     //    V      UNDEF    BUILD_VECTOR    UNDEF
22932     //     \      /           \           /
22933     //  CONCAT_VECTOR         CONCAT_VECTOR
22934     //         \                  /
22935     //          \                /
22936     //          RESULT: V + zero extended
22937     //
22938     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22939         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22940         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22941       return SDValue();
22942
22943     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22944       return SDValue();
22945
22946     // To match the shuffle mask, the first half of the mask should
22947     // be exactly the first vector, and all the rest a splat with the
22948     // first element of the second one.
22949     for (unsigned i = 0; i != NumElems/2; ++i)
22950       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22951           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22952         return SDValue();
22953
22954     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22955     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22956       if (Ld->hasNUsesOfValue(1, 0)) {
22957         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22958         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22959         SDValue ResNode =
22960           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22961                                   Ld->getMemoryVT(),
22962                                   Ld->getPointerInfo(),
22963                                   Ld->getAlignment(),
22964                                   false/*isVolatile*/, true/*ReadMem*/,
22965                                   false/*WriteMem*/);
22966
22967         // Make sure the newly-created LOAD is in the same position as Ld in
22968         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22969         // and update uses of Ld's output chain to use the TokenFactor.
22970         if (Ld->hasAnyUseOfValue(1)) {
22971           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22972                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22973           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22974           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22975                                  SDValue(ResNode.getNode(), 1));
22976         }
22977
22978         return DAG.getBitcast(VT, ResNode);
22979       }
22980     }
22981
22982     // Emit a zeroed vector and insert the desired subvector on its
22983     // first half.
22984     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22985     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22986     return DCI.CombineTo(N, InsV);
22987   }
22988
22989   return SDValue();
22990 }
22991
22992 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22993 /// possible.
22994 ///
22995 /// This is the leaf of the recursive combinine below. When we have found some
22996 /// chain of single-use x86 shuffle instructions and accumulated the combined
22997 /// shuffle mask represented by them, this will try to pattern match that mask
22998 /// into either a single instruction if there is a special purpose instruction
22999 /// for this operation, or into a PSHUFB instruction which is a fully general
23000 /// instruction but should only be used to replace chains over a certain depth.
23001 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
23002                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
23003                                    TargetLowering::DAGCombinerInfo &DCI,
23004                                    const X86Subtarget *Subtarget) {
23005   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
23006
23007   // Find the operand that enters the chain. Note that multiple uses are OK
23008   // here, we're not going to remove the operand we find.
23009   SDValue Input = Op.getOperand(0);
23010   while (Input.getOpcode() == ISD::BITCAST)
23011     Input = Input.getOperand(0);
23012
23013   MVT VT = Input.getSimpleValueType();
23014   MVT RootVT = Root.getSimpleValueType();
23015   SDLoc DL(Root);
23016
23017   if (Mask.size() == 1) {
23018     int Index = Mask[0];
23019     assert((Index >= 0 || Index == SM_SentinelUndef ||
23020             Index == SM_SentinelZero) &&
23021            "Invalid shuffle index found!");
23022
23023     // We may end up with an accumulated mask of size 1 as a result of
23024     // widening of shuffle operands (see function canWidenShuffleElements).
23025     // If the only shuffle index is equal to SM_SentinelZero then propagate
23026     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
23027     // mask, and therefore the entire chain of shuffles can be folded away.
23028     if (Index == SM_SentinelZero)
23029       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
23030     else
23031       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
23032                     /*AddTo*/ true);
23033     return true;
23034   }
23035
23036   // Use the float domain if the operand type is a floating point type.
23037   bool FloatDomain = VT.isFloatingPoint();
23038
23039   // For floating point shuffles, we don't have free copies in the shuffle
23040   // instructions or the ability to load as part of the instruction, so
23041   // canonicalize their shuffles to UNPCK or MOV variants.
23042   //
23043   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
23044   // vectors because it can have a load folded into it that UNPCK cannot. This
23045   // doesn't preclude something switching to the shorter encoding post-RA.
23046   //
23047   // FIXME: Should teach these routines about AVX vector widths.
23048   if (FloatDomain && VT.is128BitVector()) {
23049     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23050       bool Lo = Mask.equals({0, 0});
23051       unsigned Shuffle;
23052       MVT ShuffleVT;
23053       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23054       // is no slower than UNPCKLPD but has the option to fold the input operand
23055       // into even an unaligned memory load.
23056       if (Lo && Subtarget->hasSSE3()) {
23057         Shuffle = X86ISD::MOVDDUP;
23058         ShuffleVT = MVT::v2f64;
23059       } else {
23060         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23061         // than the UNPCK variants.
23062         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23063         ShuffleVT = MVT::v4f32;
23064       }
23065       if (Depth == 1 && Root->getOpcode() == Shuffle)
23066         return false; // Nothing to do!
23067       Op = DAG.getBitcast(ShuffleVT, Input);
23068       DCI.AddToWorklist(Op.getNode());
23069       if (Shuffle == X86ISD::MOVDDUP)
23070         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23071       else
23072         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23073       DCI.AddToWorklist(Op.getNode());
23074       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23075                     /*AddTo*/ true);
23076       return true;
23077     }
23078     if (Subtarget->hasSSE3() &&
23079         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23080       bool Lo = Mask.equals({0, 0, 2, 2});
23081       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23082       MVT ShuffleVT = MVT::v4f32;
23083       if (Depth == 1 && Root->getOpcode() == Shuffle)
23084         return false; // Nothing to do!
23085       Op = DAG.getBitcast(ShuffleVT, Input);
23086       DCI.AddToWorklist(Op.getNode());
23087       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23088       DCI.AddToWorklist(Op.getNode());
23089       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23090                     /*AddTo*/ true);
23091       return true;
23092     }
23093     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23094       bool Lo = Mask.equals({0, 0, 1, 1});
23095       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23096       MVT ShuffleVT = MVT::v4f32;
23097       if (Depth == 1 && Root->getOpcode() == Shuffle)
23098         return false; // Nothing to do!
23099       Op = DAG.getBitcast(ShuffleVT, Input);
23100       DCI.AddToWorklist(Op.getNode());
23101       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23102       DCI.AddToWorklist(Op.getNode());
23103       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23104                     /*AddTo*/ true);
23105       return true;
23106     }
23107   }
23108
23109   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23110   // variants as none of these have single-instruction variants that are
23111   // superior to the UNPCK formulation.
23112   if (!FloatDomain && VT.is128BitVector() &&
23113       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23114        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23115        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23116        Mask.equals(
23117            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23118     bool Lo = Mask[0] == 0;
23119     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23120     if (Depth == 1 && Root->getOpcode() == Shuffle)
23121       return false; // Nothing to do!
23122     MVT ShuffleVT;
23123     switch (Mask.size()) {
23124     case 8:
23125       ShuffleVT = MVT::v8i16;
23126       break;
23127     case 16:
23128       ShuffleVT = MVT::v16i8;
23129       break;
23130     default:
23131       llvm_unreachable("Impossible mask size!");
23132     };
23133     Op = DAG.getBitcast(ShuffleVT, Input);
23134     DCI.AddToWorklist(Op.getNode());
23135     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23136     DCI.AddToWorklist(Op.getNode());
23137     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23138                   /*AddTo*/ true);
23139     return true;
23140   }
23141
23142   // Don't try to re-form single instruction chains under any circumstances now
23143   // that we've done encoding canonicalization for them.
23144   if (Depth < 2)
23145     return false;
23146
23147   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23148   // can replace them with a single PSHUFB instruction profitably. Intel's
23149   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23150   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23151   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23152     SmallVector<SDValue, 16> PSHUFBMask;
23153     int NumBytes = VT.getSizeInBits() / 8;
23154     int Ratio = NumBytes / Mask.size();
23155     for (int i = 0; i < NumBytes; ++i) {
23156       if (Mask[i / Ratio] == SM_SentinelUndef) {
23157         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23158         continue;
23159       }
23160       int M = Mask[i / Ratio] != SM_SentinelZero
23161                   ? Ratio * Mask[i / Ratio] + i % Ratio
23162                   : 255;
23163       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23164     }
23165     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23166     Op = DAG.getBitcast(ByteVT, Input);
23167     DCI.AddToWorklist(Op.getNode());
23168     SDValue PSHUFBMaskOp =
23169         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23170     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23171     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23172     DCI.AddToWorklist(Op.getNode());
23173     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23174                   /*AddTo*/ true);
23175     return true;
23176   }
23177
23178   // Failed to find any combines.
23179   return false;
23180 }
23181
23182 /// \brief Fully generic combining of x86 shuffle instructions.
23183 ///
23184 /// This should be the last combine run over the x86 shuffle instructions. Once
23185 /// they have been fully optimized, this will recursively consider all chains
23186 /// of single-use shuffle instructions, build a generic model of the cumulative
23187 /// shuffle operation, and check for simpler instructions which implement this
23188 /// operation. We use this primarily for two purposes:
23189 ///
23190 /// 1) Collapse generic shuffles to specialized single instructions when
23191 ///    equivalent. In most cases, this is just an encoding size win, but
23192 ///    sometimes we will collapse multiple generic shuffles into a single
23193 ///    special-purpose shuffle.
23194 /// 2) Look for sequences of shuffle instructions with 3 or more total
23195 ///    instructions, and replace them with the slightly more expensive SSSE3
23196 ///    PSHUFB instruction if available. We do this as the last combining step
23197 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
23198 ///    a suitable short sequence of other instructions. The PHUFB will either
23199 ///    use a register or have to read from memory and so is slightly (but only
23200 ///    slightly) more expensive than the other shuffle instructions.
23201 ///
23202 /// Because this is inherently a quadratic operation (for each shuffle in
23203 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23204 /// This should never be an issue in practice as the shuffle lowering doesn't
23205 /// produce sequences of more than 8 instructions.
23206 ///
23207 /// FIXME: We will currently miss some cases where the redundant shuffling
23208 /// would simplify under the threshold for PSHUFB formation because of
23209 /// combine-ordering. To fix this, we should do the redundant instruction
23210 /// combining in this recursive walk.
23211 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23212                                           ArrayRef<int> RootMask,
23213                                           int Depth, bool HasPSHUFB,
23214                                           SelectionDAG &DAG,
23215                                           TargetLowering::DAGCombinerInfo &DCI,
23216                                           const X86Subtarget *Subtarget) {
23217   // Bound the depth of our recursive combine because this is ultimately
23218   // quadratic in nature.
23219   if (Depth > 8)
23220     return false;
23221
23222   // Directly rip through bitcasts to find the underlying operand.
23223   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23224     Op = Op.getOperand(0);
23225
23226   MVT VT = Op.getSimpleValueType();
23227   if (!VT.isVector())
23228     return false; // Bail if we hit a non-vector.
23229
23230   assert(Root.getSimpleValueType().isVector() &&
23231          "Shuffles operate on vector types!");
23232   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23233          "Can only combine shuffles of the same vector register size.");
23234
23235   if (!isTargetShuffle(Op.getOpcode()))
23236     return false;
23237   SmallVector<int, 16> OpMask;
23238   bool IsUnary;
23239   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, true, OpMask, IsUnary);
23240   // We only can combine unary shuffles which we can decode the mask for.
23241   if (!HaveMask || !IsUnary)
23242     return false;
23243
23244   assert(VT.getVectorNumElements() == OpMask.size() &&
23245          "Different mask size from vector size!");
23246   assert(((RootMask.size() > OpMask.size() &&
23247            RootMask.size() % OpMask.size() == 0) ||
23248           (OpMask.size() > RootMask.size() &&
23249            OpMask.size() % RootMask.size() == 0) ||
23250           OpMask.size() == RootMask.size()) &&
23251          "The smaller number of elements must divide the larger.");
23252   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23253   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23254   assert(((RootRatio == 1 && OpRatio == 1) ||
23255           (RootRatio == 1) != (OpRatio == 1)) &&
23256          "Must not have a ratio for both incoming and op masks!");
23257
23258   SmallVector<int, 16> Mask;
23259   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23260
23261   // Merge this shuffle operation's mask into our accumulated mask. Note that
23262   // this shuffle's mask will be the first applied to the input, followed by the
23263   // root mask to get us all the way to the root value arrangement. The reason
23264   // for this order is that we are recursing up the operation chain.
23265   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23266     int RootIdx = i / RootRatio;
23267     if (RootMask[RootIdx] < 0) {
23268       // This is a zero or undef lane, we're done.
23269       Mask.push_back(RootMask[RootIdx]);
23270       continue;
23271     }
23272
23273     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23274     int OpIdx = RootMaskedIdx / OpRatio;
23275     if (OpMask[OpIdx] < 0) {
23276       // The incoming lanes are zero or undef, it doesn't matter which ones we
23277       // are using.
23278       Mask.push_back(OpMask[OpIdx]);
23279       continue;
23280     }
23281
23282     // Ok, we have non-zero lanes, map them through.
23283     Mask.push_back(OpMask[OpIdx] * OpRatio +
23284                    RootMaskedIdx % OpRatio);
23285   }
23286
23287   // See if we can recurse into the operand to combine more things.
23288   switch (Op.getOpcode()) {
23289   case X86ISD::PSHUFB:
23290     HasPSHUFB = true;
23291   case X86ISD::PSHUFD:
23292   case X86ISD::PSHUFHW:
23293   case X86ISD::PSHUFLW:
23294     if (Op.getOperand(0).hasOneUse() &&
23295         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23296                                       HasPSHUFB, DAG, DCI, Subtarget))
23297       return true;
23298     break;
23299
23300   case X86ISD::UNPCKL:
23301   case X86ISD::UNPCKH:
23302     assert(Op.getOperand(0) == Op.getOperand(1) &&
23303            "We only combine unary shuffles!");
23304     // We can't check for single use, we have to check that this shuffle is the
23305     // only user.
23306     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23307         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23308                                       HasPSHUFB, DAG, DCI, Subtarget))
23309       return true;
23310     break;
23311   }
23312
23313   // Minor canonicalization of the accumulated shuffle mask to make it easier
23314   // to match below. All this does is detect masks with squential pairs of
23315   // elements, and shrink them to the half-width mask. It does this in a loop
23316   // so it will reduce the size of the mask to the minimal width mask which
23317   // performs an equivalent shuffle.
23318   SmallVector<int, 16> WidenedMask;
23319   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23320     Mask = std::move(WidenedMask);
23321     WidenedMask.clear();
23322   }
23323
23324   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23325                                 Subtarget);
23326 }
23327
23328 /// \brief Get the PSHUF-style mask from PSHUF node.
23329 ///
23330 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23331 /// PSHUF-style masks that can be reused with such instructions.
23332 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23333   MVT VT = N.getSimpleValueType();
23334   SmallVector<int, 4> Mask;
23335   bool IsUnary;
23336   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, false, Mask, IsUnary);
23337   (void)HaveMask;
23338   assert(HaveMask);
23339
23340   // If we have more than 128-bits, only the low 128-bits of shuffle mask
23341   // matter. Check that the upper masks are repeats and remove them.
23342   if (VT.getSizeInBits() > 128) {
23343     int LaneElts = 128 / VT.getScalarSizeInBits();
23344 #ifndef NDEBUG
23345     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23346       for (int j = 0; j < LaneElts; ++j)
23347         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23348                "Mask doesn't repeat in high 128-bit lanes!");
23349 #endif
23350     Mask.resize(LaneElts);
23351   }
23352
23353   switch (N.getOpcode()) {
23354   case X86ISD::PSHUFD:
23355     return Mask;
23356   case X86ISD::PSHUFLW:
23357     Mask.resize(4);
23358     return Mask;
23359   case X86ISD::PSHUFHW:
23360     Mask.erase(Mask.begin(), Mask.begin() + 4);
23361     for (int &M : Mask)
23362       M -= 4;
23363     return Mask;
23364   default:
23365     llvm_unreachable("No valid shuffle instruction found!");
23366   }
23367 }
23368
23369 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23370 ///
23371 /// We walk up the chain and look for a combinable shuffle, skipping over
23372 /// shuffles that we could hoist this shuffle's transformation past without
23373 /// altering anything.
23374 static SDValue
23375 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23376                              SelectionDAG &DAG,
23377                              TargetLowering::DAGCombinerInfo &DCI) {
23378   assert(N.getOpcode() == X86ISD::PSHUFD &&
23379          "Called with something other than an x86 128-bit half shuffle!");
23380   SDLoc DL(N);
23381
23382   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23383   // of the shuffles in the chain so that we can form a fresh chain to replace
23384   // this one.
23385   SmallVector<SDValue, 8> Chain;
23386   SDValue V = N.getOperand(0);
23387   for (; V.hasOneUse(); V = V.getOperand(0)) {
23388     switch (V.getOpcode()) {
23389     default:
23390       return SDValue(); // Nothing combined!
23391
23392     case ISD::BITCAST:
23393       // Skip bitcasts as we always know the type for the target specific
23394       // instructions.
23395       continue;
23396
23397     case X86ISD::PSHUFD:
23398       // Found another dword shuffle.
23399       break;
23400
23401     case X86ISD::PSHUFLW:
23402       // Check that the low words (being shuffled) are the identity in the
23403       // dword shuffle, and the high words are self-contained.
23404       if (Mask[0] != 0 || Mask[1] != 1 ||
23405           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23406         return SDValue();
23407
23408       Chain.push_back(V);
23409       continue;
23410
23411     case X86ISD::PSHUFHW:
23412       // Check that the high words (being shuffled) are the identity in the
23413       // dword shuffle, and the low words are self-contained.
23414       if (Mask[2] != 2 || Mask[3] != 3 ||
23415           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23416         return SDValue();
23417
23418       Chain.push_back(V);
23419       continue;
23420
23421     case X86ISD::UNPCKL:
23422     case X86ISD::UNPCKH:
23423       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23424       // shuffle into a preceding word shuffle.
23425       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23426           V.getSimpleValueType().getVectorElementType() != MVT::i16)
23427         return SDValue();
23428
23429       // Search for a half-shuffle which we can combine with.
23430       unsigned CombineOp =
23431           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23432       if (V.getOperand(0) != V.getOperand(1) ||
23433           !V->isOnlyUserOf(V.getOperand(0).getNode()))
23434         return SDValue();
23435       Chain.push_back(V);
23436       V = V.getOperand(0);
23437       do {
23438         switch (V.getOpcode()) {
23439         default:
23440           return SDValue(); // Nothing to combine.
23441
23442         case X86ISD::PSHUFLW:
23443         case X86ISD::PSHUFHW:
23444           if (V.getOpcode() == CombineOp)
23445             break;
23446
23447           Chain.push_back(V);
23448
23449           // Fallthrough!
23450         case ISD::BITCAST:
23451           V = V.getOperand(0);
23452           continue;
23453         }
23454         break;
23455       } while (V.hasOneUse());
23456       break;
23457     }
23458     // Break out of the loop if we break out of the switch.
23459     break;
23460   }
23461
23462   if (!V.hasOneUse())
23463     // We fell out of the loop without finding a viable combining instruction.
23464     return SDValue();
23465
23466   // Merge this node's mask and our incoming mask.
23467   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23468   for (int &M : Mask)
23469     M = VMask[M];
23470   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23471                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23472
23473   // Rebuild the chain around this new shuffle.
23474   while (!Chain.empty()) {
23475     SDValue W = Chain.pop_back_val();
23476
23477     if (V.getValueType() != W.getOperand(0).getValueType())
23478       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23479
23480     switch (W.getOpcode()) {
23481     default:
23482       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23483
23484     case X86ISD::UNPCKL:
23485     case X86ISD::UNPCKH:
23486       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23487       break;
23488
23489     case X86ISD::PSHUFD:
23490     case X86ISD::PSHUFLW:
23491     case X86ISD::PSHUFHW:
23492       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23493       break;
23494     }
23495   }
23496   if (V.getValueType() != N.getValueType())
23497     V = DAG.getBitcast(N.getValueType(), V);
23498
23499   // Return the new chain to replace N.
23500   return V;
23501 }
23502
23503 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23504 /// pshufhw.
23505 ///
23506 /// We walk up the chain, skipping shuffles of the other half and looking
23507 /// through shuffles which switch halves trying to find a shuffle of the same
23508 /// pair of dwords.
23509 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23510                                         SelectionDAG &DAG,
23511                                         TargetLowering::DAGCombinerInfo &DCI) {
23512   assert(
23513       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23514       "Called with something other than an x86 128-bit half shuffle!");
23515   SDLoc DL(N);
23516   unsigned CombineOpcode = N.getOpcode();
23517
23518   // Walk up a single-use chain looking for a combinable shuffle.
23519   SDValue V = N.getOperand(0);
23520   for (; V.hasOneUse(); V = V.getOperand(0)) {
23521     switch (V.getOpcode()) {
23522     default:
23523       return false; // Nothing combined!
23524
23525     case ISD::BITCAST:
23526       // Skip bitcasts as we always know the type for the target specific
23527       // instructions.
23528       continue;
23529
23530     case X86ISD::PSHUFLW:
23531     case X86ISD::PSHUFHW:
23532       if (V.getOpcode() == CombineOpcode)
23533         break;
23534
23535       // Other-half shuffles are no-ops.
23536       continue;
23537     }
23538     // Break out of the loop if we break out of the switch.
23539     break;
23540   }
23541
23542   if (!V.hasOneUse())
23543     // We fell out of the loop without finding a viable combining instruction.
23544     return false;
23545
23546   // Combine away the bottom node as its shuffle will be accumulated into
23547   // a preceding shuffle.
23548   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23549
23550   // Record the old value.
23551   SDValue Old = V;
23552
23553   // Merge this node's mask and our incoming mask (adjusted to account for all
23554   // the pshufd instructions encountered).
23555   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23556   for (int &M : Mask)
23557     M = VMask[M];
23558   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23559                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23560
23561   // Check that the shuffles didn't cancel each other out. If not, we need to
23562   // combine to the new one.
23563   if (Old != V)
23564     // Replace the combinable shuffle with the combined one, updating all users
23565     // so that we re-evaluate the chain here.
23566     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23567
23568   return true;
23569 }
23570
23571 /// \brief Try to combine x86 target specific shuffles.
23572 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23573                                            TargetLowering::DAGCombinerInfo &DCI,
23574                                            const X86Subtarget *Subtarget) {
23575   SDLoc DL(N);
23576   MVT VT = N.getSimpleValueType();
23577   SmallVector<int, 4> Mask;
23578
23579   switch (N.getOpcode()) {
23580   case X86ISD::PSHUFD:
23581   case X86ISD::PSHUFLW:
23582   case X86ISD::PSHUFHW:
23583     Mask = getPSHUFShuffleMask(N);
23584     assert(Mask.size() == 4);
23585     break;
23586   case X86ISD::UNPCKL: {
23587     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23588     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23589     // moves upper half elements into the lower half part. For example:
23590     //
23591     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23592     //     undef:v16i8
23593     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23594     //
23595     // will be combined to:
23596     //
23597     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23598
23599     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23600     // happen due to advanced instructions.
23601     if (!VT.is128BitVector())
23602       return SDValue();
23603
23604     auto Op0 = N.getOperand(0);
23605     auto Op1 = N.getOperand(1);
23606     if (Op0.getOpcode() == ISD::UNDEF &&
23607         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23608       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23609
23610       unsigned NumElts = VT.getVectorNumElements();
23611       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23612       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23613                 NumElts / 2);
23614
23615       auto ShufOp = Op1.getOperand(0);
23616       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23617         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23618     }
23619     return SDValue();
23620   }
23621   case X86ISD::BLENDI: {
23622     SDValue V0 = N->getOperand(0);
23623     SDValue V1 = N->getOperand(1);
23624     assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23625            "Unexpected input vector types");
23626
23627     // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23628     // operands and changing the mask to 1. This saves us a bunch of
23629     // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23630     // x86InstrInfo knows how to commute this back after instruction selection
23631     // if it would help register allocation.
23632
23633     // TODO: If optimizing for size or a processor that doesn't suffer from
23634     // partial register update stalls, this should be transformed into a MOVSD
23635     // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23636
23637     if (VT == MVT::v2f64)
23638       if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23639         if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23640           SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23641           return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23642         }
23643
23644     return SDValue();
23645   }
23646   default:
23647     return SDValue();
23648   }
23649
23650   // Nuke no-op shuffles that show up after combining.
23651   if (isNoopShuffleMask(Mask))
23652     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23653
23654   // Look for simplifications involving one or two shuffle instructions.
23655   SDValue V = N.getOperand(0);
23656   switch (N.getOpcode()) {
23657   default:
23658     break;
23659   case X86ISD::PSHUFLW:
23660   case X86ISD::PSHUFHW:
23661     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23662
23663     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23664       return SDValue(); // We combined away this shuffle, so we're done.
23665
23666     // See if this reduces to a PSHUFD which is no more expensive and can
23667     // combine with more operations. Note that it has to at least flip the
23668     // dwords as otherwise it would have been removed as a no-op.
23669     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23670       int DMask[] = {0, 1, 2, 3};
23671       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23672       DMask[DOffset + 0] = DOffset + 1;
23673       DMask[DOffset + 1] = DOffset + 0;
23674       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23675       V = DAG.getBitcast(DVT, V);
23676       DCI.AddToWorklist(V.getNode());
23677       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23678                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23679       DCI.AddToWorklist(V.getNode());
23680       return DAG.getBitcast(VT, V);
23681     }
23682
23683     // Look for shuffle patterns which can be implemented as a single unpack.
23684     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23685     // only works when we have a PSHUFD followed by two half-shuffles.
23686     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23687         (V.getOpcode() == X86ISD::PSHUFLW ||
23688          V.getOpcode() == X86ISD::PSHUFHW) &&
23689         V.getOpcode() != N.getOpcode() &&
23690         V.hasOneUse()) {
23691       SDValue D = V.getOperand(0);
23692       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23693         D = D.getOperand(0);
23694       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23695         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23696         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23697         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23698         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23699         int WordMask[8];
23700         for (int i = 0; i < 4; ++i) {
23701           WordMask[i + NOffset] = Mask[i] + NOffset;
23702           WordMask[i + VOffset] = VMask[i] + VOffset;
23703         }
23704         // Map the word mask through the DWord mask.
23705         int MappedMask[8];
23706         for (int i = 0; i < 8; ++i)
23707           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23708         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23709             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23710           // We can replace all three shuffles with an unpack.
23711           V = DAG.getBitcast(VT, D.getOperand(0));
23712           DCI.AddToWorklist(V.getNode());
23713           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23714                                                 : X86ISD::UNPCKH,
23715                              DL, VT, V, V);
23716         }
23717       }
23718     }
23719
23720     break;
23721
23722   case X86ISD::PSHUFD:
23723     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23724       return NewN;
23725
23726     break;
23727   }
23728
23729   return SDValue();
23730 }
23731
23732 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23733 ///
23734 /// We combine this directly on the abstract vector shuffle nodes so it is
23735 /// easier to generically match. We also insert dummy vector shuffle nodes for
23736 /// the operands which explicitly discard the lanes which are unused by this
23737 /// operation to try to flow through the rest of the combiner the fact that
23738 /// they're unused.
23739 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget *Subtarget,
23740                                       SelectionDAG &DAG) {
23741   SDLoc DL(N);
23742   EVT VT = N->getValueType(0);
23743   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
23744       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
23745     return SDValue();
23746
23747   // We only handle target-independent shuffles.
23748   // FIXME: It would be easy and harmless to use the target shuffle mask
23749   // extraction tool to support more.
23750   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23751     return SDValue();
23752
23753   auto *SVN = cast<ShuffleVectorSDNode>(N);
23754   SmallVector<int, 8> Mask;
23755   for (int M : SVN->getMask())
23756     Mask.push_back(M);
23757
23758   SDValue V1 = N->getOperand(0);
23759   SDValue V2 = N->getOperand(1);
23760
23761   // We require the first shuffle operand to be the FSUB node, and the second to
23762   // be the FADD node.
23763   if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23764     ShuffleVectorSDNode::commuteMask(Mask);
23765     std::swap(V1, V2);
23766   } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23767     return SDValue();
23768
23769   // If there are other uses of these operations we can't fold them.
23770   if (!V1->hasOneUse() || !V2->hasOneUse())
23771     return SDValue();
23772
23773   // Ensure that both operations have the same operands. Note that we can
23774   // commute the FADD operands.
23775   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23776   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23777       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23778     return SDValue();
23779
23780   // We're looking for blends between FADD and FSUB nodes. We insist on these
23781   // nodes being lined up in a specific expected pattern.
23782   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23783         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23784         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23785     return SDValue();
23786
23787   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23788 }
23789
23790 /// PerformShuffleCombine - Performs several different shuffle combines.
23791 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23792                                      TargetLowering::DAGCombinerInfo &DCI,
23793                                      const X86Subtarget *Subtarget) {
23794   SDLoc dl(N);
23795   SDValue N0 = N->getOperand(0);
23796   SDValue N1 = N->getOperand(1);
23797   EVT VT = N->getValueType(0);
23798
23799   // Don't create instructions with illegal types after legalize types has run.
23800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23801   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23802     return SDValue();
23803
23804   // If we have legalized the vector types, look for blends of FADD and FSUB
23805   // nodes that we can fuse into an ADDSUB node.
23806   if (TLI.isTypeLegal(VT))
23807     if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
23808       return AddSub;
23809
23810   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23811   if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23812       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23813     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23814
23815   // During Type Legalization, when promoting illegal vector types,
23816   // the backend might introduce new shuffle dag nodes and bitcasts.
23817   //
23818   // This code performs the following transformation:
23819   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23820   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23821   //
23822   // We do this only if both the bitcast and the BINOP dag nodes have
23823   // one use. Also, perform this transformation only if the new binary
23824   // operation is legal. This is to avoid introducing dag nodes that
23825   // potentially need to be further expanded (or custom lowered) into a
23826   // less optimal sequence of dag nodes.
23827   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23828       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23829       N0.getOpcode() == ISD::BITCAST) {
23830     SDValue BC0 = N0.getOperand(0);
23831     EVT SVT = BC0.getValueType();
23832     unsigned Opcode = BC0.getOpcode();
23833     unsigned NumElts = VT.getVectorNumElements();
23834
23835     if (BC0.hasOneUse() && SVT.isVector() &&
23836         SVT.getVectorNumElements() * 2 == NumElts &&
23837         TLI.isOperationLegal(Opcode, VT)) {
23838       bool CanFold = false;
23839       switch (Opcode) {
23840       default : break;
23841       case ISD::ADD :
23842       case ISD::FADD :
23843       case ISD::SUB :
23844       case ISD::FSUB :
23845       case ISD::MUL :
23846       case ISD::FMUL :
23847         CanFold = true;
23848       }
23849
23850       unsigned SVTNumElts = SVT.getVectorNumElements();
23851       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23852       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23853         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23854       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23855         CanFold = SVOp->getMaskElt(i) < 0;
23856
23857       if (CanFold) {
23858         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23859         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23860         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23861         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23862       }
23863     }
23864   }
23865
23866   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23867   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23868   // consecutive, non-overlapping, and in the right order.
23869   SmallVector<SDValue, 16> Elts;
23870   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23871     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23872
23873   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23874     return LD;
23875
23876   if (isTargetShuffle(N->getOpcode())) {
23877     SDValue Shuffle =
23878         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23879     if (Shuffle.getNode())
23880       return Shuffle;
23881
23882     // Try recursively combining arbitrary sequences of x86 shuffle
23883     // instructions into higher-order shuffles. We do this after combining
23884     // specific PSHUF instruction sequences into their minimal form so that we
23885     // can evaluate how many specialized shuffle instructions are involved in
23886     // a particular chain.
23887     SmallVector<int, 1> NonceMask; // Just a placeholder.
23888     NonceMask.push_back(0);
23889     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23890                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23891                                       DCI, Subtarget))
23892       return SDValue(); // This routine will use CombineTo to replace N.
23893   }
23894
23895   return SDValue();
23896 }
23897
23898 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23899 /// specific shuffle of a load can be folded into a single element load.
23900 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23901 /// shuffles have been custom lowered so we need to handle those here.
23902 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23903                                          TargetLowering::DAGCombinerInfo &DCI) {
23904   if (DCI.isBeforeLegalizeOps())
23905     return SDValue();
23906
23907   SDValue InVec = N->getOperand(0);
23908   SDValue EltNo = N->getOperand(1);
23909   EVT EltVT = N->getValueType(0);
23910
23911   if (!isa<ConstantSDNode>(EltNo))
23912     return SDValue();
23913
23914   EVT OriginalVT = InVec.getValueType();
23915
23916   if (InVec.getOpcode() == ISD::BITCAST) {
23917     // Don't duplicate a load with other uses.
23918     if (!InVec.hasOneUse())
23919       return SDValue();
23920     EVT BCVT = InVec.getOperand(0).getValueType();
23921     if (!BCVT.isVector() ||
23922         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23923       return SDValue();
23924     InVec = InVec.getOperand(0);
23925   }
23926
23927   EVT CurrentVT = InVec.getValueType();
23928
23929   if (!isTargetShuffle(InVec.getOpcode()))
23930     return SDValue();
23931
23932   // Don't duplicate a load with other uses.
23933   if (!InVec.hasOneUse())
23934     return SDValue();
23935
23936   SmallVector<int, 16> ShuffleMask;
23937   bool UnaryShuffle;
23938   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
23939                             ShuffleMask, UnaryShuffle))
23940     return SDValue();
23941
23942   // Select the input vector, guarding against out of range extract vector.
23943   unsigned NumElems = CurrentVT.getVectorNumElements();
23944   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23945   int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
23946
23947   if (Idx == SM_SentinelZero)
23948     return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
23949                              : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
23950   if (Idx == SM_SentinelUndef)
23951     return DAG.getUNDEF(EltVT);
23952
23953   assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
23954   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23955                                          : InVec.getOperand(1);
23956
23957   // If inputs to shuffle are the same for both ops, then allow 2 uses
23958   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23959                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23960
23961   if (LdNode.getOpcode() == ISD::BITCAST) {
23962     // Don't duplicate a load with other uses.
23963     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23964       return SDValue();
23965
23966     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23967     LdNode = LdNode.getOperand(0);
23968   }
23969
23970   if (!ISD::isNormalLoad(LdNode.getNode()))
23971     return SDValue();
23972
23973   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23974
23975   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23976     return SDValue();
23977
23978   // If there's a bitcast before the shuffle, check if the load type and
23979   // alignment is valid.
23980   unsigned Align = LN0->getAlignment();
23981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23982   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23983       EltVT.getTypeForEVT(*DAG.getContext()));
23984
23985   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23986     return SDValue();
23987
23988   // All checks match so transform back to vector_shuffle so that DAG combiner
23989   // can finish the job
23990   SDLoc dl(N);
23991
23992   // Create shuffle node taking into account the case that its a unary shuffle
23993   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23994                                    : InVec.getOperand(1);
23995   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23996                                  InVec.getOperand(0), Shuffle,
23997                                  &ShuffleMask[0]);
23998   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23999   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
24000                      EltNo);
24001 }
24002
24003 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
24004                                      const X86Subtarget *Subtarget) {
24005   SDValue N0 = N->getOperand(0);
24006   EVT VT = N->getValueType(0);
24007
24008   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
24009   // special and don't usually play with other vector types, it's better to
24010   // handle them early to be sure we emit efficient code by avoiding
24011   // store-load conversions.
24012   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
24013       N0.getValueType() == MVT::v2i32 &&
24014       isNullConstant(N0.getOperand(1))) {
24015     SDValue N00 = N0->getOperand(0);
24016     if (N00.getValueType() == MVT::i32)
24017       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
24018   }
24019
24020   // Convert a bitcasted integer logic operation that has one bitcasted
24021   // floating-point operand and one constant operand into a floating-point
24022   // logic operation. This may create a load of the constant, but that is
24023   // cheaper than materializing the constant in an integer register and
24024   // transferring it to an SSE register or transferring the SSE operand to
24025   // integer register and back.
24026   unsigned FPOpcode;
24027   switch (N0.getOpcode()) {
24028     case ISD::AND: FPOpcode = X86ISD::FAND; break;
24029     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
24030     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
24031     default: return SDValue();
24032   }
24033   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
24034        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
24035       isa<ConstantSDNode>(N0.getOperand(1)) &&
24036       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
24037       N0.getOperand(0).getOperand(0).getValueType() == VT) {
24038     SDValue N000 = N0.getOperand(0).getOperand(0);
24039     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
24040     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
24041   }
24042
24043   return SDValue();
24044 }
24045
24046 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
24047 /// generation and convert it from being a bunch of shuffles and extracts
24048 /// into a somewhat faster sequence. For i686, the best sequence is apparently
24049 /// storing the value and loading scalars back, while for x64 we should
24050 /// use 64-bit extracts and shifts.
24051 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
24052                                          TargetLowering::DAGCombinerInfo &DCI) {
24053   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
24054     return NewOp;
24055
24056   SDValue InputVector = N->getOperand(0);
24057   SDLoc dl(InputVector);
24058   // Detect mmx to i32 conversion through a v2i32 elt extract.
24059   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24060       N->getValueType(0) == MVT::i32 &&
24061       InputVector.getValueType() == MVT::v2i32) {
24062
24063     // The bitcast source is a direct mmx result.
24064     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24065     if (MMXSrc.getValueType() == MVT::x86mmx)
24066       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24067                          N->getValueType(0),
24068                          InputVector.getNode()->getOperand(0));
24069
24070     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24071     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24072         MMXSrc.getValueType() == MVT::i64) {
24073       SDValue MMXSrcOp = MMXSrc.getOperand(0);
24074       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24075           MMXSrcOp.getValueType() == MVT::v1i64 &&
24076           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24077         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24078                            N->getValueType(0), MMXSrcOp.getOperand(0));
24079     }
24080   }
24081
24082   EVT VT = N->getValueType(0);
24083
24084   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24085       InputVector.getOpcode() == ISD::BITCAST &&
24086       isa<ConstantSDNode>(InputVector.getOperand(0))) {
24087     uint64_t ExtractedElt =
24088         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24089     uint64_t InputValue =
24090         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24091     uint64_t Res = (InputValue >> ExtractedElt) & 1;
24092     return DAG.getConstant(Res, dl, MVT::i1);
24093   }
24094   // Only operate on vectors of 4 elements, where the alternative shuffling
24095   // gets to be more expensive.
24096   if (InputVector.getValueType() != MVT::v4i32)
24097     return SDValue();
24098
24099   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24100   // single use which is a sign-extend or zero-extend, and all elements are
24101   // used.
24102   SmallVector<SDNode *, 4> Uses;
24103   unsigned ExtractedElements = 0;
24104   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24105        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24106     if (UI.getUse().getResNo() != InputVector.getResNo())
24107       return SDValue();
24108
24109     SDNode *Extract = *UI;
24110     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24111       return SDValue();
24112
24113     if (Extract->getValueType(0) != MVT::i32)
24114       return SDValue();
24115     if (!Extract->hasOneUse())
24116       return SDValue();
24117     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24118         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24119       return SDValue();
24120     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24121       return SDValue();
24122
24123     // Record which element was extracted.
24124     ExtractedElements |=
24125       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24126
24127     Uses.push_back(Extract);
24128   }
24129
24130   // If not all the elements were used, this may not be worthwhile.
24131   if (ExtractedElements != 15)
24132     return SDValue();
24133
24134   // Ok, we've now decided to do the transformation.
24135   // If 64-bit shifts are legal, use the extract-shift sequence,
24136   // otherwise bounce the vector off the cache.
24137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24138   SDValue Vals[4];
24139
24140   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24141     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24142     auto &DL = DAG.getDataLayout();
24143     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24144     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24145       DAG.getConstant(0, dl, VecIdxTy));
24146     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24147       DAG.getConstant(1, dl, VecIdxTy));
24148
24149     SDValue ShAmt = DAG.getConstant(
24150         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24151     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24152     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24153       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24154     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24155     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24156       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24157   } else {
24158     // Store the value to a temporary stack slot.
24159     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24160     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24161       MachinePointerInfo(), false, false, 0);
24162
24163     EVT ElementType = InputVector.getValueType().getVectorElementType();
24164     unsigned EltSize = ElementType.getSizeInBits() / 8;
24165
24166     // Replace each use (extract) with a load of the appropriate element.
24167     for (unsigned i = 0; i < 4; ++i) {
24168       uint64_t Offset = EltSize * i;
24169       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24170       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24171
24172       SDValue ScalarAddr =
24173           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24174
24175       // Load the scalar.
24176       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24177                             ScalarAddr, MachinePointerInfo(),
24178                             false, false, false, 0);
24179
24180     }
24181   }
24182
24183   // Replace the extracts
24184   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24185     UE = Uses.end(); UI != UE; ++UI) {
24186     SDNode *Extract = *UI;
24187
24188     SDValue Idx = Extract->getOperand(1);
24189     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24190     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24191   }
24192
24193   // The replacement was made in place; don't return anything.
24194   return SDValue();
24195 }
24196
24197 static SDValue
24198 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24199                                       const X86Subtarget *Subtarget) {
24200   SDLoc dl(N);
24201   SDValue Cond = N->getOperand(0);
24202   SDValue LHS = N->getOperand(1);
24203   SDValue RHS = N->getOperand(2);
24204
24205   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24206     SDValue CondSrc = Cond->getOperand(0);
24207     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24208       Cond = CondSrc->getOperand(0);
24209   }
24210
24211   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24212     return SDValue();
24213
24214   // A vselect where all conditions and data are constants can be optimized into
24215   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24216   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24217       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24218     return SDValue();
24219
24220   unsigned MaskValue = 0;
24221   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24222     return SDValue();
24223
24224   MVT VT = N->getSimpleValueType(0);
24225   unsigned NumElems = VT.getVectorNumElements();
24226   SmallVector<int, 8> ShuffleMask(NumElems, -1);
24227   for (unsigned i = 0; i < NumElems; ++i) {
24228     // Be sure we emit undef where we can.
24229     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24230       ShuffleMask[i] = -1;
24231     else
24232       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24233   }
24234
24235   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24236   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24237     return SDValue();
24238   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24239 }
24240
24241 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24242 /// nodes.
24243 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24244                                     TargetLowering::DAGCombinerInfo &DCI,
24245                                     const X86Subtarget *Subtarget) {
24246   SDLoc DL(N);
24247   SDValue Cond = N->getOperand(0);
24248   // Get the LHS/RHS of the select.
24249   SDValue LHS = N->getOperand(1);
24250   SDValue RHS = N->getOperand(2);
24251   EVT VT = LHS.getValueType();
24252   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24253
24254   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24255   // instructions match the semantics of the common C idiom x<y?x:y but not
24256   // x<=y?x:y, because of how they handle negative zero (which can be
24257   // ignored in unsafe-math mode).
24258   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24259   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24260       VT != MVT::f80 && VT != MVT::f128 &&
24261       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24262       (Subtarget->hasSSE2() ||
24263        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24264     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24265
24266     unsigned Opcode = 0;
24267     // Check for x CC y ? x : y.
24268     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24269         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24270       switch (CC) {
24271       default: break;
24272       case ISD::SETULT:
24273         // Converting this to a min would handle NaNs incorrectly, and swapping
24274         // the operands would cause it to handle comparisons between positive
24275         // and negative zero incorrectly.
24276         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24277           if (!DAG.getTarget().Options.UnsafeFPMath &&
24278               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24279             break;
24280           std::swap(LHS, RHS);
24281         }
24282         Opcode = X86ISD::FMIN;
24283         break;
24284       case ISD::SETOLE:
24285         // Converting this to a min would handle comparisons between positive
24286         // and negative zero incorrectly.
24287         if (!DAG.getTarget().Options.UnsafeFPMath &&
24288             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24289           break;
24290         Opcode = X86ISD::FMIN;
24291         break;
24292       case ISD::SETULE:
24293         // Converting this to a min would handle both negative zeros and NaNs
24294         // incorrectly, but we can swap the operands to fix both.
24295         std::swap(LHS, RHS);
24296       case ISD::SETOLT:
24297       case ISD::SETLT:
24298       case ISD::SETLE:
24299         Opcode = X86ISD::FMIN;
24300         break;
24301
24302       case ISD::SETOGE:
24303         // Converting this to a max would handle comparisons between positive
24304         // and negative zero incorrectly.
24305         if (!DAG.getTarget().Options.UnsafeFPMath &&
24306             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24307           break;
24308         Opcode = X86ISD::FMAX;
24309         break;
24310       case ISD::SETUGT:
24311         // Converting this to a max would handle NaNs incorrectly, and swapping
24312         // the operands would cause it to handle comparisons between positive
24313         // and negative zero incorrectly.
24314         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24315           if (!DAG.getTarget().Options.UnsafeFPMath &&
24316               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24317             break;
24318           std::swap(LHS, RHS);
24319         }
24320         Opcode = X86ISD::FMAX;
24321         break;
24322       case ISD::SETUGE:
24323         // Converting this to a max would handle both negative zeros and NaNs
24324         // incorrectly, but we can swap the operands to fix both.
24325         std::swap(LHS, RHS);
24326       case ISD::SETOGT:
24327       case ISD::SETGT:
24328       case ISD::SETGE:
24329         Opcode = X86ISD::FMAX;
24330         break;
24331       }
24332     // Check for x CC y ? y : x -- a min/max with reversed arms.
24333     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24334                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24335       switch (CC) {
24336       default: break;
24337       case ISD::SETOGE:
24338         // Converting this to a min would handle comparisons between positive
24339         // and negative zero incorrectly, and swapping the operands would
24340         // cause it to handle NaNs incorrectly.
24341         if (!DAG.getTarget().Options.UnsafeFPMath &&
24342             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24343           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24344             break;
24345           std::swap(LHS, RHS);
24346         }
24347         Opcode = X86ISD::FMIN;
24348         break;
24349       case ISD::SETUGT:
24350         // Converting this to a min would handle NaNs incorrectly.
24351         if (!DAG.getTarget().Options.UnsafeFPMath &&
24352             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24353           break;
24354         Opcode = X86ISD::FMIN;
24355         break;
24356       case ISD::SETUGE:
24357         // Converting this to a min would handle both negative zeros and NaNs
24358         // incorrectly, but we can swap the operands to fix both.
24359         std::swap(LHS, RHS);
24360       case ISD::SETOGT:
24361       case ISD::SETGT:
24362       case ISD::SETGE:
24363         Opcode = X86ISD::FMIN;
24364         break;
24365
24366       case ISD::SETULT:
24367         // Converting this to a max would handle NaNs incorrectly.
24368         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24369           break;
24370         Opcode = X86ISD::FMAX;
24371         break;
24372       case ISD::SETOLE:
24373         // Converting this to a max would handle comparisons between positive
24374         // and negative zero incorrectly, and swapping the operands would
24375         // cause it to handle NaNs incorrectly.
24376         if (!DAG.getTarget().Options.UnsafeFPMath &&
24377             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24378           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24379             break;
24380           std::swap(LHS, RHS);
24381         }
24382         Opcode = X86ISD::FMAX;
24383         break;
24384       case ISD::SETULE:
24385         // Converting this to a max would handle both negative zeros and NaNs
24386         // incorrectly, but we can swap the operands to fix both.
24387         std::swap(LHS, RHS);
24388       case ISD::SETOLT:
24389       case ISD::SETLT:
24390       case ISD::SETLE:
24391         Opcode = X86ISD::FMAX;
24392         break;
24393       }
24394     }
24395
24396     if (Opcode)
24397       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24398   }
24399
24400   EVT CondVT = Cond.getValueType();
24401   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24402       CondVT.getVectorElementType() == MVT::i1) {
24403     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24404     // lowering on KNL. In this case we convert it to
24405     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24406     // The same situation for all 128 and 256-bit vectors of i8 and i16.
24407     // Since SKX these selects have a proper lowering.
24408     EVT OpVT = LHS.getValueType();
24409     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24410         (OpVT.getVectorElementType() == MVT::i8 ||
24411          OpVT.getVectorElementType() == MVT::i16) &&
24412         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24413       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24414       DCI.AddToWorklist(Cond.getNode());
24415       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24416     }
24417   }
24418   // If this is a select between two integer constants, try to do some
24419   // optimizations.
24420   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24421     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24422       // Don't do this for crazy integer types.
24423       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24424         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24425         // so that TrueC (the true value) is larger than FalseC.
24426         bool NeedsCondInvert = false;
24427
24428         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24429             // Efficiently invertible.
24430             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
24431              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
24432               isa<ConstantSDNode>(Cond.getOperand(1))))) {
24433           NeedsCondInvert = true;
24434           std::swap(TrueC, FalseC);
24435         }
24436
24437         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
24438         if (FalseC->getAPIntValue() == 0 &&
24439             TrueC->getAPIntValue().isPowerOf2()) {
24440           if (NeedsCondInvert) // Invert the condition if needed.
24441             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24442                                DAG.getConstant(1, DL, Cond.getValueType()));
24443
24444           // Zero extend the condition if needed.
24445           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24446
24447           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24448           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24449                              DAG.getConstant(ShAmt, DL, MVT::i8));
24450         }
24451
24452         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24453         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24454           if (NeedsCondInvert) // Invert the condition if needed.
24455             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24456                                DAG.getConstant(1, DL, Cond.getValueType()));
24457
24458           // Zero extend the condition if needed.
24459           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24460                              FalseC->getValueType(0), Cond);
24461           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24462                              SDValue(FalseC, 0));
24463         }
24464
24465         // Optimize cases that will turn into an LEA instruction.  This requires
24466         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24467         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24468           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24469           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24470
24471           bool isFastMultiplier = false;
24472           if (Diff < 10) {
24473             switch ((unsigned char)Diff) {
24474               default: break;
24475               case 1:  // result = add base, cond
24476               case 2:  // result = lea base(    , cond*2)
24477               case 3:  // result = lea base(cond, cond*2)
24478               case 4:  // result = lea base(    , cond*4)
24479               case 5:  // result = lea base(cond, cond*4)
24480               case 8:  // result = lea base(    , cond*8)
24481               case 9:  // result = lea base(cond, cond*8)
24482                 isFastMultiplier = true;
24483                 break;
24484             }
24485           }
24486
24487           if (isFastMultiplier) {
24488             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24489             if (NeedsCondInvert) // Invert the condition if needed.
24490               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24491                                  DAG.getConstant(1, DL, Cond.getValueType()));
24492
24493             // Zero extend the condition if needed.
24494             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24495                                Cond);
24496             // Scale the condition by the difference.
24497             if (Diff != 1)
24498               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24499                                  DAG.getConstant(Diff, DL,
24500                                                  Cond.getValueType()));
24501
24502             // Add the base if non-zero.
24503             if (FalseC->getAPIntValue() != 0)
24504               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24505                                  SDValue(FalseC, 0));
24506             return Cond;
24507           }
24508         }
24509       }
24510   }
24511
24512   // Canonicalize max and min:
24513   // (x > y) ? x : y -> (x >= y) ? x : y
24514   // (x < y) ? x : y -> (x <= y) ? x : y
24515   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24516   // the need for an extra compare
24517   // against zero. e.g.
24518   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24519   // subl   %esi, %edi
24520   // testl  %edi, %edi
24521   // movl   $0, %eax
24522   // cmovgl %edi, %eax
24523   // =>
24524   // xorl   %eax, %eax
24525   // subl   %esi, $edi
24526   // cmovsl %eax, %edi
24527   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24528       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24529       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24530     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24531     switch (CC) {
24532     default: break;
24533     case ISD::SETLT:
24534     case ISD::SETGT: {
24535       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24536       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24537                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
24538       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24539     }
24540     }
24541   }
24542
24543   // Early exit check
24544   if (!TLI.isTypeLegal(VT))
24545     return SDValue();
24546
24547   // Match VSELECTs into subs with unsigned saturation.
24548   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24549       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24550       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24551        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24552     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24553
24554     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24555     // left side invert the predicate to simplify logic below.
24556     SDValue Other;
24557     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24558       Other = RHS;
24559       CC = ISD::getSetCCInverse(CC, true);
24560     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24561       Other = LHS;
24562     }
24563
24564     if (Other.getNode() && Other->getNumOperands() == 2 &&
24565         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24566       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24567       SDValue CondRHS = Cond->getOperand(1);
24568
24569       // Look for a general sub with unsigned saturation first.
24570       // x >= y ? x-y : 0 --> subus x, y
24571       // x >  y ? x-y : 0 --> subus x, y
24572       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24573           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24574         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24575
24576       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24577         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24578           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24579             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24580               // If the RHS is a constant we have to reverse the const
24581               // canonicalization.
24582               // x > C-1 ? x+-C : 0 --> subus x, C
24583               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24584                   CondRHSConst->getAPIntValue() ==
24585                       (-OpRHSConst->getAPIntValue() - 1))
24586                 return DAG.getNode(
24587                     X86ISD::SUBUS, DL, VT, OpLHS,
24588                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24589
24590           // Another special case: If C was a sign bit, the sub has been
24591           // canonicalized into a xor.
24592           // FIXME: Would it be better to use computeKnownBits to determine
24593           //        whether it's safe to decanonicalize the xor?
24594           // x s< 0 ? x^C : 0 --> subus x, C
24595           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24596               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24597               OpRHSConst->getAPIntValue().isSignBit())
24598             // Note that we have to rebuild the RHS constant here to ensure we
24599             // don't rely on particular values of undef lanes.
24600             return DAG.getNode(
24601                 X86ISD::SUBUS, DL, VT, OpLHS,
24602                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24603         }
24604     }
24605   }
24606
24607   // Simplify vector selection if condition value type matches vselect
24608   // operand type
24609   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24610     assert(Cond.getValueType().isVector() &&
24611            "vector select expects a vector selector!");
24612
24613     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24614     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24615
24616     // Try invert the condition if true value is not all 1s and false value
24617     // is not all 0s.
24618     if (!TValIsAllOnes && !FValIsAllZeros &&
24619         // Check if the selector will be produced by CMPP*/PCMP*
24620         Cond.getOpcode() == ISD::SETCC &&
24621         // Check if SETCC has already been promoted
24622         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24623             CondVT) {
24624       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24625       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24626
24627       if (TValIsAllZeros || FValIsAllOnes) {
24628         SDValue CC = Cond.getOperand(2);
24629         ISD::CondCode NewCC =
24630           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24631                                Cond.getOperand(0).getValueType().isInteger());
24632         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24633         std::swap(LHS, RHS);
24634         TValIsAllOnes = FValIsAllOnes;
24635         FValIsAllZeros = TValIsAllZeros;
24636       }
24637     }
24638
24639     if (TValIsAllOnes || FValIsAllZeros) {
24640       SDValue Ret;
24641
24642       if (TValIsAllOnes && FValIsAllZeros)
24643         Ret = Cond;
24644       else if (TValIsAllOnes)
24645         Ret =
24646             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24647       else if (FValIsAllZeros)
24648         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24649                           DAG.getBitcast(CondVT, LHS));
24650
24651       return DAG.getBitcast(VT, Ret);
24652     }
24653   }
24654
24655   // We should generate an X86ISD::BLENDI from a vselect if its argument
24656   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24657   // constants. This specific pattern gets generated when we split a
24658   // selector for a 512 bit vector in a machine without AVX512 (but with
24659   // 256-bit vectors), during legalization:
24660   //
24661   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24662   //
24663   // Iff we find this pattern and the build_vectors are built from
24664   // constants, we translate the vselect into a shuffle_vector that we
24665   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24666   if ((N->getOpcode() == ISD::VSELECT ||
24667        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24668       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24669     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24670     if (Shuffle.getNode())
24671       return Shuffle;
24672   }
24673
24674   // If this is a *dynamic* select (non-constant condition) and we can match
24675   // this node with one of the variable blend instructions, restructure the
24676   // condition so that the blends can use the high bit of each element and use
24677   // SimplifyDemandedBits to simplify the condition operand.
24678   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24679       !DCI.isBeforeLegalize() &&
24680       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24681     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24682
24683     // Don't optimize vector selects that map to mask-registers.
24684     if (BitWidth == 1)
24685       return SDValue();
24686
24687     // We can only handle the cases where VSELECT is directly legal on the
24688     // subtarget. We custom lower VSELECT nodes with constant conditions and
24689     // this makes it hard to see whether a dynamic VSELECT will correctly
24690     // lower, so we both check the operation's status and explicitly handle the
24691     // cases where a *dynamic* blend will fail even though a constant-condition
24692     // blend could be custom lowered.
24693     // FIXME: We should find a better way to handle this class of problems.
24694     // Potentially, we should combine constant-condition vselect nodes
24695     // pre-legalization into shuffles and not mark as many types as custom
24696     // lowered.
24697     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24698       return SDValue();
24699     // FIXME: We don't support i16-element blends currently. We could and
24700     // should support them by making *all* the bits in the condition be set
24701     // rather than just the high bit and using an i8-element blend.
24702     if (VT.getVectorElementType() == MVT::i16)
24703       return SDValue();
24704     // Dynamic blending was only available from SSE4.1 onward.
24705     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24706       return SDValue();
24707     // Byte blends are only available in AVX2
24708     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24709       return SDValue();
24710
24711     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24712     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24713
24714     APInt KnownZero, KnownOne;
24715     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24716                                           DCI.isBeforeLegalizeOps());
24717     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24718         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24719                                  TLO)) {
24720       // If we changed the computation somewhere in the DAG, this change
24721       // will affect all users of Cond.
24722       // Make sure it is fine and update all the nodes so that we do not
24723       // use the generic VSELECT anymore. Otherwise, we may perform
24724       // wrong optimizations as we messed up with the actual expectation
24725       // for the vector boolean values.
24726       if (Cond != TLO.Old) {
24727         // Check all uses of that condition operand to check whether it will be
24728         // consumed by non-BLEND instructions, which may depend on all bits are
24729         // set properly.
24730         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24731              I != E; ++I)
24732           if (I->getOpcode() != ISD::VSELECT)
24733             // TODO: Add other opcodes eventually lowered into BLEND.
24734             return SDValue();
24735
24736         // Update all the users of the condition, before committing the change,
24737         // so that the VSELECT optimizations that expect the correct vector
24738         // boolean value will not be triggered.
24739         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24740              I != E; ++I)
24741           DAG.ReplaceAllUsesOfValueWith(
24742               SDValue(*I, 0),
24743               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24744                           Cond, I->getOperand(1), I->getOperand(2)));
24745         DCI.CommitTargetLoweringOpt(TLO);
24746         return SDValue();
24747       }
24748       // At this point, only Cond is changed. Change the condition
24749       // just for N to keep the opportunity to optimize all other
24750       // users their own way.
24751       DAG.ReplaceAllUsesOfValueWith(
24752           SDValue(N, 0),
24753           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24754                       TLO.New, N->getOperand(1), N->getOperand(2)));
24755       return SDValue();
24756     }
24757   }
24758
24759   return SDValue();
24760 }
24761
24762 // Check whether a boolean test is testing a boolean value generated by
24763 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24764 // code.
24765 //
24766 // Simplify the following patterns:
24767 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24768 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24769 // to (Op EFLAGS Cond)
24770 //
24771 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24772 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24773 // to (Op EFLAGS !Cond)
24774 //
24775 // where Op could be BRCOND or CMOV.
24776 //
24777 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24778   // Quit if not CMP and SUB with its value result used.
24779   if (Cmp.getOpcode() != X86ISD::CMP &&
24780       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24781       return SDValue();
24782
24783   // Quit if not used as a boolean value.
24784   if (CC != X86::COND_E && CC != X86::COND_NE)
24785     return SDValue();
24786
24787   // Check CMP operands. One of them should be 0 or 1 and the other should be
24788   // an SetCC or extended from it.
24789   SDValue Op1 = Cmp.getOperand(0);
24790   SDValue Op2 = Cmp.getOperand(1);
24791
24792   SDValue SetCC;
24793   const ConstantSDNode* C = nullptr;
24794   bool needOppositeCond = (CC == X86::COND_E);
24795   bool checkAgainstTrue = false; // Is it a comparison against 1?
24796
24797   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24798     SetCC = Op2;
24799   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24800     SetCC = Op1;
24801   else // Quit if all operands are not constants.
24802     return SDValue();
24803
24804   if (C->getZExtValue() == 1) {
24805     needOppositeCond = !needOppositeCond;
24806     checkAgainstTrue = true;
24807   } else if (C->getZExtValue() != 0)
24808     // Quit if the constant is neither 0 or 1.
24809     return SDValue();
24810
24811   bool truncatedToBoolWithAnd = false;
24812   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24813   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24814          SetCC.getOpcode() == ISD::TRUNCATE ||
24815          SetCC.getOpcode() == ISD::AND) {
24816     if (SetCC.getOpcode() == ISD::AND) {
24817       int OpIdx = -1;
24818       if (isOneConstant(SetCC.getOperand(0)))
24819         OpIdx = 1;
24820       if (isOneConstant(SetCC.getOperand(1)))
24821         OpIdx = 0;
24822       if (OpIdx == -1)
24823         break;
24824       SetCC = SetCC.getOperand(OpIdx);
24825       truncatedToBoolWithAnd = true;
24826     } else
24827       SetCC = SetCC.getOperand(0);
24828   }
24829
24830   switch (SetCC.getOpcode()) {
24831   case X86ISD::SETCC_CARRY:
24832     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24833     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24834     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24835     // truncated to i1 using 'and'.
24836     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24837       break;
24838     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24839            "Invalid use of SETCC_CARRY!");
24840     // FALL THROUGH
24841   case X86ISD::SETCC:
24842     // Set the condition code or opposite one if necessary.
24843     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24844     if (needOppositeCond)
24845       CC = X86::GetOppositeBranchCondition(CC);
24846     return SetCC.getOperand(1);
24847   case X86ISD::CMOV: {
24848     // Check whether false/true value has canonical one, i.e. 0 or 1.
24849     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24850     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24851     // Quit if true value is not a constant.
24852     if (!TVal)
24853       return SDValue();
24854     // Quit if false value is not a constant.
24855     if (!FVal) {
24856       SDValue Op = SetCC.getOperand(0);
24857       // Skip 'zext' or 'trunc' node.
24858       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24859           Op.getOpcode() == ISD::TRUNCATE)
24860         Op = Op.getOperand(0);
24861       // A special case for rdrand/rdseed, where 0 is set if false cond is
24862       // found.
24863       if ((Op.getOpcode() != X86ISD::RDRAND &&
24864            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24865         return SDValue();
24866     }
24867     // Quit if false value is not the constant 0 or 1.
24868     bool FValIsFalse = true;
24869     if (FVal && FVal->getZExtValue() != 0) {
24870       if (FVal->getZExtValue() != 1)
24871         return SDValue();
24872       // If FVal is 1, opposite cond is needed.
24873       needOppositeCond = !needOppositeCond;
24874       FValIsFalse = false;
24875     }
24876     // Quit if TVal is not the constant opposite of FVal.
24877     if (FValIsFalse && TVal->getZExtValue() != 1)
24878       return SDValue();
24879     if (!FValIsFalse && TVal->getZExtValue() != 0)
24880       return SDValue();
24881     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24882     if (needOppositeCond)
24883       CC = X86::GetOppositeBranchCondition(CC);
24884     return SetCC.getOperand(3);
24885   }
24886   }
24887
24888   return SDValue();
24889 }
24890
24891 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24892 /// Match:
24893 ///   (X86or (X86setcc) (X86setcc))
24894 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24895 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24896                                            X86::CondCode &CC1, SDValue &Flags,
24897                                            bool &isAnd) {
24898   if (Cond->getOpcode() == X86ISD::CMP) {
24899     if (!isNullConstant(Cond->getOperand(1)))
24900       return false;
24901
24902     Cond = Cond->getOperand(0);
24903   }
24904
24905   isAnd = false;
24906
24907   SDValue SetCC0, SetCC1;
24908   switch (Cond->getOpcode()) {
24909   default: return false;
24910   case ISD::AND:
24911   case X86ISD::AND:
24912     isAnd = true;
24913     // fallthru
24914   case ISD::OR:
24915   case X86ISD::OR:
24916     SetCC0 = Cond->getOperand(0);
24917     SetCC1 = Cond->getOperand(1);
24918     break;
24919   };
24920
24921   // Make sure we have SETCC nodes, using the same flags value.
24922   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24923       SetCC1.getOpcode() != X86ISD::SETCC ||
24924       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24925     return false;
24926
24927   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24928   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24929   Flags = SetCC0->getOperand(1);
24930   return true;
24931 }
24932
24933 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24934 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24935                                   TargetLowering::DAGCombinerInfo &DCI,
24936                                   const X86Subtarget *Subtarget) {
24937   SDLoc DL(N);
24938
24939   // If the flag operand isn't dead, don't touch this CMOV.
24940   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24941     return SDValue();
24942
24943   SDValue FalseOp = N->getOperand(0);
24944   SDValue TrueOp = N->getOperand(1);
24945   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24946   SDValue Cond = N->getOperand(3);
24947
24948   if (CC == X86::COND_E || CC == X86::COND_NE) {
24949     switch (Cond.getOpcode()) {
24950     default: break;
24951     case X86ISD::BSR:
24952     case X86ISD::BSF:
24953       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24954       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24955         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24956     }
24957   }
24958
24959   SDValue Flags;
24960
24961   Flags = checkBoolTestSetCCCombine(Cond, CC);
24962   if (Flags.getNode() &&
24963       // Extra check as FCMOV only supports a subset of X86 cond.
24964       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24965     SDValue Ops[] = { FalseOp, TrueOp,
24966                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24967     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24968   }
24969
24970   // If this is a select between two integer constants, try to do some
24971   // optimizations.  Note that the operands are ordered the opposite of SELECT
24972   // operands.
24973   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24974     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24975       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24976       // larger than FalseC (the false value).
24977       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24978         CC = X86::GetOppositeBranchCondition(CC);
24979         std::swap(TrueC, FalseC);
24980         std::swap(TrueOp, FalseOp);
24981       }
24982
24983       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24984       // This is efficient for any integer data type (including i8/i16) and
24985       // shift amount.
24986       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24987         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24988                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24989
24990         // Zero extend the condition if needed.
24991         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24992
24993         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24994         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24995                            DAG.getConstant(ShAmt, DL, MVT::i8));
24996         if (N->getNumValues() == 2)  // Dead flag value?
24997           return DCI.CombineTo(N, Cond, SDValue());
24998         return Cond;
24999       }
25000
25001       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
25002       // for any integer data type, including i8/i16.
25003       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
25004         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25005                            DAG.getConstant(CC, DL, MVT::i8), Cond);
25006
25007         // Zero extend the condition if needed.
25008         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
25009                            FalseC->getValueType(0), Cond);
25010         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25011                            SDValue(FalseC, 0));
25012
25013         if (N->getNumValues() == 2)  // Dead flag value?
25014           return DCI.CombineTo(N, Cond, SDValue());
25015         return Cond;
25016       }
25017
25018       // Optimize cases that will turn into an LEA instruction.  This requires
25019       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
25020       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
25021         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
25022         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
25023
25024         bool isFastMultiplier = false;
25025         if (Diff < 10) {
25026           switch ((unsigned char)Diff) {
25027           default: break;
25028           case 1:  // result = add base, cond
25029           case 2:  // result = lea base(    , cond*2)
25030           case 3:  // result = lea base(cond, cond*2)
25031           case 4:  // result = lea base(    , cond*4)
25032           case 5:  // result = lea base(cond, cond*4)
25033           case 8:  // result = lea base(    , cond*8)
25034           case 9:  // result = lea base(cond, cond*8)
25035             isFastMultiplier = true;
25036             break;
25037           }
25038         }
25039
25040         if (isFastMultiplier) {
25041           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
25042           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25043                              DAG.getConstant(CC, DL, MVT::i8), Cond);
25044           // Zero extend the condition if needed.
25045           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
25046                              Cond);
25047           // Scale the condition by the difference.
25048           if (Diff != 1)
25049             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
25050                                DAG.getConstant(Diff, DL, Cond.getValueType()));
25051
25052           // Add the base if non-zero.
25053           if (FalseC->getAPIntValue() != 0)
25054             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25055                                SDValue(FalseC, 0));
25056           if (N->getNumValues() == 2)  // Dead flag value?
25057             return DCI.CombineTo(N, Cond, SDValue());
25058           return Cond;
25059         }
25060       }
25061     }
25062   }
25063
25064   // Handle these cases:
25065   //   (select (x != c), e, c) -> select (x != c), e, x),
25066   //   (select (x == c), c, e) -> select (x == c), x, e)
25067   // where the c is an integer constant, and the "select" is the combination
25068   // of CMOV and CMP.
25069   //
25070   // The rationale for this change is that the conditional-move from a constant
25071   // needs two instructions, however, conditional-move from a register needs
25072   // only one instruction.
25073   //
25074   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25075   //  some instruction-combining opportunities. This opt needs to be
25076   //  postponed as late as possible.
25077   //
25078   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25079     // the DCI.xxxx conditions are provided to postpone the optimization as
25080     // late as possible.
25081
25082     ConstantSDNode *CmpAgainst = nullptr;
25083     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25084         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25085         !isa<ConstantSDNode>(Cond.getOperand(0))) {
25086
25087       if (CC == X86::COND_NE &&
25088           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25089         CC = X86::GetOppositeBranchCondition(CC);
25090         std::swap(TrueOp, FalseOp);
25091       }
25092
25093       if (CC == X86::COND_E &&
25094           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25095         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25096                           DAG.getConstant(CC, DL, MVT::i8), Cond };
25097         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25098       }
25099     }
25100   }
25101
25102   // Fold and/or of setcc's to double CMOV:
25103   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25104   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25105   //
25106   // This combine lets us generate:
25107   //   cmovcc1 (jcc1 if we don't have CMOV)
25108   //   cmovcc2 (same)
25109   // instead of:
25110   //   setcc1
25111   //   setcc2
25112   //   and/or
25113   //   cmovne (jne if we don't have CMOV)
25114   // When we can't use the CMOV instruction, it might increase branch
25115   // mispredicts.
25116   // When we can use CMOV, or when there is no mispredict, this improves
25117   // throughput and reduces register pressure.
25118   //
25119   if (CC == X86::COND_NE) {
25120     SDValue Flags;
25121     X86::CondCode CC0, CC1;
25122     bool isAndSetCC;
25123     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25124       if (isAndSetCC) {
25125         std::swap(FalseOp, TrueOp);
25126         CC0 = X86::GetOppositeBranchCondition(CC0);
25127         CC1 = X86::GetOppositeBranchCondition(CC1);
25128       }
25129
25130       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25131         Flags};
25132       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25133       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25134       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25135       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25136       return CMOV;
25137     }
25138   }
25139
25140   return SDValue();
25141 }
25142
25143 /// PerformMulCombine - Optimize a single multiply with constant into two
25144 /// in order to implement it with two cheaper instructions, e.g.
25145 /// LEA + SHL, LEA + LEA.
25146 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25147                                  TargetLowering::DAGCombinerInfo &DCI) {
25148   // An imul is usually smaller than the alternative sequence.
25149   if (DAG.getMachineFunction().getFunction()->optForMinSize())
25150     return SDValue();
25151
25152   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25153     return SDValue();
25154
25155   EVT VT = N->getValueType(0);
25156   if (VT != MVT::i64 && VT != MVT::i32)
25157     return SDValue();
25158
25159   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25160   if (!C)
25161     return SDValue();
25162   uint64_t MulAmt = C->getZExtValue();
25163   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25164     return SDValue();
25165
25166   uint64_t MulAmt1 = 0;
25167   uint64_t MulAmt2 = 0;
25168   if ((MulAmt % 9) == 0) {
25169     MulAmt1 = 9;
25170     MulAmt2 = MulAmt / 9;
25171   } else if ((MulAmt % 5) == 0) {
25172     MulAmt1 = 5;
25173     MulAmt2 = MulAmt / 5;
25174   } else if ((MulAmt % 3) == 0) {
25175     MulAmt1 = 3;
25176     MulAmt2 = MulAmt / 3;
25177   }
25178
25179   SDLoc DL(N);
25180   SDValue NewMul;
25181   if (MulAmt2 &&
25182       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25183
25184     if (isPowerOf2_64(MulAmt2) &&
25185         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25186       // If second multiplifer is pow2, issue it first. We want the multiply by
25187       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25188       // is an add.
25189       std::swap(MulAmt1, MulAmt2);
25190
25191     if (isPowerOf2_64(MulAmt1))
25192       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25193                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25194     else
25195       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25196                            DAG.getConstant(MulAmt1, DL, VT));
25197
25198     if (isPowerOf2_64(MulAmt2))
25199       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25200                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25201     else
25202       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25203                            DAG.getConstant(MulAmt2, DL, VT));
25204   }
25205
25206   if (!NewMul) {
25207     assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25208            && "Both cases that could cause potential overflows should have "
25209               "already been handled.");
25210     if (isPowerOf2_64(MulAmt - 1))
25211       // (mul x, 2^N + 1) => (add (shl x, N), x)
25212       NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25213                                 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25214                                 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25215                                 MVT::i8)));
25216
25217     else if (isPowerOf2_64(MulAmt + 1))
25218       // (mul x, 2^N - 1) => (sub (shl x, N), x)
25219       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25220                                 N->getOperand(0),
25221                                 DAG.getConstant(Log2_64(MulAmt + 1),
25222                                 DL, MVT::i8)), N->getOperand(0));
25223   }
25224
25225   if (NewMul)
25226     // Do not add new nodes to DAG combiner worklist.
25227     DCI.CombineTo(N, NewMul, false);
25228
25229   return SDValue();
25230 }
25231
25232 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25233   SDValue N0 = N->getOperand(0);
25234   SDValue N1 = N->getOperand(1);
25235   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25236   EVT VT = N0.getValueType();
25237
25238   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25239   // since the result of setcc_c is all zero's or all ones.
25240   if (VT.isInteger() && !VT.isVector() &&
25241       N1C && N0.getOpcode() == ISD::AND &&
25242       N0.getOperand(1).getOpcode() == ISD::Constant) {
25243     SDValue N00 = N0.getOperand(0);
25244     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25245     APInt ShAmt = N1C->getAPIntValue();
25246     Mask = Mask.shl(ShAmt);
25247     bool MaskOK = false;
25248     // We can handle cases concerning bit-widening nodes containing setcc_c if
25249     // we carefully interrogate the mask to make sure we are semantics
25250     // preserving.
25251     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25252     // of the underlying setcc_c operation if the setcc_c was zero extended.
25253     // Consider the following example:
25254     //   zext(setcc_c)                 -> i32 0x0000FFFF
25255     //   c1                            -> i32 0x0000FFFF
25256     //   c2                            -> i32 0x00000001
25257     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25258     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
25259     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25260       MaskOK = true;
25261     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25262                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25263       MaskOK = true;
25264     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25265                 N00.getOpcode() == ISD::ANY_EXTEND) &&
25266                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25267       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25268     }
25269     if (MaskOK && Mask != 0) {
25270       SDLoc DL(N);
25271       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25272     }
25273   }
25274
25275   // Hardware support for vector shifts is sparse which makes us scalarize the
25276   // vector operations in many cases. Also, on sandybridge ADD is faster than
25277   // shl.
25278   // (shl V, 1) -> add V,V
25279   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25280     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25281       assert(N0.getValueType().isVector() && "Invalid vector shift type");
25282       // We shift all of the values by one. In many cases we do not have
25283       // hardware support for this operation. This is better expressed as an ADD
25284       // of two values.
25285       if (N1SplatC->getAPIntValue() == 1)
25286         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25287     }
25288
25289   return SDValue();
25290 }
25291
25292 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25293   SDValue N0 = N->getOperand(0);
25294   SDValue N1 = N->getOperand(1);
25295   EVT VT = N0.getValueType();
25296   unsigned Size = VT.getSizeInBits();
25297
25298   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25299   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25300   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25301   // depending on sign of (SarConst - [56,48,32,24,16])
25302
25303   // sexts in X86 are MOVs. The MOVs have the same code size
25304   // as above SHIFTs (only SHIFT on 1 has lower code size).
25305   // However the MOVs have 2 advantages to a SHIFT:
25306   // 1. MOVs can write to a register that differs from source
25307   // 2. MOVs accept memory operands
25308
25309   if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25310       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25311       N0.getOperand(1).getOpcode() != ISD::Constant)
25312     return SDValue();
25313
25314   SDValue N00 = N0.getOperand(0);
25315   SDValue N01 = N0.getOperand(1);
25316   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25317   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25318   EVT CVT = N1.getValueType();
25319
25320   if (SarConst.isNegative())
25321     return SDValue();
25322
25323   for (MVT SVT : MVT::integer_valuetypes()) {
25324     unsigned ShiftSize = SVT.getSizeInBits();
25325     // skipping types without corresponding sext/zext and
25326     // ShlConst that is not one of [56,48,32,24,16]
25327     if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25328       continue;
25329     SDLoc DL(N);
25330     SDValue NN =
25331         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25332     SarConst = SarConst - (Size - ShiftSize);
25333     if (SarConst == 0)
25334       return NN;
25335     else if (SarConst.isNegative())
25336       return DAG.getNode(ISD::SHL, DL, VT, NN,
25337                          DAG.getConstant(-SarConst, DL, CVT));
25338     else
25339       return DAG.getNode(ISD::SRA, DL, VT, NN,
25340                          DAG.getConstant(SarConst, DL, CVT));
25341   }
25342   return SDValue();
25343 }
25344
25345 /// \brief Returns a vector of 0s if the node in input is a vector logical
25346 /// shift by a constant amount which is known to be bigger than or equal
25347 /// to the vector element size in bits.
25348 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25349                                       const X86Subtarget *Subtarget) {
25350   EVT VT = N->getValueType(0);
25351
25352   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25353       (!Subtarget->hasInt256() ||
25354        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25355     return SDValue();
25356
25357   SDValue Amt = N->getOperand(1);
25358   SDLoc DL(N);
25359   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25360     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25361       APInt ShiftAmt = AmtSplat->getAPIntValue();
25362       unsigned MaxAmount =
25363         VT.getSimpleVT().getVectorElementType().getSizeInBits();
25364
25365       // SSE2/AVX2 logical shifts always return a vector of 0s
25366       // if the shift amount is bigger than or equal to
25367       // the element size. The constant shift amount will be
25368       // encoded as a 8-bit immediate.
25369       if (ShiftAmt.trunc(8).uge(MaxAmount))
25370         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25371     }
25372
25373   return SDValue();
25374 }
25375
25376 /// PerformShiftCombine - Combine shifts.
25377 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25378                                    TargetLowering::DAGCombinerInfo &DCI,
25379                                    const X86Subtarget *Subtarget) {
25380   if (N->getOpcode() == ISD::SHL)
25381     if (SDValue V = PerformSHLCombine(N, DAG))
25382       return V;
25383
25384   if (N->getOpcode() == ISD::SRA)
25385     if (SDValue V = PerformSRACombine(N, DAG))
25386       return V;
25387
25388   // Try to fold this logical shift into a zero vector.
25389   if (N->getOpcode() != ISD::SRA)
25390     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25391       return V;
25392
25393   return SDValue();
25394 }
25395
25396 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
25397 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25398 // and friends.  Likewise for OR -> CMPNEQSS.
25399 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25400                             TargetLowering::DAGCombinerInfo &DCI,
25401                             const X86Subtarget *Subtarget) {
25402   unsigned opcode;
25403
25404   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25405   // we're requiring SSE2 for both.
25406   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25407     SDValue N0 = N->getOperand(0);
25408     SDValue N1 = N->getOperand(1);
25409     SDValue CMP0 = N0->getOperand(1);
25410     SDValue CMP1 = N1->getOperand(1);
25411     SDLoc DL(N);
25412
25413     // The SETCCs should both refer to the same CMP.
25414     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25415       return SDValue();
25416
25417     SDValue CMP00 = CMP0->getOperand(0);
25418     SDValue CMP01 = CMP0->getOperand(1);
25419     EVT     VT    = CMP00.getValueType();
25420
25421     if (VT == MVT::f32 || VT == MVT::f64) {
25422       bool ExpectingFlags = false;
25423       // Check for any users that want flags:
25424       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25425            !ExpectingFlags && UI != UE; ++UI)
25426         switch (UI->getOpcode()) {
25427         default:
25428         case ISD::BR_CC:
25429         case ISD::BRCOND:
25430         case ISD::SELECT:
25431           ExpectingFlags = true;
25432           break;
25433         case ISD::CopyToReg:
25434         case ISD::SIGN_EXTEND:
25435         case ISD::ZERO_EXTEND:
25436         case ISD::ANY_EXTEND:
25437           break;
25438         }
25439
25440       if (!ExpectingFlags) {
25441         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25442         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25443
25444         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25445           X86::CondCode tmp = cc0;
25446           cc0 = cc1;
25447           cc1 = tmp;
25448         }
25449
25450         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
25451             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25452           // FIXME: need symbolic constants for these magic numbers.
25453           // See X86ATTInstPrinter.cpp:printSSECC().
25454           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25455           if (Subtarget->hasAVX512()) {
25456             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25457                                          CMP01,
25458                                          DAG.getConstant(x86cc, DL, MVT::i8));
25459             if (N->getValueType(0) != MVT::i1)
25460               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25461                                  FSetCC);
25462             return FSetCC;
25463           }
25464           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25465                                               CMP00.getValueType(), CMP00, CMP01,
25466                                               DAG.getConstant(x86cc, DL,
25467                                                               MVT::i8));
25468
25469           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25470           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25471
25472           if (is64BitFP && !Subtarget->is64Bit()) {
25473             // On a 32-bit target, we cannot bitcast the 64-bit float to a
25474             // 64-bit integer, since that's not a legal type. Since
25475             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25476             // bits, but can do this little dance to extract the lowest 32 bits
25477             // and work with those going forward.
25478             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25479                                            OnesOrZeroesF);
25480             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25481             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25482                                         Vector32, DAG.getIntPtrConstant(0, DL));
25483             IntVT = MVT::i32;
25484           }
25485
25486           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25487           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25488                                       DAG.getConstant(1, DL, IntVT));
25489           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25490                                               ANDed);
25491           return OneBitOfTruth;
25492         }
25493       }
25494     }
25495   }
25496   return SDValue();
25497 }
25498
25499 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25500 /// so it can be folded inside ANDNP.
25501 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25502   EVT VT = N->getValueType(0);
25503
25504   // Match direct AllOnes for 128 and 256-bit vectors
25505   if (ISD::isBuildVectorAllOnes(N))
25506     return true;
25507
25508   // Look through a bit convert.
25509   if (N->getOpcode() == ISD::BITCAST)
25510     N = N->getOperand(0).getNode();
25511
25512   // Sometimes the operand may come from a insert_subvector building a 256-bit
25513   // allones vector
25514   if (VT.is256BitVector() &&
25515       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25516     SDValue V1 = N->getOperand(0);
25517     SDValue V2 = N->getOperand(1);
25518
25519     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25520         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25521         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25522         ISD::isBuildVectorAllOnes(V2.getNode()))
25523       return true;
25524   }
25525
25526   return false;
25527 }
25528
25529 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25530 // register. In most cases we actually compare or select YMM-sized registers
25531 // and mixing the two types creates horrible code. This method optimizes
25532 // some of the transition sequences.
25533 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25534                                  TargetLowering::DAGCombinerInfo &DCI,
25535                                  const X86Subtarget *Subtarget) {
25536   EVT VT = N->getValueType(0);
25537   if (!VT.is256BitVector())
25538     return SDValue();
25539
25540   assert((N->getOpcode() == ISD::ANY_EXTEND ||
25541           N->getOpcode() == ISD::ZERO_EXTEND ||
25542           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25543
25544   SDValue Narrow = N->getOperand(0);
25545   EVT NarrowVT = Narrow->getValueType(0);
25546   if (!NarrowVT.is128BitVector())
25547     return SDValue();
25548
25549   if (Narrow->getOpcode() != ISD::XOR &&
25550       Narrow->getOpcode() != ISD::AND &&
25551       Narrow->getOpcode() != ISD::OR)
25552     return SDValue();
25553
25554   SDValue N0  = Narrow->getOperand(0);
25555   SDValue N1  = Narrow->getOperand(1);
25556   SDLoc DL(Narrow);
25557
25558   // The Left side has to be a trunc.
25559   if (N0.getOpcode() != ISD::TRUNCATE)
25560     return SDValue();
25561
25562   // The type of the truncated inputs.
25563   EVT WideVT = N0->getOperand(0)->getValueType(0);
25564   if (WideVT != VT)
25565     return SDValue();
25566
25567   // The right side has to be a 'trunc' or a constant vector.
25568   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25569   ConstantSDNode *RHSConstSplat = nullptr;
25570   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25571     RHSConstSplat = RHSBV->getConstantSplatNode();
25572   if (!RHSTrunc && !RHSConstSplat)
25573     return SDValue();
25574
25575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25576
25577   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25578     return SDValue();
25579
25580   // Set N0 and N1 to hold the inputs to the new wide operation.
25581   N0 = N0->getOperand(0);
25582   if (RHSConstSplat) {
25583     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25584                      SDValue(RHSConstSplat, 0));
25585     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25586     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25587   } else if (RHSTrunc) {
25588     N1 = N1->getOperand(0);
25589   }
25590
25591   // Generate the wide operation.
25592   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25593   unsigned Opcode = N->getOpcode();
25594   switch (Opcode) {
25595   case ISD::ANY_EXTEND:
25596     return Op;
25597   case ISD::ZERO_EXTEND: {
25598     unsigned InBits = NarrowVT.getScalarSizeInBits();
25599     APInt Mask = APInt::getAllOnesValue(InBits);
25600     Mask = Mask.zext(VT.getScalarSizeInBits());
25601     return DAG.getNode(ISD::AND, DL, VT,
25602                        Op, DAG.getConstant(Mask, DL, VT));
25603   }
25604   case ISD::SIGN_EXTEND:
25605     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25606                        Op, DAG.getValueType(NarrowVT));
25607   default:
25608     llvm_unreachable("Unexpected opcode");
25609   }
25610 }
25611
25612 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25613                                  TargetLowering::DAGCombinerInfo &DCI,
25614                                  const X86Subtarget *Subtarget) {
25615   SDValue N0 = N->getOperand(0);
25616   SDValue N1 = N->getOperand(1);
25617   SDLoc DL(N);
25618
25619   // A vector zext_in_reg may be represented as a shuffle,
25620   // feeding into a bitcast (this represents anyext) feeding into
25621   // an and with a mask.
25622   // We'd like to try to combine that into a shuffle with zero
25623   // plus a bitcast, removing the and.
25624   if (N0.getOpcode() != ISD::BITCAST ||
25625       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25626     return SDValue();
25627
25628   // The other side of the AND should be a splat of 2^C, where C
25629   // is the number of bits in the source type.
25630   if (N1.getOpcode() == ISD::BITCAST)
25631     N1 = N1.getOperand(0);
25632   if (N1.getOpcode() != ISD::BUILD_VECTOR)
25633     return SDValue();
25634   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25635
25636   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25637   EVT SrcType = Shuffle->getValueType(0);
25638
25639   // We expect a single-source shuffle
25640   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25641     return SDValue();
25642
25643   unsigned SrcSize = SrcType.getScalarSizeInBits();
25644
25645   APInt SplatValue, SplatUndef;
25646   unsigned SplatBitSize;
25647   bool HasAnyUndefs;
25648   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25649                                 SplatBitSize, HasAnyUndefs))
25650     return SDValue();
25651
25652   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25653   // Make sure the splat matches the mask we expect
25654   if (SplatBitSize > ResSize ||
25655       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25656     return SDValue();
25657
25658   // Make sure the input and output size make sense
25659   if (SrcSize >= ResSize || ResSize % SrcSize)
25660     return SDValue();
25661
25662   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25663   // The number of u's between each two values depends on the ratio between
25664   // the source and dest type.
25665   unsigned ZextRatio = ResSize / SrcSize;
25666   bool IsZext = true;
25667   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25668     if (i % ZextRatio) {
25669       if (Shuffle->getMaskElt(i) > 0) {
25670         // Expected undef
25671         IsZext = false;
25672         break;
25673       }
25674     } else {
25675       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25676         // Expected element number
25677         IsZext = false;
25678         break;
25679       }
25680     }
25681   }
25682
25683   if (!IsZext)
25684     return SDValue();
25685
25686   // Ok, perform the transformation - replace the shuffle with
25687   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25688   // (instead of undef) where the k elements come from the zero vector.
25689   SmallVector<int, 8> Mask;
25690   unsigned NumElems = SrcType.getVectorNumElements();
25691   for (unsigned i = 0; i < NumElems; ++i)
25692     if (i % ZextRatio)
25693       Mask.push_back(NumElems);
25694     else
25695       Mask.push_back(i / ZextRatio);
25696
25697   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25698     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25699   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25700 }
25701
25702 /// If both input operands of a logic op are being cast from floating point
25703 /// types, try to convert this into a floating point logic node to avoid
25704 /// unnecessary moves from SSE to integer registers.
25705 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25706                                         const X86Subtarget *Subtarget) {
25707   unsigned FPOpcode = ISD::DELETED_NODE;
25708   if (N->getOpcode() == ISD::AND)
25709     FPOpcode = X86ISD::FAND;
25710   else if (N->getOpcode() == ISD::OR)
25711     FPOpcode = X86ISD::FOR;
25712   else if (N->getOpcode() == ISD::XOR)
25713     FPOpcode = X86ISD::FXOR;
25714
25715   assert(FPOpcode != ISD::DELETED_NODE &&
25716          "Unexpected input node for FP logic conversion");
25717
25718   EVT VT = N->getValueType(0);
25719   SDValue N0 = N->getOperand(0);
25720   SDValue N1 = N->getOperand(1);
25721   SDLoc DL(N);
25722   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25723       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25724        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25725     SDValue N00 = N0.getOperand(0);
25726     SDValue N10 = N1.getOperand(0);
25727     EVT N00Type = N00.getValueType();
25728     EVT N10Type = N10.getValueType();
25729     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25730       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25731       return DAG.getBitcast(VT, FPLogic);
25732     }
25733   }
25734   return SDValue();
25735 }
25736
25737 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25738                                  TargetLowering::DAGCombinerInfo &DCI,
25739                                  const X86Subtarget *Subtarget) {
25740   if (DCI.isBeforeLegalizeOps())
25741     return SDValue();
25742
25743   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25744     return Zext;
25745
25746   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25747     return R;
25748
25749   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25750     return FPLogic;
25751
25752   EVT VT = N->getValueType(0);
25753   SDValue N0 = N->getOperand(0);
25754   SDValue N1 = N->getOperand(1);
25755   SDLoc DL(N);
25756
25757   // Create BEXTR instructions
25758   // BEXTR is ((X >> imm) & (2**size-1))
25759   if (VT == MVT::i32 || VT == MVT::i64) {
25760     // Check for BEXTR.
25761     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25762         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25763       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25764       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25765       if (MaskNode && ShiftNode) {
25766         uint64_t Mask = MaskNode->getZExtValue();
25767         uint64_t Shift = ShiftNode->getZExtValue();
25768         if (isMask_64(Mask)) {
25769           uint64_t MaskSize = countPopulation(Mask);
25770           if (Shift + MaskSize <= VT.getSizeInBits())
25771             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25772                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25773                                                VT));
25774         }
25775       }
25776     } // BEXTR
25777
25778     return SDValue();
25779   }
25780
25781   // Want to form ANDNP nodes:
25782   // 1) In the hopes of then easily combining them with OR and AND nodes
25783   //    to form PBLEND/PSIGN.
25784   // 2) To match ANDN packed intrinsics
25785   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25786     return SDValue();
25787
25788   // Check LHS for vnot
25789   if (N0.getOpcode() == ISD::XOR &&
25790       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25791       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25792     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25793
25794   // Check RHS for vnot
25795   if (N1.getOpcode() == ISD::XOR &&
25796       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25797       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25798     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25799
25800   return SDValue();
25801 }
25802
25803 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25804                                 TargetLowering::DAGCombinerInfo &DCI,
25805                                 const X86Subtarget *Subtarget) {
25806   if (DCI.isBeforeLegalizeOps())
25807     return SDValue();
25808
25809   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25810     return R;
25811
25812   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25813     return FPLogic;
25814
25815   SDValue N0 = N->getOperand(0);
25816   SDValue N1 = N->getOperand(1);
25817   EVT VT = N->getValueType(0);
25818
25819   // look for psign/blend
25820   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25821     if (!Subtarget->hasSSSE3() ||
25822         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25823       return SDValue();
25824
25825     // Canonicalize pandn to RHS
25826     if (N0.getOpcode() == X86ISD::ANDNP)
25827       std::swap(N0, N1);
25828     // or (and (m, y), (pandn m, x))
25829     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25830       SDValue Mask = N1.getOperand(0);
25831       SDValue X    = N1.getOperand(1);
25832       SDValue Y;
25833       if (N0.getOperand(0) == Mask)
25834         Y = N0.getOperand(1);
25835       if (N0.getOperand(1) == Mask)
25836         Y = N0.getOperand(0);
25837
25838       // Check to see if the mask appeared in both the AND and ANDNP and
25839       if (!Y.getNode())
25840         return SDValue();
25841
25842       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25843       // Look through mask bitcast.
25844       if (Mask.getOpcode() == ISD::BITCAST)
25845         Mask = Mask.getOperand(0);
25846       if (X.getOpcode() == ISD::BITCAST)
25847         X = X.getOperand(0);
25848       if (Y.getOpcode() == ISD::BITCAST)
25849         Y = Y.getOperand(0);
25850
25851       EVT MaskVT = Mask.getValueType();
25852
25853       // Validate that the Mask operand is a vector sra node.
25854       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25855       // there is no psrai.b
25856       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25857       unsigned SraAmt = ~0;
25858       if (Mask.getOpcode() == ISD::SRA) {
25859         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25860           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25861             SraAmt = AmtConst->getZExtValue();
25862       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25863         SDValue SraC = Mask.getOperand(1);
25864         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25865       }
25866       if ((SraAmt + 1) != EltBits)
25867         return SDValue();
25868
25869       SDLoc DL(N);
25870
25871       // Now we know we at least have a plendvb with the mask val.  See if
25872       // we can form a psignb/w/d.
25873       // psign = x.type == y.type == mask.type && y = sub(0, x);
25874       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25875           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25876           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25877         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25878                "Unsupported VT for PSIGN");
25879         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25880         return DAG.getBitcast(VT, Mask);
25881       }
25882       // PBLENDVB only available on SSE 4.1
25883       if (!Subtarget->hasSSE41())
25884         return SDValue();
25885
25886       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25887
25888       X = DAG.getBitcast(BlendVT, X);
25889       Y = DAG.getBitcast(BlendVT, Y);
25890       Mask = DAG.getBitcast(BlendVT, Mask);
25891       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25892       return DAG.getBitcast(VT, Mask);
25893     }
25894   }
25895
25896   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25897     return SDValue();
25898
25899   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25900   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25901
25902   // SHLD/SHRD instructions have lower register pressure, but on some
25903   // platforms they have higher latency than the equivalent
25904   // series of shifts/or that would otherwise be generated.
25905   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25906   // have higher latencies and we are not optimizing for size.
25907   if (!OptForSize && Subtarget->isSHLDSlow())
25908     return SDValue();
25909
25910   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25911     std::swap(N0, N1);
25912   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25913     return SDValue();
25914   if (!N0.hasOneUse() || !N1.hasOneUse())
25915     return SDValue();
25916
25917   SDValue ShAmt0 = N0.getOperand(1);
25918   if (ShAmt0.getValueType() != MVT::i8)
25919     return SDValue();
25920   SDValue ShAmt1 = N1.getOperand(1);
25921   if (ShAmt1.getValueType() != MVT::i8)
25922     return SDValue();
25923   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25924     ShAmt0 = ShAmt0.getOperand(0);
25925   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25926     ShAmt1 = ShAmt1.getOperand(0);
25927
25928   SDLoc DL(N);
25929   unsigned Opc = X86ISD::SHLD;
25930   SDValue Op0 = N0.getOperand(0);
25931   SDValue Op1 = N1.getOperand(0);
25932   if (ShAmt0.getOpcode() == ISD::SUB) {
25933     Opc = X86ISD::SHRD;
25934     std::swap(Op0, Op1);
25935     std::swap(ShAmt0, ShAmt1);
25936   }
25937
25938   unsigned Bits = VT.getSizeInBits();
25939   if (ShAmt1.getOpcode() == ISD::SUB) {
25940     SDValue Sum = ShAmt1.getOperand(0);
25941     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25942       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25943       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25944         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25945       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25946         return DAG.getNode(Opc, DL, VT,
25947                            Op0, Op1,
25948                            DAG.getNode(ISD::TRUNCATE, DL,
25949                                        MVT::i8, ShAmt0));
25950     }
25951   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25952     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25953     if (ShAmt0C &&
25954         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25955       return DAG.getNode(Opc, DL, VT,
25956                          N0.getOperand(0), N1.getOperand(0),
25957                          DAG.getNode(ISD::TRUNCATE, DL,
25958                                        MVT::i8, ShAmt0));
25959   }
25960
25961   return SDValue();
25962 }
25963
25964 // Generate NEG and CMOV for integer abs.
25965 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25966   EVT VT = N->getValueType(0);
25967
25968   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25969   // 8-bit integer abs to NEG and CMOV.
25970   if (VT.isInteger() && VT.getSizeInBits() == 8)
25971     return SDValue();
25972
25973   SDValue N0 = N->getOperand(0);
25974   SDValue N1 = N->getOperand(1);
25975   SDLoc DL(N);
25976
25977   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25978   // and change it to SUB and CMOV.
25979   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25980       N0.getOpcode() == ISD::ADD &&
25981       N0.getOperand(1) == N1 &&
25982       N1.getOpcode() == ISD::SRA &&
25983       N1.getOperand(0) == N0.getOperand(0))
25984     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25985       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25986         // Generate SUB & CMOV.
25987         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25988                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25989
25990         SDValue Ops[] = { N0.getOperand(0), Neg,
25991                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25992                           SDValue(Neg.getNode(), 1) };
25993         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25994       }
25995   return SDValue();
25996 }
25997
25998 // Try to turn tests against the signbit in the form of:
25999 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
26000 // into:
26001 //   SETGT(X, -1)
26002 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
26003   // This is only worth doing if the output type is i8.
26004   if (N->getValueType(0) != MVT::i8)
26005     return SDValue();
26006
26007   SDValue N0 = N->getOperand(0);
26008   SDValue N1 = N->getOperand(1);
26009
26010   // We should be performing an xor against a truncated shift.
26011   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
26012     return SDValue();
26013
26014   // Make sure we are performing an xor against one.
26015   if (!isOneConstant(N1))
26016     return SDValue();
26017
26018   // SetCC on x86 zero extends so only act on this if it's a logical shift.
26019   SDValue Shift = N0.getOperand(0);
26020   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
26021     return SDValue();
26022
26023   // Make sure we are truncating from one of i16, i32 or i64.
26024   EVT ShiftTy = Shift.getValueType();
26025   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
26026     return SDValue();
26027
26028   // Make sure the shift amount extracts the sign bit.
26029   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
26030       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
26031     return SDValue();
26032
26033   // Create a greater-than comparison against -1.
26034   // N.B. Using SETGE against 0 works but we want a canonical looking
26035   // comparison, using SETGT matches up with what TranslateX86CC.
26036   SDLoc DL(N);
26037   SDValue ShiftOp = Shift.getOperand(0);
26038   EVT ShiftOpTy = ShiftOp.getValueType();
26039   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
26040                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
26041   return Cond;
26042 }
26043
26044 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
26045                                  TargetLowering::DAGCombinerInfo &DCI,
26046                                  const X86Subtarget *Subtarget) {
26047   if (DCI.isBeforeLegalizeOps())
26048     return SDValue();
26049
26050   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
26051     return RV;
26052
26053   if (Subtarget->hasCMov())
26054     if (SDValue RV = performIntegerAbsCombine(N, DAG))
26055       return RV;
26056
26057   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26058     return FPLogic;
26059
26060   return SDValue();
26061 }
26062
26063 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26064 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26065 /// X86ISD::AVG instruction.
26066 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26067                                 const X86Subtarget *Subtarget, SDLoc DL) {
26068   if (!VT.isVector() || !VT.isSimple())
26069     return SDValue();
26070   EVT InVT = In.getValueType();
26071   unsigned NumElems = VT.getVectorNumElements();
26072
26073   EVT ScalarVT = VT.getVectorElementType();
26074   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26075         isPowerOf2_32(NumElems)))
26076     return SDValue();
26077
26078   // InScalarVT is the intermediate type in AVG pattern and it should be greater
26079   // than the original input type (i8/i16).
26080   EVT InScalarVT = InVT.getVectorElementType();
26081   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26082     return SDValue();
26083
26084   if (Subtarget->hasAVX512()) {
26085     if (VT.getSizeInBits() > 512)
26086       return SDValue();
26087   } else if (Subtarget->hasAVX2()) {
26088     if (VT.getSizeInBits() > 256)
26089       return SDValue();
26090   } else {
26091     if (VT.getSizeInBits() > 128)
26092       return SDValue();
26093   }
26094
26095   // Detect the following pattern:
26096   //
26097   //   %1 = zext <N x i8> %a to <N x i32>
26098   //   %2 = zext <N x i8> %b to <N x i32>
26099   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26100   //   %4 = add nuw nsw <N x i32> %3, %2
26101   //   %5 = lshr <N x i32> %N, <i32 1 x N>
26102   //   %6 = trunc <N x i32> %5 to <N x i8>
26103   //
26104   // In AVX512, the last instruction can also be a trunc store.
26105
26106   if (In.getOpcode() != ISD::SRL)
26107     return SDValue();
26108
26109   // A lambda checking the given SDValue is a constant vector and each element
26110   // is in the range [Min, Max].
26111   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26112     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26113     if (!BV || !BV->isConstant())
26114       return false;
26115     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26116       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26117       if (!C)
26118         return false;
26119       uint64_t Val = C->getZExtValue();
26120       if (Val < Min || Val > Max)
26121         return false;
26122     }
26123     return true;
26124   };
26125
26126   // Check if each element of the vector is left-shifted by one.
26127   auto LHS = In.getOperand(0);
26128   auto RHS = In.getOperand(1);
26129   if (!IsConstVectorInRange(RHS, 1, 1))
26130     return SDValue();
26131   if (LHS.getOpcode() != ISD::ADD)
26132     return SDValue();
26133
26134   // Detect a pattern of a + b + 1 where the order doesn't matter.
26135   SDValue Operands[3];
26136   Operands[0] = LHS.getOperand(0);
26137   Operands[1] = LHS.getOperand(1);
26138
26139   // Take care of the case when one of the operands is a constant vector whose
26140   // element is in the range [1, 256].
26141   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26142       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26143       Operands[0].getOperand(0).getValueType() == VT) {
26144     // The pattern is detected. Subtract one from the constant vector, then
26145     // demote it and emit X86ISD::AVG instruction.
26146     SDValue One = DAG.getConstant(1, DL, InScalarVT);
26147     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26148                                SmallVector<SDValue, 8>(NumElems, One));
26149     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26150     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26151     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26152                        Operands[1]);
26153   }
26154
26155   if (Operands[0].getOpcode() == ISD::ADD)
26156     std::swap(Operands[0], Operands[1]);
26157   else if (Operands[1].getOpcode() != ISD::ADD)
26158     return SDValue();
26159   Operands[2] = Operands[1].getOperand(0);
26160   Operands[1] = Operands[1].getOperand(1);
26161
26162   // Now we have three operands of two additions. Check that one of them is a
26163   // constant vector with ones, and the other two are promoted from i8/i16.
26164   for (int i = 0; i < 3; ++i) {
26165     if (!IsConstVectorInRange(Operands[i], 1, 1))
26166       continue;
26167     std::swap(Operands[i], Operands[2]);
26168
26169     // Check if Operands[0] and Operands[1] are results of type promotion.
26170     for (int j = 0; j < 2; ++j)
26171       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26172           Operands[j].getOperand(0).getValueType() != VT)
26173         return SDValue();
26174
26175     // The pattern is detected, emit X86ISD::AVG instruction.
26176     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26177                        Operands[1].getOperand(0));
26178   }
26179
26180   return SDValue();
26181 }
26182
26183 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26184 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26185                                   TargetLowering::DAGCombinerInfo &DCI,
26186                                   const X86Subtarget *Subtarget) {
26187   LoadSDNode *Ld = cast<LoadSDNode>(N);
26188   EVT RegVT = Ld->getValueType(0);
26189   EVT MemVT = Ld->getMemoryVT();
26190   SDLoc dl(Ld);
26191   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26192
26193   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26194   // into two 16-byte operations.
26195   ISD::LoadExtType Ext = Ld->getExtensionType();
26196   bool Fast;
26197   unsigned AddressSpace = Ld->getAddressSpace();
26198   unsigned Alignment = Ld->getAlignment();
26199   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26200       Ext == ISD::NON_EXTLOAD &&
26201       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26202                              AddressSpace, Alignment, &Fast) && !Fast) {
26203     unsigned NumElems = RegVT.getVectorNumElements();
26204     if (NumElems < 2)
26205       return SDValue();
26206
26207     SDValue Ptr = Ld->getBasePtr();
26208     SDValue Increment =
26209         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26210
26211     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26212                                   NumElems/2);
26213     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26214                                 Ld->getPointerInfo(), Ld->isVolatile(),
26215                                 Ld->isNonTemporal(), Ld->isInvariant(),
26216                                 Alignment);
26217     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26218     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26219                                 Ld->getPointerInfo(), Ld->isVolatile(),
26220                                 Ld->isNonTemporal(), Ld->isInvariant(),
26221                                 std::min(16U, Alignment));
26222     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26223                              Load1.getValue(1),
26224                              Load2.getValue(1));
26225
26226     SDValue NewVec = DAG.getUNDEF(RegVT);
26227     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26228     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26229     return DCI.CombineTo(N, NewVec, TF, true);
26230   }
26231
26232   return SDValue();
26233 }
26234
26235 /// PerformMLOADCombine - Resolve extending loads
26236 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26237                                    TargetLowering::DAGCombinerInfo &DCI,
26238                                    const X86Subtarget *Subtarget) {
26239   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26240   if (Mld->getExtensionType() != ISD::SEXTLOAD)
26241     return SDValue();
26242
26243   EVT VT = Mld->getValueType(0);
26244   unsigned NumElems = VT.getVectorNumElements();
26245   EVT LdVT = Mld->getMemoryVT();
26246   SDLoc dl(Mld);
26247
26248   assert(LdVT != VT && "Cannot extend to the same type");
26249   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26250   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26251   // From, To sizes and ElemCount must be pow of two
26252   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26253     "Unexpected size for extending masked load");
26254
26255   unsigned SizeRatio  = ToSz / FromSz;
26256   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26257
26258   // Create a type on which we perform the shuffle
26259   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26260           LdVT.getScalarType(), NumElems*SizeRatio);
26261   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26262
26263   // Convert Src0 value
26264   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26265   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26266     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26267     for (unsigned i = 0; i != NumElems; ++i)
26268       ShuffleVec[i] = i * SizeRatio;
26269
26270     // Can't shuffle using an illegal type.
26271     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26272            "WideVecVT should be legal");
26273     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26274                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26275   }
26276   // Prepare the new mask
26277   SDValue NewMask;
26278   SDValue Mask = Mld->getMask();
26279   if (Mask.getValueType() == VT) {
26280     // Mask and original value have the same type
26281     NewMask = DAG.getBitcast(WideVecVT, Mask);
26282     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26283     for (unsigned i = 0; i != NumElems; ++i)
26284       ShuffleVec[i] = i * SizeRatio;
26285     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26286       ShuffleVec[i] = NumElems * SizeRatio;
26287     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26288                                    DAG.getConstant(0, dl, WideVecVT),
26289                                    &ShuffleVec[0]);
26290   }
26291   else {
26292     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26293     unsigned WidenNumElts = NumElems*SizeRatio;
26294     unsigned MaskNumElts = VT.getVectorNumElements();
26295     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26296                                      WidenNumElts);
26297
26298     unsigned NumConcat = WidenNumElts / MaskNumElts;
26299     SmallVector<SDValue, 16> Ops(NumConcat);
26300     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26301     Ops[0] = Mask;
26302     for (unsigned i = 1; i != NumConcat; ++i)
26303       Ops[i] = ZeroVal;
26304
26305     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26306   }
26307
26308   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26309                                      Mld->getBasePtr(), NewMask, WideSrc0,
26310                                      Mld->getMemoryVT(), Mld->getMemOperand(),
26311                                      ISD::NON_EXTLOAD);
26312   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26313   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26314 }
26315 /// PerformMSTORECombine - Resolve truncating stores
26316 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26317                                     const X86Subtarget *Subtarget) {
26318   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26319   if (!Mst->isTruncatingStore())
26320     return SDValue();
26321
26322   EVT VT = Mst->getValue().getValueType();
26323   unsigned NumElems = VT.getVectorNumElements();
26324   EVT StVT = Mst->getMemoryVT();
26325   SDLoc dl(Mst);
26326
26327   assert(StVT != VT && "Cannot truncate to the same type");
26328   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26329   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26330
26331   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26332
26333   // The truncating store is legal in some cases. For example
26334   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26335   // are designated for truncate store.
26336   // In this case we don't need any further transformations.
26337   if (TLI.isTruncStoreLegal(VT, StVT))
26338     return SDValue();
26339
26340   // From, To sizes and ElemCount must be pow of two
26341   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26342     "Unexpected size for truncating masked store");
26343   // We are going to use the original vector elt for storing.
26344   // Accumulated smaller vector elements must be a multiple of the store size.
26345   assert (((NumElems * FromSz) % ToSz) == 0 &&
26346           "Unexpected ratio for truncating masked store");
26347
26348   unsigned SizeRatio  = FromSz / ToSz;
26349   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26350
26351   // Create a type on which we perform the shuffle
26352   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26353           StVT.getScalarType(), NumElems*SizeRatio);
26354
26355   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26356
26357   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26358   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26359   for (unsigned i = 0; i != NumElems; ++i)
26360     ShuffleVec[i] = i * SizeRatio;
26361
26362   // Can't shuffle using an illegal type.
26363   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26364          "WideVecVT should be legal");
26365
26366   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26367                                               DAG.getUNDEF(WideVecVT),
26368                                               &ShuffleVec[0]);
26369
26370   SDValue NewMask;
26371   SDValue Mask = Mst->getMask();
26372   if (Mask.getValueType() == VT) {
26373     // Mask and original value have the same type
26374     NewMask = DAG.getBitcast(WideVecVT, Mask);
26375     for (unsigned i = 0; i != NumElems; ++i)
26376       ShuffleVec[i] = i * SizeRatio;
26377     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26378       ShuffleVec[i] = NumElems*SizeRatio;
26379     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26380                                    DAG.getConstant(0, dl, WideVecVT),
26381                                    &ShuffleVec[0]);
26382   }
26383   else {
26384     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26385     unsigned WidenNumElts = NumElems*SizeRatio;
26386     unsigned MaskNumElts = VT.getVectorNumElements();
26387     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26388                                      WidenNumElts);
26389
26390     unsigned NumConcat = WidenNumElts / MaskNumElts;
26391     SmallVector<SDValue, 16> Ops(NumConcat);
26392     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26393     Ops[0] = Mask;
26394     for (unsigned i = 1; i != NumConcat; ++i)
26395       Ops[i] = ZeroVal;
26396
26397     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26398   }
26399
26400   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26401                             Mst->getBasePtr(), NewMask, StVT,
26402                             Mst->getMemOperand(), false);
26403 }
26404 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26405 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26406                                    const X86Subtarget *Subtarget) {
26407   StoreSDNode *St = cast<StoreSDNode>(N);
26408   EVT VT = St->getValue().getValueType();
26409   EVT StVT = St->getMemoryVT();
26410   SDLoc dl(St);
26411   SDValue StoredVal = St->getOperand(1);
26412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26413
26414   // If we are saving a concatenation of two XMM registers and 32-byte stores
26415   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26416   bool Fast;
26417   unsigned AddressSpace = St->getAddressSpace();
26418   unsigned Alignment = St->getAlignment();
26419   if (VT.is256BitVector() && StVT == VT &&
26420       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26421                              AddressSpace, Alignment, &Fast) && !Fast) {
26422     unsigned NumElems = VT.getVectorNumElements();
26423     if (NumElems < 2)
26424       return SDValue();
26425
26426     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26427     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26428
26429     SDValue Stride =
26430         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26431     SDValue Ptr0 = St->getBasePtr();
26432     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26433
26434     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26435                                 St->getPointerInfo(), St->isVolatile(),
26436                                 St->isNonTemporal(), Alignment);
26437     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26438                                 St->getPointerInfo(), St->isVolatile(),
26439                                 St->isNonTemporal(),
26440                                 std::min(16U, Alignment));
26441     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26442   }
26443
26444   // Optimize trunc store (of multiple scalars) to shuffle and store.
26445   // First, pack all of the elements in one place. Next, store to memory
26446   // in fewer chunks.
26447   if (St->isTruncatingStore() && VT.isVector()) {
26448     // Check if we can detect an AVG pattern from the truncation. If yes,
26449     // replace the trunc store by a normal store with the result of X86ISD::AVG
26450     // instruction.
26451     SDValue Avg =
26452         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26453     if (Avg.getNode())
26454       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26455                           St->getPointerInfo(), St->isVolatile(),
26456                           St->isNonTemporal(), St->getAlignment());
26457
26458     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26459     unsigned NumElems = VT.getVectorNumElements();
26460     assert(StVT != VT && "Cannot truncate to the same type");
26461     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26462     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26463
26464     // The truncating store is legal in some cases. For example
26465     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26466     // are designated for truncate store.
26467     // In this case we don't need any further transformations.
26468     if (TLI.isTruncStoreLegal(VT, StVT))
26469       return SDValue();
26470
26471     // From, To sizes and ElemCount must be pow of two
26472     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26473     // We are going to use the original vector elt for storing.
26474     // Accumulated smaller vector elements must be a multiple of the store size.
26475     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26476
26477     unsigned SizeRatio  = FromSz / ToSz;
26478
26479     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26480
26481     // Create a type on which we perform the shuffle
26482     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26483             StVT.getScalarType(), NumElems*SizeRatio);
26484
26485     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26486
26487     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26488     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26489     for (unsigned i = 0; i != NumElems; ++i)
26490       ShuffleVec[i] = i * SizeRatio;
26491
26492     // Can't shuffle using an illegal type.
26493     if (!TLI.isTypeLegal(WideVecVT))
26494       return SDValue();
26495
26496     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26497                                          DAG.getUNDEF(WideVecVT),
26498                                          &ShuffleVec[0]);
26499     // At this point all of the data is stored at the bottom of the
26500     // register. We now need to save it to mem.
26501
26502     // Find the largest store unit
26503     MVT StoreType = MVT::i8;
26504     for (MVT Tp : MVT::integer_valuetypes()) {
26505       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26506         StoreType = Tp;
26507     }
26508
26509     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26510     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26511         (64 <= NumElems * ToSz))
26512       StoreType = MVT::f64;
26513
26514     // Bitcast the original vector into a vector of store-size units
26515     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26516             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26517     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26518     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26519     SmallVector<SDValue, 8> Chains;
26520     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26521                                         TLI.getPointerTy(DAG.getDataLayout()));
26522     SDValue Ptr = St->getBasePtr();
26523
26524     // Perform one or more big stores into memory.
26525     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26526       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26527                                    StoreType, ShuffWide,
26528                                    DAG.getIntPtrConstant(i, dl));
26529       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26530                                 St->getPointerInfo(), St->isVolatile(),
26531                                 St->isNonTemporal(), St->getAlignment());
26532       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26533       Chains.push_back(Ch);
26534     }
26535
26536     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26537   }
26538
26539   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
26540   // the FP state in cases where an emms may be missing.
26541   // A preferable solution to the general problem is to figure out the right
26542   // places to insert EMMS.  This qualifies as a quick hack.
26543
26544   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26545   if (VT.getSizeInBits() != 64)
26546     return SDValue();
26547
26548   const Function *F = DAG.getMachineFunction().getFunction();
26549   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26550   bool F64IsLegal =
26551       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26552   if ((VT.isVector() ||
26553        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26554       isa<LoadSDNode>(St->getValue()) &&
26555       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26556       St->getChain().hasOneUse() && !St->isVolatile()) {
26557     SDNode* LdVal = St->getValue().getNode();
26558     LoadSDNode *Ld = nullptr;
26559     int TokenFactorIndex = -1;
26560     SmallVector<SDValue, 8> Ops;
26561     SDNode* ChainVal = St->getChain().getNode();
26562     // Must be a store of a load.  We currently handle two cases:  the load
26563     // is a direct child, and it's under an intervening TokenFactor.  It is
26564     // possible to dig deeper under nested TokenFactors.
26565     if (ChainVal == LdVal)
26566       Ld = cast<LoadSDNode>(St->getChain());
26567     else if (St->getValue().hasOneUse() &&
26568              ChainVal->getOpcode() == ISD::TokenFactor) {
26569       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26570         if (ChainVal->getOperand(i).getNode() == LdVal) {
26571           TokenFactorIndex = i;
26572           Ld = cast<LoadSDNode>(St->getValue());
26573         } else
26574           Ops.push_back(ChainVal->getOperand(i));
26575       }
26576     }
26577
26578     if (!Ld || !ISD::isNormalLoad(Ld))
26579       return SDValue();
26580
26581     // If this is not the MMX case, i.e. we are just turning i64 load/store
26582     // into f64 load/store, avoid the transformation if there are multiple
26583     // uses of the loaded value.
26584     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26585       return SDValue();
26586
26587     SDLoc LdDL(Ld);
26588     SDLoc StDL(N);
26589     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26590     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26591     // pair instead.
26592     if (Subtarget->is64Bit() || F64IsLegal) {
26593       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26594       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26595                                   Ld->getPointerInfo(), Ld->isVolatile(),
26596                                   Ld->isNonTemporal(), Ld->isInvariant(),
26597                                   Ld->getAlignment());
26598       SDValue NewChain = NewLd.getValue(1);
26599       if (TokenFactorIndex != -1) {
26600         Ops.push_back(NewChain);
26601         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26602       }
26603       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26604                           St->getPointerInfo(),
26605                           St->isVolatile(), St->isNonTemporal(),
26606                           St->getAlignment());
26607     }
26608
26609     // Otherwise, lower to two pairs of 32-bit loads / stores.
26610     SDValue LoAddr = Ld->getBasePtr();
26611     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26612                                  DAG.getConstant(4, LdDL, MVT::i32));
26613
26614     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26615                                Ld->getPointerInfo(),
26616                                Ld->isVolatile(), Ld->isNonTemporal(),
26617                                Ld->isInvariant(), Ld->getAlignment());
26618     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26619                                Ld->getPointerInfo().getWithOffset(4),
26620                                Ld->isVolatile(), Ld->isNonTemporal(),
26621                                Ld->isInvariant(),
26622                                MinAlign(Ld->getAlignment(), 4));
26623
26624     SDValue NewChain = LoLd.getValue(1);
26625     if (TokenFactorIndex != -1) {
26626       Ops.push_back(LoLd);
26627       Ops.push_back(HiLd);
26628       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26629     }
26630
26631     LoAddr = St->getBasePtr();
26632     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26633                          DAG.getConstant(4, StDL, MVT::i32));
26634
26635     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26636                                 St->getPointerInfo(),
26637                                 St->isVolatile(), St->isNonTemporal(),
26638                                 St->getAlignment());
26639     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26640                                 St->getPointerInfo().getWithOffset(4),
26641                                 St->isVolatile(),
26642                                 St->isNonTemporal(),
26643                                 MinAlign(St->getAlignment(), 4));
26644     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26645   }
26646
26647   // This is similar to the above case, but here we handle a scalar 64-bit
26648   // integer store that is extracted from a vector on a 32-bit target.
26649   // If we have SSE2, then we can treat it like a floating-point double
26650   // to get past legalization. The execution dependencies fixup pass will
26651   // choose the optimal machine instruction for the store if this really is
26652   // an integer or v2f32 rather than an f64.
26653   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26654       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26655     SDValue OldExtract = St->getOperand(1);
26656     SDValue ExtOp0 = OldExtract.getOperand(0);
26657     unsigned VecSize = ExtOp0.getValueSizeInBits();
26658     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26659     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26660     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26661                                      BitCast, OldExtract.getOperand(1));
26662     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26663                         St->getPointerInfo(), St->isVolatile(),
26664                         St->isNonTemporal(), St->getAlignment());
26665   }
26666
26667   return SDValue();
26668 }
26669
26670 /// Return 'true' if this vector operation is "horizontal"
26671 /// and return the operands for the horizontal operation in LHS and RHS.  A
26672 /// horizontal operation performs the binary operation on successive elements
26673 /// of its first operand, then on successive elements of its second operand,
26674 /// returning the resulting values in a vector.  For example, if
26675 ///   A = < float a0, float a1, float a2, float a3 >
26676 /// and
26677 ///   B = < float b0, float b1, float b2, float b3 >
26678 /// then the result of doing a horizontal operation on A and B is
26679 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26680 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26681 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26682 /// set to A, RHS to B, and the routine returns 'true'.
26683 /// Note that the binary operation should have the property that if one of the
26684 /// operands is UNDEF then the result is UNDEF.
26685 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26686   // Look for the following pattern: if
26687   //   A = < float a0, float a1, float a2, float a3 >
26688   //   B = < float b0, float b1, float b2, float b3 >
26689   // and
26690   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26691   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26692   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26693   // which is A horizontal-op B.
26694
26695   // At least one of the operands should be a vector shuffle.
26696   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26697       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26698     return false;
26699
26700   MVT VT = LHS.getSimpleValueType();
26701
26702   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26703          "Unsupported vector type for horizontal add/sub");
26704
26705   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26706   // operate independently on 128-bit lanes.
26707   unsigned NumElts = VT.getVectorNumElements();
26708   unsigned NumLanes = VT.getSizeInBits()/128;
26709   unsigned NumLaneElts = NumElts / NumLanes;
26710   assert((NumLaneElts % 2 == 0) &&
26711          "Vector type should have an even number of elements in each lane");
26712   unsigned HalfLaneElts = NumLaneElts/2;
26713
26714   // View LHS in the form
26715   //   LHS = VECTOR_SHUFFLE A, B, LMask
26716   // If LHS is not a shuffle then pretend it is the shuffle
26717   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26718   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26719   // type VT.
26720   SDValue A, B;
26721   SmallVector<int, 16> LMask(NumElts);
26722   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26723     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26724       A = LHS.getOperand(0);
26725     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26726       B = LHS.getOperand(1);
26727     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26728     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26729   } else {
26730     if (LHS.getOpcode() != ISD::UNDEF)
26731       A = LHS;
26732     for (unsigned i = 0; i != NumElts; ++i)
26733       LMask[i] = i;
26734   }
26735
26736   // Likewise, view RHS in the form
26737   //   RHS = VECTOR_SHUFFLE C, D, RMask
26738   SDValue C, D;
26739   SmallVector<int, 16> RMask(NumElts);
26740   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26741     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26742       C = RHS.getOperand(0);
26743     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26744       D = RHS.getOperand(1);
26745     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26746     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26747   } else {
26748     if (RHS.getOpcode() != ISD::UNDEF)
26749       C = RHS;
26750     for (unsigned i = 0; i != NumElts; ++i)
26751       RMask[i] = i;
26752   }
26753
26754   // Check that the shuffles are both shuffling the same vectors.
26755   if (!(A == C && B == D) && !(A == D && B == C))
26756     return false;
26757
26758   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26759   if (!A.getNode() && !B.getNode())
26760     return false;
26761
26762   // If A and B occur in reverse order in RHS, then "swap" them (which means
26763   // rewriting the mask).
26764   if (A != C)
26765     ShuffleVectorSDNode::commuteMask(RMask);
26766
26767   // At this point LHS and RHS are equivalent to
26768   //   LHS = VECTOR_SHUFFLE A, B, LMask
26769   //   RHS = VECTOR_SHUFFLE A, B, RMask
26770   // Check that the masks correspond to performing a horizontal operation.
26771   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26772     for (unsigned i = 0; i != NumLaneElts; ++i) {
26773       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26774
26775       // Ignore any UNDEF components.
26776       if (LIdx < 0 || RIdx < 0 ||
26777           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26778           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26779         continue;
26780
26781       // Check that successive elements are being operated on.  If not, this is
26782       // not a horizontal operation.
26783       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26784       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26785       if (!(LIdx == Index && RIdx == Index + 1) &&
26786           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26787         return false;
26788     }
26789   }
26790
26791   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26792   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26793   return true;
26794 }
26795
26796 /// Do target-specific dag combines on floating point adds.
26797 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26798                                   const X86Subtarget *Subtarget) {
26799   EVT VT = N->getValueType(0);
26800   SDValue LHS = N->getOperand(0);
26801   SDValue RHS = N->getOperand(1);
26802
26803   // Try to synthesize horizontal adds from adds of shuffles.
26804   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26805        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26806       isHorizontalBinOp(LHS, RHS, true))
26807     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26808   return SDValue();
26809 }
26810
26811 /// Do target-specific dag combines on floating point subs.
26812 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26813                                   const X86Subtarget *Subtarget) {
26814   EVT VT = N->getValueType(0);
26815   SDValue LHS = N->getOperand(0);
26816   SDValue RHS = N->getOperand(1);
26817
26818   // Try to synthesize horizontal subs from subs of shuffles.
26819   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26820        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26821       isHorizontalBinOp(LHS, RHS, false))
26822     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26823   return SDValue();
26824 }
26825
26826 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26827 static SDValue
26828 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26829                                   SmallVector<SDValue, 8> &Regs) {
26830   assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26831                              Regs[0].getValueType() == MVT::v2i64));
26832   EVT OutVT = N->getValueType(0);
26833   EVT OutSVT = OutVT.getVectorElementType();
26834   EVT InVT = Regs[0].getValueType();
26835   EVT InSVT = InVT.getVectorElementType();
26836   SDLoc DL(N);
26837
26838   // First, use mask to unset all bits that won't appear in the result.
26839   assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26840          "OutSVT can only be either i8 or i16.");
26841   SDValue MaskVal =
26842       DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26843   SDValue MaskVec = DAG.getNode(
26844       ISD::BUILD_VECTOR, DL, InVT,
26845       SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26846   for (auto &Reg : Regs)
26847     Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26848
26849   MVT UnpackedVT, PackedVT;
26850   if (OutSVT == MVT::i8) {
26851     UnpackedVT = MVT::v8i16;
26852     PackedVT = MVT::v16i8;
26853   } else {
26854     UnpackedVT = MVT::v4i32;
26855     PackedVT = MVT::v8i16;
26856   }
26857
26858   // In each iteration, truncate the type by a half size.
26859   auto RegNum = Regs.size();
26860   for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26861        j < e; j *= 2, RegNum /= 2) {
26862     for (unsigned i = 0; i < RegNum; i++)
26863       Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26864     for (unsigned i = 0; i < RegNum / 2; i++)
26865       Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26866                             Regs[i * 2 + 1]);
26867   }
26868
26869   // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26870   // then extract a subvector as the result since v8i8 is not a legal type.
26871   if (OutVT == MVT::v8i8) {
26872     Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26873     Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26874                           DAG.getIntPtrConstant(0, DL));
26875     return Regs[0];
26876   } else if (RegNum > 1) {
26877     Regs.resize(RegNum);
26878     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26879   } else
26880     return Regs[0];
26881 }
26882
26883 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26884 static SDValue
26885 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26886                                   SmallVector<SDValue, 8> &Regs) {
26887   assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26888   EVT OutVT = N->getValueType(0);
26889   SDLoc DL(N);
26890
26891   // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26892   SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26893   for (auto &Reg : Regs) {
26894     Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26895     Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26896   }
26897
26898   for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26899     Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26900                           Regs[i * 2 + 1]);
26901
26902   if (Regs.size() > 2) {
26903     Regs.resize(Regs.size() / 2);
26904     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26905   } else
26906     return Regs[0];
26907 }
26908
26909 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26910 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26911 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26912 /// element that is extracted from a vector and then truncated, and it is
26913 /// diffcult to do this optimization based on them.
26914 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26915                                        const X86Subtarget *Subtarget) {
26916   EVT OutVT = N->getValueType(0);
26917   if (!OutVT.isVector())
26918     return SDValue();
26919
26920   SDValue In = N->getOperand(0);
26921   if (!In.getValueType().isSimple())
26922     return SDValue();
26923
26924   EVT InVT = In.getValueType();
26925   unsigned NumElems = OutVT.getVectorNumElements();
26926
26927   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26928   // SSE2, and we need to take care of it specially.
26929   // AVX512 provides vpmovdb.
26930   if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26931     return SDValue();
26932
26933   EVT OutSVT = OutVT.getVectorElementType();
26934   EVT InSVT = InVT.getVectorElementType();
26935   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26936         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26937         NumElems >= 8))
26938     return SDValue();
26939
26940   // SSSE3's pshufb results in less instructions in the cases below.
26941   if (Subtarget->hasSSSE3() && NumElems == 8 &&
26942       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26943        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26944     return SDValue();
26945
26946   SDLoc DL(N);
26947
26948   // Split a long vector into vectors of legal type.
26949   unsigned RegNum = InVT.getSizeInBits() / 128;
26950   SmallVector<SDValue, 8> SubVec(RegNum);
26951   if (InSVT == MVT::i32) {
26952     for (unsigned i = 0; i < RegNum; i++)
26953       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26954                               DAG.getIntPtrConstant(i * 4, DL));
26955   } else {
26956     for (unsigned i = 0; i < RegNum; i++)
26957       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
26958                               DAG.getIntPtrConstant(i * 2, DL));
26959   }
26960
26961   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
26962   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
26963   // truncate 2 x v4i32 to v8i16.
26964   if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
26965     return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
26966   else if (InSVT == MVT::i32)
26967     return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
26968   else
26969     return SDValue();
26970 }
26971
26972 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
26973                                       const X86Subtarget *Subtarget) {
26974   // Try to detect AVG pattern first.
26975   SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
26976                                  Subtarget, SDLoc(N));
26977   if (Avg.getNode())
26978     return Avg;
26979
26980   return combineVectorTruncation(N, DAG, Subtarget);
26981 }
26982
26983 /// Do target-specific dag combines on floating point negations.
26984 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26985                                   const X86Subtarget *Subtarget) {
26986   EVT VT = N->getValueType(0);
26987   EVT SVT = VT.getScalarType();
26988   SDValue Arg = N->getOperand(0);
26989   SDLoc DL(N);
26990
26991   // Let legalize expand this if it isn't a legal type yet.
26992   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26993     return SDValue();
26994
26995   // If we're negating a FMUL node on a target with FMA, then we can avoid the
26996   // use of a constant by performing (-0 - A*B) instead.
26997   // FIXME: Check rounding control flags as well once it becomes available.
26998   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
26999       Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
27000     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
27001     return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27002                        Arg.getOperand(1), Zero);
27003   }
27004
27005   // If we're negating a FMA node, then we can adjust the
27006   // instruction to include the extra negation.
27007   if (Arg.hasOneUse()) {
27008     switch (Arg.getOpcode()) {
27009     case X86ISD::FMADD:
27010       return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27011                          Arg.getOperand(1), Arg.getOperand(2));
27012     case X86ISD::FMSUB:
27013       return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
27014                          Arg.getOperand(1), Arg.getOperand(2));
27015     case X86ISD::FNMADD:
27016       return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
27017                          Arg.getOperand(1), Arg.getOperand(2));
27018     case X86ISD::FNMSUB:
27019       return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
27020                          Arg.getOperand(1), Arg.getOperand(2));
27021     }
27022   }
27023   return SDValue();
27024 }
27025
27026 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
27027                               const X86Subtarget *Subtarget) {
27028   EVT VT = N->getValueType(0);
27029   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
27030     // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
27031     // These logic operations may be executed in the integer domain.
27032     SDLoc dl(N);
27033     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
27034     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
27035
27036     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
27037     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
27038     unsigned IntOpcode = 0;
27039     switch (N->getOpcode()) {
27040       default: llvm_unreachable("Unexpected FP logic op");
27041       case X86ISD::FOR: IntOpcode = ISD::OR; break;
27042       case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
27043       case X86ISD::FAND: IntOpcode = ISD::AND; break;
27044       case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
27045     }
27046     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
27047     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
27048   }
27049   return SDValue();
27050 }
27051 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
27052 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
27053                                  const X86Subtarget *Subtarget) {
27054   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27055
27056   // F[X]OR(0.0, x) -> x
27057   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27058     if (C->getValueAPF().isPosZero())
27059       return N->getOperand(1);
27060
27061   // F[X]OR(x, 0.0) -> x
27062   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27063     if (C->getValueAPF().isPosZero())
27064       return N->getOperand(0);
27065
27066   return lowerX86FPLogicOp(N, DAG, Subtarget);
27067 }
27068
27069 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27070 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27071   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27072
27073   // Only perform optimizations if UnsafeMath is used.
27074   if (!DAG.getTarget().Options.UnsafeFPMath)
27075     return SDValue();
27076
27077   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27078   // into FMINC and FMAXC, which are Commutative operations.
27079   unsigned NewOp = 0;
27080   switch (N->getOpcode()) {
27081     default: llvm_unreachable("unknown opcode");
27082     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
27083     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
27084   }
27085
27086   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27087                      N->getOperand(0), N->getOperand(1));
27088 }
27089
27090 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27091                                             const X86Subtarget *Subtarget) {
27092   if (Subtarget->useSoftFloat())
27093     return SDValue();
27094
27095   // TODO: Check for global or instruction-level "nnan". In that case, we
27096   //       should be able to lower to FMAX/FMIN alone.
27097   // TODO: If an operand is already known to be a NaN or not a NaN, this
27098   //       should be an optional swap and FMAX/FMIN.
27099
27100   EVT VT = N->getValueType(0);
27101   if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27102         (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27103         (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27104     return SDValue();
27105
27106   // This takes at least 3 instructions, so favor a library call when operating
27107   // on a scalar and minimizing code size.
27108   if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27109     return SDValue();
27110
27111   SDValue Op0 = N->getOperand(0);
27112   SDValue Op1 = N->getOperand(1);
27113   SDLoc DL(N);
27114   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27115       DAG.getDataLayout(), *DAG.getContext(), VT);
27116
27117   // There are 4 possibilities involving NaN inputs, and these are the required
27118   // outputs:
27119   //                   Op1
27120   //               Num     NaN
27121   //            ----------------
27122   //       Num  |  Max  |  Op0 |
27123   // Op0        ----------------
27124   //       NaN  |  Op1  |  NaN |
27125   //            ----------------
27126   //
27127   // The SSE FP max/min instructions were not designed for this case, but rather
27128   // to implement:
27129   //   Min = Op1 < Op0 ? Op1 : Op0
27130   //   Max = Op1 > Op0 ? Op1 : Op0
27131   //
27132   // So they always return Op0 if either input is a NaN. However, we can still
27133   // use those instructions for fmaxnum by selecting away a NaN input.
27134
27135   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27136   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27137   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27138   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27139
27140   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27141   // are NaN, the NaN value of Op1 is the result.
27142   auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27143   return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27144 }
27145
27146 /// Do target-specific dag combines on X86ISD::FAND nodes.
27147 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27148                                   const X86Subtarget *Subtarget) {
27149   // FAND(0.0, x) -> 0.0
27150   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27151     if (C->getValueAPF().isPosZero())
27152       return N->getOperand(0);
27153
27154   // FAND(x, 0.0) -> 0.0
27155   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27156     if (C->getValueAPF().isPosZero())
27157       return N->getOperand(1);
27158
27159   return lowerX86FPLogicOp(N, DAG, Subtarget);
27160 }
27161
27162 /// Do target-specific dag combines on X86ISD::FANDN nodes
27163 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27164                                    const X86Subtarget *Subtarget) {
27165   // FANDN(0.0, x) -> x
27166   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27167     if (C->getValueAPF().isPosZero())
27168       return N->getOperand(1);
27169
27170   // FANDN(x, 0.0) -> 0.0
27171   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27172     if (C->getValueAPF().isPosZero())
27173       return N->getOperand(1);
27174
27175   return lowerX86FPLogicOp(N, DAG, Subtarget);
27176 }
27177
27178 static SDValue PerformBTCombine(SDNode *N,
27179                                 SelectionDAG &DAG,
27180                                 TargetLowering::DAGCombinerInfo &DCI) {
27181   // BT ignores high bits in the bit index operand.
27182   SDValue Op1 = N->getOperand(1);
27183   if (Op1.hasOneUse()) {
27184     unsigned BitWidth = Op1.getValueSizeInBits();
27185     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27186     APInt KnownZero, KnownOne;
27187     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27188                                           !DCI.isBeforeLegalizeOps());
27189     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27190     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27191         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27192       DCI.CommitTargetLoweringOpt(TLO);
27193   }
27194   return SDValue();
27195 }
27196
27197 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27198   SDValue Op = N->getOperand(0);
27199   if (Op.getOpcode() == ISD::BITCAST)
27200     Op = Op.getOperand(0);
27201   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27202   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27203       VT.getVectorElementType().getSizeInBits() ==
27204       OpVT.getVectorElementType().getSizeInBits()) {
27205     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27206   }
27207   return SDValue();
27208 }
27209
27210 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27211                                                const X86Subtarget *Subtarget) {
27212   EVT VT = N->getValueType(0);
27213   if (!VT.isVector())
27214     return SDValue();
27215
27216   SDValue N0 = N->getOperand(0);
27217   SDValue N1 = N->getOperand(1);
27218   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27219   SDLoc dl(N);
27220
27221   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27222   // both SSE and AVX2 since there is no sign-extended shift right
27223   // operation on a vector with 64-bit elements.
27224   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27225   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27226   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27227       N0.getOpcode() == ISD::SIGN_EXTEND)) {
27228     SDValue N00 = N0.getOperand(0);
27229
27230     // EXTLOAD has a better solution on AVX2,
27231     // it may be replaced with X86ISD::VSEXT node.
27232     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27233       if (!ISD::isNormalLoad(N00.getNode()))
27234         return SDValue();
27235
27236     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27237         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27238                                   N00, N1);
27239       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27240     }
27241   }
27242   return SDValue();
27243 }
27244
27245 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27246 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27247 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27248 /// eliminate extend, add, and shift instructions.
27249 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27250                                        const X86Subtarget *Subtarget) {
27251   // TODO: This should be valid for other integer types.
27252   EVT VT = Sext->getValueType(0);
27253   if (VT != MVT::i64)
27254     return SDValue();
27255
27256   // We need an 'add nsw' feeding into the 'sext'.
27257   SDValue Add = Sext->getOperand(0);
27258   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27259     return SDValue();
27260
27261   // Having a constant operand to the 'add' ensures that we are not increasing
27262   // the instruction count because the constant is extended for free below.
27263   // A constant operand can also become the displacement field of an LEA.
27264   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27265   if (!AddOp1)
27266     return SDValue();
27267
27268   // Don't make the 'add' bigger if there's no hope of combining it with some
27269   // other 'add' or 'shl' instruction.
27270   // TODO: It may be profitable to generate simpler LEA instructions in place
27271   // of single 'add' instructions, but the cost model for selecting an LEA
27272   // currently has a high threshold.
27273   bool HasLEAPotential = false;
27274   for (auto *User : Sext->uses()) {
27275     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27276       HasLEAPotential = true;
27277       break;
27278     }
27279   }
27280   if (!HasLEAPotential)
27281     return SDValue();
27282
27283   // Everything looks good, so pull the 'sext' ahead of the 'add'.
27284   int64_t AddConstant = AddOp1->getSExtValue();
27285   SDValue AddOp0 = Add.getOperand(0);
27286   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27287   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27288
27289   // The wider add is guaranteed to not wrap because both operands are
27290   // sign-extended.
27291   SDNodeFlags Flags;
27292   Flags.setNoSignedWrap(true);
27293   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27294 }
27295
27296 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
27297 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
27298 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
27299 /// extends from AH (which we otherwise need to do contortions to access).
27300 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
27301   SDValue N0 = N->getOperand(0);
27302   auto OpcodeN = N->getOpcode();
27303   auto OpcodeN0 = N0.getOpcode();
27304   if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
27305         (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
27306     return SDValue();
27307
27308   EVT VT = N->getValueType(0);
27309   EVT InVT = N0.getValueType();
27310   if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
27311     return SDValue();
27312
27313   SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27314   auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
27315                                                : X86ISD::UDIVREM8_ZEXT_HREG;
27316   SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
27317                           N0.getOperand(1));
27318   DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27319   return R.getValue(1);
27320 }
27321
27322 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27323                                   TargetLowering::DAGCombinerInfo &DCI,
27324                                   const X86Subtarget *Subtarget) {
27325   SDValue N0 = N->getOperand(0);
27326   EVT VT = N->getValueType(0);
27327   EVT SVT = VT.getScalarType();
27328   EVT InVT = N0.getValueType();
27329   EVT InSVT = InVT.getScalarType();
27330   SDLoc DL(N);
27331
27332   if (SDValue DivRem8 = getDivRem8(N, DAG))
27333     return DivRem8;
27334
27335   if (!DCI.isBeforeLegalizeOps()) {
27336     if (InVT == MVT::i1) {
27337       SDValue Zero = DAG.getConstant(0, DL, VT);
27338       SDValue AllOnes =
27339         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27340       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27341     }
27342     return SDValue();
27343   }
27344
27345   if (VT.isVector() && Subtarget->hasSSE2()) {
27346     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27347       EVT InVT = N.getValueType();
27348       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27349                                    Size / InVT.getScalarSizeInBits());
27350       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27351                                     DAG.getUNDEF(InVT));
27352       Opnds[0] = N;
27353       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27354     };
27355
27356     // If target-size is less than 128-bits, extend to a type that would extend
27357     // to 128 bits, extend that and extract the original target vector.
27358     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27359         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27360         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27361       unsigned Scale = 128 / VT.getSizeInBits();
27362       EVT ExVT =
27363           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27364       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27365       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27366       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27367                          DAG.getIntPtrConstant(0, DL));
27368     }
27369
27370     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27371     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27372     if (VT.getSizeInBits() == 128 &&
27373         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27374         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27375       SDValue ExOp = ExtendVecSize(DL, N0, 128);
27376       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27377     }
27378
27379     // On pre-AVX2 targets, split into 128-bit nodes of
27380     // ISD::SIGN_EXTEND_VECTOR_INREG.
27381     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27382         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27383         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27384       unsigned NumVecs = VT.getSizeInBits() / 128;
27385       unsigned NumSubElts = 128 / SVT.getSizeInBits();
27386       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27387       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27388
27389       SmallVector<SDValue, 8> Opnds;
27390       for (unsigned i = 0, Offset = 0; i != NumVecs;
27391            ++i, Offset += NumSubElts) {
27392         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27393                                      DAG.getIntPtrConstant(Offset, DL));
27394         SrcVec = ExtendVecSize(DL, SrcVec, 128);
27395         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27396         Opnds.push_back(SrcVec);
27397       }
27398       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27399     }
27400   }
27401
27402   if (Subtarget->hasAVX() && VT.is256BitVector())
27403     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27404       return R;
27405
27406   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27407     return NewAdd;
27408
27409   return SDValue();
27410 }
27411
27412 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27413                                  const X86Subtarget* Subtarget) {
27414   SDLoc dl(N);
27415   EVT VT = N->getValueType(0);
27416
27417   // Let legalize expand this if it isn't a legal type yet.
27418   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27419     return SDValue();
27420
27421   EVT ScalarVT = VT.getScalarType();
27422   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27423     return SDValue();
27424
27425   SDValue A = N->getOperand(0);
27426   SDValue B = N->getOperand(1);
27427   SDValue C = N->getOperand(2);
27428
27429   bool NegA = (A.getOpcode() == ISD::FNEG);
27430   bool NegB = (B.getOpcode() == ISD::FNEG);
27431   bool NegC = (C.getOpcode() == ISD::FNEG);
27432
27433   // Negative multiplication when NegA xor NegB
27434   bool NegMul = (NegA != NegB);
27435   if (NegA)
27436     A = A.getOperand(0);
27437   if (NegB)
27438     B = B.getOperand(0);
27439   if (NegC)
27440     C = C.getOperand(0);
27441
27442   unsigned Opcode;
27443   if (!NegMul)
27444     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27445   else
27446     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27447
27448   return DAG.getNode(Opcode, dl, VT, A, B, C);
27449 }
27450
27451 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27452                                   TargetLowering::DAGCombinerInfo &DCI,
27453                                   const X86Subtarget *Subtarget) {
27454   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
27455   //           (and (i32 x86isd::setcc_carry), 1)
27456   // This eliminates the zext. This transformation is necessary because
27457   // ISD::SETCC is always legalized to i8.
27458   SDLoc dl(N);
27459   SDValue N0 = N->getOperand(0);
27460   EVT VT = N->getValueType(0);
27461
27462   if (N0.getOpcode() == ISD::AND &&
27463       N0.hasOneUse() &&
27464       N0.getOperand(0).hasOneUse()) {
27465     SDValue N00 = N0.getOperand(0);
27466     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27467       if (!isOneConstant(N0.getOperand(1)))
27468         return SDValue();
27469       return DAG.getNode(ISD::AND, dl, VT,
27470                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27471                                      N00.getOperand(0), N00.getOperand(1)),
27472                          DAG.getConstant(1, dl, VT));
27473     }
27474   }
27475
27476   if (N0.getOpcode() == ISD::TRUNCATE &&
27477       N0.hasOneUse() &&
27478       N0.getOperand(0).hasOneUse()) {
27479     SDValue N00 = N0.getOperand(0);
27480     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
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 (VT.is256BitVector())
27489     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27490       return R;
27491
27492   if (SDValue DivRem8 = getDivRem8(N, DAG))
27493     return DivRem8;
27494
27495   return SDValue();
27496 }
27497
27498 // Optimize x == -y --> x+y == 0
27499 //          x != -y --> x+y != 0
27500 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27501                                       const X86Subtarget* Subtarget) {
27502   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27503   SDValue LHS = N->getOperand(0);
27504   SDValue RHS = N->getOperand(1);
27505   EVT VT = N->getValueType(0);
27506   SDLoc DL(N);
27507
27508   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27509     if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27510       SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27511                                  LHS.getOperand(1));
27512       return DAG.getSetCC(DL, N->getValueType(0), addV,
27513                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27514     }
27515   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27516     if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27517       SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27518                                  RHS.getOperand(1));
27519       return DAG.getSetCC(DL, N->getValueType(0), addV,
27520                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27521     }
27522
27523   if (VT.getScalarType() == MVT::i1 &&
27524       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27525     bool IsSEXT0 =
27526         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27527         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27528     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27529
27530     if (!IsSEXT0 || !IsVZero1) {
27531       // Swap the operands and update the condition code.
27532       std::swap(LHS, RHS);
27533       CC = ISD::getSetCCSwappedOperands(CC);
27534
27535       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27536                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27537       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27538     }
27539
27540     if (IsSEXT0 && IsVZero1) {
27541       assert(VT == LHS.getOperand(0).getValueType() &&
27542              "Uexpected operand type");
27543       if (CC == ISD::SETGT)
27544         return DAG.getConstant(0, DL, VT);
27545       if (CC == ISD::SETLE)
27546         return DAG.getConstant(1, DL, VT);
27547       if (CC == ISD::SETEQ || CC == ISD::SETGE)
27548         return DAG.getNOT(DL, LHS.getOperand(0), VT);
27549
27550       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27551              "Unexpected condition code!");
27552       return LHS.getOperand(0);
27553     }
27554   }
27555
27556   return SDValue();
27557 }
27558
27559 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27560   SDLoc DL(N);
27561   // Gather and Scatter instructions use k-registers for masks. The type of
27562   // the masks is v*i1. So the mask will be truncated anyway.
27563   // The SIGN_EXTEND_INREG my be dropped.
27564   SDValue Mask = N->getOperand(2);
27565   if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27566     SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27567     NewOps[2] = Mask.getOperand(0);
27568     DAG.UpdateNodeOperands(N, NewOps);
27569   }
27570   return SDValue();
27571 }
27572
27573 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27574 // as "sbb reg,reg", since it can be extended without zext and produces
27575 // an all-ones bit which is more useful than 0/1 in some cases.
27576 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27577                                MVT VT) {
27578   if (VT == MVT::i8)
27579     return DAG.getNode(ISD::AND, DL, VT,
27580                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27581                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
27582                                    EFLAGS),
27583                        DAG.getConstant(1, DL, VT));
27584   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27585   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27586                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27587                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
27588                                  EFLAGS));
27589 }
27590
27591 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27592 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27593                                    TargetLowering::DAGCombinerInfo &DCI,
27594                                    const X86Subtarget *Subtarget) {
27595   SDLoc DL(N);
27596   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27597   SDValue EFLAGS = N->getOperand(1);
27598
27599   if (CC == X86::COND_A) {
27600     // Try to convert COND_A into COND_B in an attempt to facilitate
27601     // materializing "setb reg".
27602     //
27603     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27604     // cannot take an immediate as its first operand.
27605     //
27606     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27607         EFLAGS.getValueType().isInteger() &&
27608         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27609       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27610                                    EFLAGS.getNode()->getVTList(),
27611                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27612       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27613       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27614     }
27615   }
27616
27617   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27618   // a zext and produces an all-ones bit which is more useful than 0/1 in some
27619   // cases.
27620   if (CC == X86::COND_B)
27621     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27622
27623   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27624     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27625     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27626   }
27627
27628   return SDValue();
27629 }
27630
27631 // Optimize branch condition evaluation.
27632 //
27633 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27634                                     TargetLowering::DAGCombinerInfo &DCI,
27635                                     const X86Subtarget *Subtarget) {
27636   SDLoc DL(N);
27637   SDValue Chain = N->getOperand(0);
27638   SDValue Dest = N->getOperand(1);
27639   SDValue EFLAGS = N->getOperand(3);
27640   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27641
27642   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27643     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27644     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27645                        Flags);
27646   }
27647
27648   return SDValue();
27649 }
27650
27651 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27652                                                          SelectionDAG &DAG) {
27653   // Take advantage of vector comparisons producing 0 or -1 in each lane to
27654   // optimize away operation when it's from a constant.
27655   //
27656   // The general transformation is:
27657   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27658   //       AND(VECTOR_CMP(x,y), constant2)
27659   //    constant2 = UNARYOP(constant)
27660
27661   // Early exit if this isn't a vector operation, the operand of the
27662   // unary operation isn't a bitwise AND, or if the sizes of the operations
27663   // aren't the same.
27664   EVT VT = N->getValueType(0);
27665   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27666       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27667       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27668     return SDValue();
27669
27670   // Now check that the other operand of the AND is a constant. We could
27671   // make the transformation for non-constant splats as well, but it's unclear
27672   // that would be a benefit as it would not eliminate any operations, just
27673   // perform one more step in scalar code before moving to the vector unit.
27674   if (BuildVectorSDNode *BV =
27675           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27676     // Bail out if the vector isn't a constant.
27677     if (!BV->isConstant())
27678       return SDValue();
27679
27680     // Everything checks out. Build up the new and improved node.
27681     SDLoc DL(N);
27682     EVT IntVT = BV->getValueType(0);
27683     // Create a new constant of the appropriate type for the transformed
27684     // DAG.
27685     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27686     // The AND node needs bitcasts to/from an integer vector type around it.
27687     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27688     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27689                                  N->getOperand(0)->getOperand(0), MaskConst);
27690     SDValue Res = DAG.getBitcast(VT, NewAnd);
27691     return Res;
27692   }
27693
27694   return SDValue();
27695 }
27696
27697 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27698                                         const X86Subtarget *Subtarget) {
27699   SDValue Op0 = N->getOperand(0);
27700   EVT VT = N->getValueType(0);
27701   EVT InVT = Op0.getValueType();
27702   EVT InSVT = InVT.getScalarType();
27703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27704
27705   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27706   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27707   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27708     SDLoc dl(N);
27709     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27710                                  InVT.getVectorNumElements());
27711     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27712
27713     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27714       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27715
27716     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27717   }
27718
27719   return SDValue();
27720 }
27721
27722 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27723                                         const X86Subtarget *Subtarget) {
27724   // First try to optimize away the conversion entirely when it's
27725   // conditionally from a constant. Vectors only.
27726   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27727     return Res;
27728
27729   // Now move on to more general possibilities.
27730   SDValue Op0 = N->getOperand(0);
27731   EVT VT = N->getValueType(0);
27732   EVT InVT = Op0.getValueType();
27733   EVT InSVT = InVT.getScalarType();
27734
27735   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27736   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27737   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27738     SDLoc dl(N);
27739     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27740                                  InVT.getVectorNumElements());
27741     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27742     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27743   }
27744
27745   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27746   // a 32-bit target where SSE doesn't support i64->FP operations.
27747   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27748     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27749     EVT LdVT = Ld->getValueType(0);
27750
27751     // This transformation is not supported if the result type is f16
27752     if (VT == MVT::f16)
27753       return SDValue();
27754
27755     if (!Ld->isVolatile() && !VT.isVector() &&
27756         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27757         !Subtarget->is64Bit() && LdVT == MVT::i64) {
27758       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27759           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27760       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27761       return FILDChain;
27762     }
27763   }
27764   return SDValue();
27765 }
27766
27767 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27768 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27769                                  X86TargetLowering::DAGCombinerInfo &DCI) {
27770   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27771   // the result is either zero or one (depending on the input carry bit).
27772   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27773   if (X86::isZeroNode(N->getOperand(0)) &&
27774       X86::isZeroNode(N->getOperand(1)) &&
27775       // We don't have a good way to replace an EFLAGS use, so only do this when
27776       // dead right now.
27777       SDValue(N, 1).use_empty()) {
27778     SDLoc DL(N);
27779     EVT VT = N->getValueType(0);
27780     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27781     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27782                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27783                                            DAG.getConstant(X86::COND_B, DL,
27784                                                            MVT::i8),
27785                                            N->getOperand(2)),
27786                                DAG.getConstant(1, DL, VT));
27787     return DCI.CombineTo(N, Res1, CarryOut);
27788   }
27789
27790   return SDValue();
27791 }
27792
27793 // fold (add Y, (sete  X, 0)) -> adc  0, Y
27794 //      (add Y, (setne X, 0)) -> sbb -1, Y
27795 //      (sub (sete  X, 0), Y) -> sbb  0, Y
27796 //      (sub (setne X, 0), Y) -> adc -1, Y
27797 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27798   SDLoc DL(N);
27799
27800   // Look through ZExts.
27801   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27802   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27803     return SDValue();
27804
27805   SDValue SetCC = Ext.getOperand(0);
27806   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27807     return SDValue();
27808
27809   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27810   if (CC != X86::COND_E && CC != X86::COND_NE)
27811     return SDValue();
27812
27813   SDValue Cmp = SetCC.getOperand(1);
27814   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27815       !X86::isZeroNode(Cmp.getOperand(1)) ||
27816       !Cmp.getOperand(0).getValueType().isInteger())
27817     return SDValue();
27818
27819   SDValue CmpOp0 = Cmp.getOperand(0);
27820   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27821                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
27822
27823   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27824   if (CC == X86::COND_NE)
27825     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27826                        DL, OtherVal.getValueType(), OtherVal,
27827                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27828                        NewCmp);
27829   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27830                      DL, OtherVal.getValueType(), OtherVal,
27831                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27832 }
27833
27834 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27835 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27836                                  const X86Subtarget *Subtarget) {
27837   EVT VT = N->getValueType(0);
27838   SDValue Op0 = N->getOperand(0);
27839   SDValue Op1 = N->getOperand(1);
27840
27841   // Try to synthesize horizontal adds from adds of shuffles.
27842   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27843        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27844       isHorizontalBinOp(Op0, Op1, true))
27845     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27846
27847   return OptimizeConditionalInDecrement(N, DAG);
27848 }
27849
27850 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27851                                  const X86Subtarget *Subtarget) {
27852   SDValue Op0 = N->getOperand(0);
27853   SDValue Op1 = N->getOperand(1);
27854
27855   // X86 can't encode an immediate LHS of a sub. See if we can push the
27856   // negation into a preceding instruction.
27857   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27858     // If the RHS of the sub is a XOR with one use and a constant, invert the
27859     // immediate. Then add one to the LHS of the sub so we can turn
27860     // X-Y -> X+~Y+1, saving one register.
27861     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27862         isa<ConstantSDNode>(Op1.getOperand(1))) {
27863       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27864       EVT VT = Op0.getValueType();
27865       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27866                                    Op1.getOperand(0),
27867                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
27868       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27869                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27870     }
27871   }
27872
27873   // Try to synthesize horizontal adds from adds of shuffles.
27874   EVT VT = N->getValueType(0);
27875   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27876        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27877       isHorizontalBinOp(Op0, Op1, true))
27878     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27879
27880   return OptimizeConditionalInDecrement(N, DAG);
27881 }
27882
27883 /// performVZEXTCombine - Performs build vector combines
27884 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27885                                    TargetLowering::DAGCombinerInfo &DCI,
27886                                    const X86Subtarget *Subtarget) {
27887   SDLoc DL(N);
27888   MVT VT = N->getSimpleValueType(0);
27889   SDValue Op = N->getOperand(0);
27890   MVT OpVT = Op.getSimpleValueType();
27891   MVT OpEltVT = OpVT.getVectorElementType();
27892   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27893
27894   // (vzext (bitcast (vzext (x)) -> (vzext x)
27895   SDValue V = Op;
27896   while (V.getOpcode() == ISD::BITCAST)
27897     V = V.getOperand(0);
27898
27899   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27900     MVT InnerVT = V.getSimpleValueType();
27901     MVT InnerEltVT = InnerVT.getVectorElementType();
27902
27903     // If the element sizes match exactly, we can just do one larger vzext. This
27904     // is always an exact type match as vzext operates on integer types.
27905     if (OpEltVT == InnerEltVT) {
27906       assert(OpVT == InnerVT && "Types must match for vzext!");
27907       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27908     }
27909
27910     // The only other way we can combine them is if only a single element of the
27911     // inner vzext is used in the input to the outer vzext.
27912     if (InnerEltVT.getSizeInBits() < InputBits)
27913       return SDValue();
27914
27915     // In this case, the inner vzext is completely dead because we're going to
27916     // only look at bits inside of the low element. Just do the outer vzext on
27917     // a bitcast of the input to the inner.
27918     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27919   }
27920
27921   // Check if we can bypass extracting and re-inserting an element of an input
27922   // vector. Essentially:
27923   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27924   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27925       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27926       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27927     SDValue ExtractedV = V.getOperand(0);
27928     SDValue OrigV = ExtractedV.getOperand(0);
27929     if (isNullConstant(ExtractedV.getOperand(1))) {
27930         MVT OrigVT = OrigV.getSimpleValueType();
27931         // Extract a subvector if necessary...
27932         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27933           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27934           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27935                                     OrigVT.getVectorNumElements() / Ratio);
27936           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27937                               DAG.getIntPtrConstant(0, DL));
27938         }
27939         Op = DAG.getBitcast(OpVT, OrigV);
27940         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27941       }
27942   }
27943
27944   return SDValue();
27945 }
27946
27947 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27948                                              DAGCombinerInfo &DCI) const {
27949   SelectionDAG &DAG = DCI.DAG;
27950   switch (N->getOpcode()) {
27951   default: break;
27952   case ISD::EXTRACT_VECTOR_ELT:
27953     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27954   case ISD::VSELECT:
27955   case ISD::SELECT:
27956   case X86ISD::SHRUNKBLEND:
27957     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27958   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
27959   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27960   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
27961   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
27962   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
27963   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
27964   case ISD::SHL:
27965   case ISD::SRA:
27966   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
27967   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
27968   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
27969   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
27970   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
27971   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27972   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
27973   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
27974   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27975   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27976   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
27977   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
27978   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
27979   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
27980   case X86ISD::FXOR:
27981   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
27982   case X86ISD::FMIN:
27983   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
27984   case ISD::FMINNUM:
27985   case ISD::FMAXNUM:        return performFMinNumFMaxNumCombine(N, DAG,
27986                                                                 Subtarget);
27987   case X86ISD::FAND:        return PerformFANDCombine(N, DAG, Subtarget);
27988   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG, Subtarget);
27989   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
27990   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
27991   case ISD::ANY_EXTEND:
27992   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
27993   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
27994   case ISD::SIGN_EXTEND_INREG:
27995     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27996   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
27997   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27998   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27999   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
28000   case X86ISD::SHUFP:       // Handle all target specific shuffles
28001   case X86ISD::PALIGNR:
28002   case X86ISD::BLENDI:
28003   case X86ISD::UNPCKH:
28004   case X86ISD::UNPCKL:
28005   case X86ISD::MOVHLPS:
28006   case X86ISD::MOVLHPS:
28007   case X86ISD::PSHUFB:
28008   case X86ISD::PSHUFD:
28009   case X86ISD::PSHUFHW:
28010   case X86ISD::PSHUFLW:
28011   case X86ISD::MOVSS:
28012   case X86ISD::MOVSD:
28013   case X86ISD::VPERMILPI:
28014   case X86ISD::VPERM2X128:
28015   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
28016   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
28017   case ISD::MGATHER:
28018   case ISD::MSCATTER:       return PerformGatherScatterCombine(N, DAG);
28019   }
28020
28021   return SDValue();
28022 }
28023
28024 /// isTypeDesirableForOp - Return true if the target has native support for
28025 /// the specified value type and it is 'desirable' to use the type for the
28026 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
28027 /// instruction encodings are longer and some i16 instructions are slow.
28028 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
28029   if (!isTypeLegal(VT))
28030     return false;
28031   if (VT != MVT::i16)
28032     return true;
28033
28034   switch (Opc) {
28035   default:
28036     return true;
28037   case ISD::LOAD:
28038   case ISD::SIGN_EXTEND:
28039   case ISD::ZERO_EXTEND:
28040   case ISD::ANY_EXTEND:
28041   case ISD::SHL:
28042   case ISD::SRL:
28043   case ISD::SUB:
28044   case ISD::ADD:
28045   case ISD::MUL:
28046   case ISD::AND:
28047   case ISD::OR:
28048   case ISD::XOR:
28049     return false;
28050   }
28051 }
28052
28053 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
28054 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
28055 /// we don't adjust the stack we clobber the first frame index.
28056 /// See X86InstrInfo::copyPhysReg.
28057 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
28058     MachineFunction *MF) const {
28059   const MachineRegisterInfo &MRI = MF->getRegInfo();
28060
28061   return any_of(MRI.reg_instructions(X86::EFLAGS),
28062                 [](const MachineInstr &RI) { return RI.isCopy(); });
28063 }
28064
28065 /// IsDesirableToPromoteOp - This method query the target whether it is
28066 /// beneficial for dag combiner to promote the specified node. If true, it
28067 /// should return the desired promotion type by reference.
28068 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28069   EVT VT = Op.getValueType();
28070   if (VT != MVT::i16)
28071     return false;
28072
28073   bool Promote = false;
28074   bool Commute = false;
28075   switch (Op.getOpcode()) {
28076   default: break;
28077   case ISD::LOAD: {
28078     LoadSDNode *LD = cast<LoadSDNode>(Op);
28079     // If the non-extending load has a single use and it's not live out, then it
28080     // might be folded.
28081     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28082                                                      Op.hasOneUse()*/) {
28083       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28084              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28085         // The only case where we'd want to promote LOAD (rather then it being
28086         // promoted as an operand is when it's only use is liveout.
28087         if (UI->getOpcode() != ISD::CopyToReg)
28088           return false;
28089       }
28090     }
28091     Promote = true;
28092     break;
28093   }
28094   case ISD::SIGN_EXTEND:
28095   case ISD::ZERO_EXTEND:
28096   case ISD::ANY_EXTEND:
28097     Promote = true;
28098     break;
28099   case ISD::SHL:
28100   case ISD::SRL: {
28101     SDValue N0 = Op.getOperand(0);
28102     // Look out for (store (shl (load), x)).
28103     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28104       return false;
28105     Promote = true;
28106     break;
28107   }
28108   case ISD::ADD:
28109   case ISD::MUL:
28110   case ISD::AND:
28111   case ISD::OR:
28112   case ISD::XOR:
28113     Commute = true;
28114     // fallthrough
28115   case ISD::SUB: {
28116     SDValue N0 = Op.getOperand(0);
28117     SDValue N1 = Op.getOperand(1);
28118     if (!Commute && MayFoldLoad(N1))
28119       return false;
28120     // Avoid disabling potential load folding opportunities.
28121     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28122       return false;
28123     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28124       return false;
28125     Promote = true;
28126   }
28127   }
28128
28129   PVT = MVT::i32;
28130   return Promote;
28131 }
28132
28133 //===----------------------------------------------------------------------===//
28134 //                           X86 Inline Assembly Support
28135 //===----------------------------------------------------------------------===//
28136
28137 // Helper to match a string separated by whitespace.
28138 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28139   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28140
28141   for (StringRef Piece : Pieces) {
28142     if (!S.startswith(Piece)) // Check if the piece matches.
28143       return false;
28144
28145     S = S.substr(Piece.size());
28146     StringRef::size_type Pos = S.find_first_not_of(" \t");
28147     if (Pos == 0) // We matched a prefix.
28148       return false;
28149
28150     S = S.substr(Pos);
28151   }
28152
28153   return S.empty();
28154 }
28155
28156 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28157
28158   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28159     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28160         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28161         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28162
28163       if (AsmPieces.size() == 3)
28164         return true;
28165       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28166         return true;
28167     }
28168   }
28169   return false;
28170 }
28171
28172 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28173   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28174
28175   std::string AsmStr = IA->getAsmString();
28176
28177   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28178   if (!Ty || Ty->getBitWidth() % 16 != 0)
28179     return false;
28180
28181   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28182   SmallVector<StringRef, 4> AsmPieces;
28183   SplitString(AsmStr, AsmPieces, ";\n");
28184
28185   switch (AsmPieces.size()) {
28186   default: return false;
28187   case 1:
28188     // FIXME: this should verify that we are targeting a 486 or better.  If not,
28189     // we will turn this bswap into something that will be lowered to logical
28190     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
28191     // lower so don't worry about this.
28192     // bswap $0
28193     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28194         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28195         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28196         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28197         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28198         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28199       // No need to check constraints, nothing other than the equivalent of
28200       // "=r,0" would be valid here.
28201       return IntrinsicLowering::LowerToByteSwap(CI);
28202     }
28203
28204     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
28205     if (CI->getType()->isIntegerTy(16) &&
28206         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28207         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28208          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28209       AsmPieces.clear();
28210       StringRef ConstraintsStr = IA->getConstraintString();
28211       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28212       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28213       if (clobbersFlagRegisters(AsmPieces))
28214         return IntrinsicLowering::LowerToByteSwap(CI);
28215     }
28216     break;
28217   case 3:
28218     if (CI->getType()->isIntegerTy(32) &&
28219         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28220         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28221         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28222         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28223       AsmPieces.clear();
28224       StringRef ConstraintsStr = IA->getConstraintString();
28225       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28226       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28227       if (clobbersFlagRegisters(AsmPieces))
28228         return IntrinsicLowering::LowerToByteSwap(CI);
28229     }
28230
28231     if (CI->getType()->isIntegerTy(64)) {
28232       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28233       if (Constraints.size() >= 2 &&
28234           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28235           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28236         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
28237         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28238             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28239             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28240           return IntrinsicLowering::LowerToByteSwap(CI);
28241       }
28242     }
28243     break;
28244   }
28245   return false;
28246 }
28247
28248 /// getConstraintType - Given a constraint letter, return the type of
28249 /// constraint it is for this target.
28250 X86TargetLowering::ConstraintType
28251 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28252   if (Constraint.size() == 1) {
28253     switch (Constraint[0]) {
28254     case 'R':
28255     case 'q':
28256     case 'Q':
28257     case 'f':
28258     case 't':
28259     case 'u':
28260     case 'y':
28261     case 'x':
28262     case 'Y':
28263     case 'l':
28264       return C_RegisterClass;
28265     case 'a':
28266     case 'b':
28267     case 'c':
28268     case 'd':
28269     case 'S':
28270     case 'D':
28271     case 'A':
28272       return C_Register;
28273     case 'I':
28274     case 'J':
28275     case 'K':
28276     case 'L':
28277     case 'M':
28278     case 'N':
28279     case 'G':
28280     case 'C':
28281     case 'e':
28282     case 'Z':
28283       return C_Other;
28284     default:
28285       break;
28286     }
28287   }
28288   return TargetLowering::getConstraintType(Constraint);
28289 }
28290
28291 /// Examine constraint type and operand type and determine a weight value.
28292 /// This object must already have been set up with the operand type
28293 /// and the current alternative constraint selected.
28294 TargetLowering::ConstraintWeight
28295   X86TargetLowering::getSingleConstraintMatchWeight(
28296     AsmOperandInfo &info, const char *constraint) const {
28297   ConstraintWeight weight = CW_Invalid;
28298   Value *CallOperandVal = info.CallOperandVal;
28299     // If we don't have a value, we can't do a match,
28300     // but allow it at the lowest weight.
28301   if (!CallOperandVal)
28302     return CW_Default;
28303   Type *type = CallOperandVal->getType();
28304   // Look at the constraint type.
28305   switch (*constraint) {
28306   default:
28307     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28308   case 'R':
28309   case 'q':
28310   case 'Q':
28311   case 'a':
28312   case 'b':
28313   case 'c':
28314   case 'd':
28315   case 'S':
28316   case 'D':
28317   case 'A':
28318     if (CallOperandVal->getType()->isIntegerTy())
28319       weight = CW_SpecificReg;
28320     break;
28321   case 'f':
28322   case 't':
28323   case 'u':
28324     if (type->isFloatingPointTy())
28325       weight = CW_SpecificReg;
28326     break;
28327   case 'y':
28328     if (type->isX86_MMXTy() && Subtarget->hasMMX())
28329       weight = CW_SpecificReg;
28330     break;
28331   case 'x':
28332   case 'Y':
28333     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28334         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28335       weight = CW_Register;
28336     break;
28337   case 'I':
28338     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28339       if (C->getZExtValue() <= 31)
28340         weight = CW_Constant;
28341     }
28342     break;
28343   case 'J':
28344     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28345       if (C->getZExtValue() <= 63)
28346         weight = CW_Constant;
28347     }
28348     break;
28349   case 'K':
28350     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28351       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28352         weight = CW_Constant;
28353     }
28354     break;
28355   case 'L':
28356     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28357       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28358         weight = CW_Constant;
28359     }
28360     break;
28361   case 'M':
28362     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28363       if (C->getZExtValue() <= 3)
28364         weight = CW_Constant;
28365     }
28366     break;
28367   case 'N':
28368     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28369       if (C->getZExtValue() <= 0xff)
28370         weight = CW_Constant;
28371     }
28372     break;
28373   case 'G':
28374   case 'C':
28375     if (isa<ConstantFP>(CallOperandVal)) {
28376       weight = CW_Constant;
28377     }
28378     break;
28379   case 'e':
28380     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28381       if ((C->getSExtValue() >= -0x80000000LL) &&
28382           (C->getSExtValue() <= 0x7fffffffLL))
28383         weight = CW_Constant;
28384     }
28385     break;
28386   case 'Z':
28387     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28388       if (C->getZExtValue() <= 0xffffffff)
28389         weight = CW_Constant;
28390     }
28391     break;
28392   }
28393   return weight;
28394 }
28395
28396 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28397 /// with another that has more specific requirements based on the type of the
28398 /// corresponding operand.
28399 const char *X86TargetLowering::
28400 LowerXConstraint(EVT ConstraintVT) const {
28401   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28402   // 'f' like normal targets.
28403   if (ConstraintVT.isFloatingPoint()) {
28404     if (Subtarget->hasSSE2())
28405       return "Y";
28406     if (Subtarget->hasSSE1())
28407       return "x";
28408   }
28409
28410   return TargetLowering::LowerXConstraint(ConstraintVT);
28411 }
28412
28413 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28414 /// vector.  If it is invalid, don't add anything to Ops.
28415 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28416                                                      std::string &Constraint,
28417                                                      std::vector<SDValue>&Ops,
28418                                                      SelectionDAG &DAG) const {
28419   SDValue Result;
28420
28421   // Only support length 1 constraints for now.
28422   if (Constraint.length() > 1) return;
28423
28424   char ConstraintLetter = Constraint[0];
28425   switch (ConstraintLetter) {
28426   default: break;
28427   case 'I':
28428     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28429       if (C->getZExtValue() <= 31) {
28430         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28431                                        Op.getValueType());
28432         break;
28433       }
28434     }
28435     return;
28436   case 'J':
28437     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28438       if (C->getZExtValue() <= 63) {
28439         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28440                                        Op.getValueType());
28441         break;
28442       }
28443     }
28444     return;
28445   case 'K':
28446     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28447       if (isInt<8>(C->getSExtValue())) {
28448         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28449                                        Op.getValueType());
28450         break;
28451       }
28452     }
28453     return;
28454   case 'L':
28455     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28456       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28457           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28458         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28459                                        Op.getValueType());
28460         break;
28461       }
28462     }
28463     return;
28464   case 'M':
28465     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28466       if (C->getZExtValue() <= 3) {
28467         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28468                                        Op.getValueType());
28469         break;
28470       }
28471     }
28472     return;
28473   case 'N':
28474     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28475       if (C->getZExtValue() <= 255) {
28476         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28477                                        Op.getValueType());
28478         break;
28479       }
28480     }
28481     return;
28482   case 'O':
28483     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28484       if (C->getZExtValue() <= 127) {
28485         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28486                                        Op.getValueType());
28487         break;
28488       }
28489     }
28490     return;
28491   case 'e': {
28492     // 32-bit signed value
28493     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28494       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28495                                            C->getSExtValue())) {
28496         // Widen to 64 bits here to get it sign extended.
28497         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28498         break;
28499       }
28500     // FIXME gcc accepts some relocatable values here too, but only in certain
28501     // memory models; it's complicated.
28502     }
28503     return;
28504   }
28505   case 'Z': {
28506     // 32-bit unsigned value
28507     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28508       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28509                                            C->getZExtValue())) {
28510         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28511                                        Op.getValueType());
28512         break;
28513       }
28514     }
28515     // FIXME gcc accepts some relocatable values here too, but only in certain
28516     // memory models; it's complicated.
28517     return;
28518   }
28519   case 'i': {
28520     // Literal immediates are always ok.
28521     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28522       // Widen to 64 bits here to get it sign extended.
28523       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28524       break;
28525     }
28526
28527     // In any sort of PIC mode addresses need to be computed at runtime by
28528     // adding in a register or some sort of table lookup.  These can't
28529     // be used as immediates.
28530     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28531       return;
28532
28533     // If we are in non-pic codegen mode, we allow the address of a global (with
28534     // an optional displacement) to be used with 'i'.
28535     GlobalAddressSDNode *GA = nullptr;
28536     int64_t Offset = 0;
28537
28538     // Match either (GA), (GA+C), (GA+C1+C2), etc.
28539     while (1) {
28540       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28541         Offset += GA->getOffset();
28542         break;
28543       } else if (Op.getOpcode() == ISD::ADD) {
28544         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28545           Offset += C->getZExtValue();
28546           Op = Op.getOperand(0);
28547           continue;
28548         }
28549       } else if (Op.getOpcode() == ISD::SUB) {
28550         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28551           Offset += -C->getZExtValue();
28552           Op = Op.getOperand(0);
28553           continue;
28554         }
28555       }
28556
28557       // Otherwise, this isn't something we can handle, reject it.
28558       return;
28559     }
28560
28561     const GlobalValue *GV = GA->getGlobal();
28562     // If we require an extra load to get this address, as in PIC mode, we
28563     // can't accept it.
28564     if (isGlobalStubReference(
28565             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28566       return;
28567
28568     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28569                                         GA->getValueType(0), Offset);
28570     break;
28571   }
28572   }
28573
28574   if (Result.getNode()) {
28575     Ops.push_back(Result);
28576     return;
28577   }
28578   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28579 }
28580
28581 std::pair<unsigned, const TargetRegisterClass *>
28582 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28583                                                 StringRef Constraint,
28584                                                 MVT VT) const {
28585   // First, see if this is a constraint that directly corresponds to an LLVM
28586   // register class.
28587   if (Constraint.size() == 1) {
28588     // GCC Constraint Letters
28589     switch (Constraint[0]) {
28590     default: break;
28591       // TODO: Slight differences here in allocation order and leaving
28592       // RIP in the class. Do they matter any more here than they do
28593       // in the normal allocation?
28594     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28595       if (Subtarget->is64Bit()) {
28596         if (VT == MVT::i32 || VT == MVT::f32)
28597           return std::make_pair(0U, &X86::GR32RegClass);
28598         if (VT == MVT::i16)
28599           return std::make_pair(0U, &X86::GR16RegClass);
28600         if (VT == MVT::i8 || VT == MVT::i1)
28601           return std::make_pair(0U, &X86::GR8RegClass);
28602         if (VT == MVT::i64 || VT == MVT::f64)
28603           return std::make_pair(0U, &X86::GR64RegClass);
28604         break;
28605       }
28606       // 32-bit fallthrough
28607     case 'Q':   // Q_REGS
28608       if (VT == MVT::i32 || VT == MVT::f32)
28609         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28610       if (VT == MVT::i16)
28611         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28612       if (VT == MVT::i8 || VT == MVT::i1)
28613         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28614       if (VT == MVT::i64)
28615         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28616       break;
28617     case 'r':   // GENERAL_REGS
28618     case 'l':   // INDEX_REGS
28619       if (VT == MVT::i8 || VT == MVT::i1)
28620         return std::make_pair(0U, &X86::GR8RegClass);
28621       if (VT == MVT::i16)
28622         return std::make_pair(0U, &X86::GR16RegClass);
28623       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28624         return std::make_pair(0U, &X86::GR32RegClass);
28625       return std::make_pair(0U, &X86::GR64RegClass);
28626     case 'R':   // LEGACY_REGS
28627       if (VT == MVT::i8 || VT == MVT::i1)
28628         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28629       if (VT == MVT::i16)
28630         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28631       if (VT == MVT::i32 || !Subtarget->is64Bit())
28632         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28633       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28634     case 'f':  // FP Stack registers.
28635       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28636       // value to the correct fpstack register class.
28637       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28638         return std::make_pair(0U, &X86::RFP32RegClass);
28639       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28640         return std::make_pair(0U, &X86::RFP64RegClass);
28641       return std::make_pair(0U, &X86::RFP80RegClass);
28642     case 'y':   // MMX_REGS if MMX allowed.
28643       if (!Subtarget->hasMMX()) break;
28644       return std::make_pair(0U, &X86::VR64RegClass);
28645     case 'Y':   // SSE_REGS if SSE2 allowed
28646       if (!Subtarget->hasSSE2()) break;
28647       // FALL THROUGH.
28648     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28649       if (!Subtarget->hasSSE1()) break;
28650
28651       switch (VT.SimpleTy) {
28652       default: break;
28653       // Scalar SSE types.
28654       case MVT::f32:
28655       case MVT::i32:
28656         return std::make_pair(0U, &X86::FR32RegClass);
28657       case MVT::f64:
28658       case MVT::i64:
28659         return std::make_pair(0U, &X86::FR64RegClass);
28660       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28661       // Vector types.
28662       case MVT::v16i8:
28663       case MVT::v8i16:
28664       case MVT::v4i32:
28665       case MVT::v2i64:
28666       case MVT::v4f32:
28667       case MVT::v2f64:
28668         return std::make_pair(0U, &X86::VR128RegClass);
28669       // AVX types.
28670       case MVT::v32i8:
28671       case MVT::v16i16:
28672       case MVT::v8i32:
28673       case MVT::v4i64:
28674       case MVT::v8f32:
28675       case MVT::v4f64:
28676         return std::make_pair(0U, &X86::VR256RegClass);
28677       case MVT::v8f64:
28678       case MVT::v16f32:
28679       case MVT::v16i32:
28680       case MVT::v8i64:
28681         return std::make_pair(0U, &X86::VR512RegClass);
28682       }
28683       break;
28684     }
28685   }
28686
28687   // Use the default implementation in TargetLowering to convert the register
28688   // constraint into a member of a register class.
28689   std::pair<unsigned, const TargetRegisterClass*> Res;
28690   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28691
28692   // Not found as a standard register?
28693   if (!Res.second) {
28694     // Map st(0) -> st(7) -> ST0
28695     if (Constraint.size() == 7 && Constraint[0] == '{' &&
28696         tolower(Constraint[1]) == 's' &&
28697         tolower(Constraint[2]) == 't' &&
28698         Constraint[3] == '(' &&
28699         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28700         Constraint[5] == ')' &&
28701         Constraint[6] == '}') {
28702
28703       Res.first = X86::FP0+Constraint[4]-'0';
28704       Res.second = &X86::RFP80RegClass;
28705       return Res;
28706     }
28707
28708     // GCC allows "st(0)" to be called just plain "st".
28709     if (StringRef("{st}").equals_lower(Constraint)) {
28710       Res.first = X86::FP0;
28711       Res.second = &X86::RFP80RegClass;
28712       return Res;
28713     }
28714
28715     // flags -> EFLAGS
28716     if (StringRef("{flags}").equals_lower(Constraint)) {
28717       Res.first = X86::EFLAGS;
28718       Res.second = &X86::CCRRegClass;
28719       return Res;
28720     }
28721
28722     // 'A' means EAX + EDX.
28723     if (Constraint == "A") {
28724       Res.first = X86::EAX;
28725       Res.second = &X86::GR32_ADRegClass;
28726       return Res;
28727     }
28728     return Res;
28729   }
28730
28731   // Otherwise, check to see if this is a register class of the wrong value
28732   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28733   // turn into {ax},{dx}.
28734   // MVT::Other is used to specify clobber names.
28735   if (Res.second->hasType(VT) || VT == MVT::Other)
28736     return Res;   // Correct type already, nothing to do.
28737
28738   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28739   // return "eax". This should even work for things like getting 64bit integer
28740   // registers when given an f64 type.
28741   const TargetRegisterClass *Class = Res.second;
28742   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28743       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28744     unsigned Size = VT.getSizeInBits();
28745     if (Size == 1) Size = 8;
28746     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28747     if (DestReg > 0) {
28748       Res.first = DestReg;
28749       Res.second = Size == 8 ? &X86::GR8RegClass
28750                  : Size == 16 ? &X86::GR16RegClass
28751                  : Size == 32 ? &X86::GR32RegClass
28752                  : &X86::GR64RegClass;
28753       assert(Res.second->contains(Res.first) && "Register in register class");
28754     } else {
28755       // No register found/type mismatch.
28756       Res.first = 0;
28757       Res.second = nullptr;
28758     }
28759   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28760              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28761              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28762              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28763              Class == &X86::VR512RegClass) {
28764     // Handle references to XMM physical registers that got mapped into the
28765     // wrong class.  This can happen with constraints like {xmm0} where the
28766     // target independent register mapper will just pick the first match it can
28767     // find, ignoring the required type.
28768
28769     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28770     if (VT == MVT::f32 || VT == MVT::i32)
28771       Res.second = &X86::FR32RegClass;
28772     else if (VT == MVT::f64 || VT == MVT::i64)
28773       Res.second = &X86::FR64RegClass;
28774     else if (X86::VR128RegClass.hasType(VT))
28775       Res.second = &X86::VR128RegClass;
28776     else if (X86::VR256RegClass.hasType(VT))
28777       Res.second = &X86::VR256RegClass;
28778     else if (X86::VR512RegClass.hasType(VT))
28779       Res.second = &X86::VR512RegClass;
28780     else {
28781       // Type mismatch and not a clobber: Return an error;
28782       Res.first = 0;
28783       Res.second = nullptr;
28784     }
28785   }
28786
28787   return Res;
28788 }
28789
28790 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28791                                             const AddrMode &AM, Type *Ty,
28792                                             unsigned AS) const {
28793   // Scaling factors are not free at all.
28794   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28795   // will take 2 allocations in the out of order engine instead of 1
28796   // for plain addressing mode, i.e. inst (reg1).
28797   // E.g.,
28798   // vaddps (%rsi,%drx), %ymm0, %ymm1
28799   // Requires two allocations (one for the load, one for the computation)
28800   // whereas:
28801   // vaddps (%rsi), %ymm0, %ymm1
28802   // Requires just 1 allocation, i.e., freeing allocations for other operations
28803   // and having less micro operations to execute.
28804   //
28805   // For some X86 architectures, this is even worse because for instance for
28806   // stores, the complex addressing mode forces the instruction to use the
28807   // "load" ports instead of the dedicated "store" port.
28808   // E.g., on Haswell:
28809   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28810   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28811   if (isLegalAddressingMode(DL, AM, Ty, AS))
28812     // Scale represents reg2 * scale, thus account for 1
28813     // as soon as we use a second register.
28814     return AM.Scale != 0;
28815   return -1;
28816 }
28817
28818 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28819   // Integer division on x86 is expensive. However, when aggressively optimizing
28820   // for code size, we prefer to use a div instruction, as it is usually smaller
28821   // than the alternative sequence.
28822   // The exception to this is vector division. Since x86 doesn't have vector
28823   // integer division, leaving the division as-is is a loss even in terms of
28824   // size, because it will have to be scalarized, while the alternative code
28825   // sequence can be performed in vector form.
28826   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28827                                    Attribute::MinSize);
28828   return OptSize && !VT.isVector();
28829 }