[X86] Make hasFP constant time
[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   }
269
270   // Scalar integer divide and remainder are lowered to use operations that
271   // produce two results, to match the available instructions. This exposes
272   // the two-result form to trivial CSE, which is able to combine x/y and x%y
273   // into a single instruction.
274   //
275   // Scalar integer multiply-high is also lowered to use two-result
276   // operations, to match the available instructions. However, plain multiply
277   // (low) operations are left as Legal, as there are single-result
278   // instructions for this in x86. Using the two-result multiply instructions
279   // when both high and low results are needed must be arranged by dagcombine.
280   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
281     setOperationAction(ISD::MULHS, VT, Expand);
282     setOperationAction(ISD::MULHU, VT, Expand);
283     setOperationAction(ISD::SDIV, VT, Expand);
284     setOperationAction(ISD::UDIV, VT, Expand);
285     setOperationAction(ISD::SREM, VT, Expand);
286     setOperationAction(ISD::UREM, VT, Expand);
287
288     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
289     setOperationAction(ISD::ADDC, VT, Custom);
290     setOperationAction(ISD::ADDE, VT, Custom);
291     setOperationAction(ISD::SUBC, VT, Custom);
292     setOperationAction(ISD::SUBE, VT, Custom);
293   }
294
295   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
296   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
297   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::f128,  Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f128,  Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
313   if (Subtarget->is64Bit())
314     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
315   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
316   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
318   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
319
320   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
321     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
322     // is. We should promote the value to 64-bits to solve this.
323     // This is what the CRT headers do - `fmodf` is an inline header
324     // function casting to f64 and calling `fmod`.
325     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
326   } else {
327     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
328   }
329
330   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
331   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
332   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
333
334   // Promote the i8 variants and force them on up to i32 which has a shorter
335   // encoding.
336   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
337   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
338   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
339   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
340   if (Subtarget->hasBMI()) {
341     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
342     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
343     if (Subtarget->is64Bit())
344       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
345   } else {
346     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
347     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
348     if (Subtarget->is64Bit())
349       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
350   }
351
352   if (Subtarget->hasLZCNT()) {
353     // When promoting the i8 variants, force them to i32 for a shorter
354     // encoding.
355     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
356     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
358     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
361     if (Subtarget->is64Bit())
362       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
363   } else {
364     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
365     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
366     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
367     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
368     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
369     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
370     if (Subtarget->is64Bit()) {
371       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
372       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
373     }
374   }
375
376   // Special handling for half-precision floating point conversions.
377   // If we don't have F16C support, then lower half float conversions
378   // into library calls.
379   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
380     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
381     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
382   }
383
384   // There's never any support for operations beyond MVT::f32.
385   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
386   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
387   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
388   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
389
390   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
391   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
392   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
393   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
394   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
395   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
396
397   if (Subtarget->hasPOPCNT()) {
398     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
399   } else {
400     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
401     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
402     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
403     if (Subtarget->is64Bit())
404       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
405   }
406
407   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
408
409   if (!Subtarget->hasMOVBE())
410     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
411
412   // These should be promoted to a larger select which is supported.
413   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
414   // X86 wants to expand cmov itself.
415   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
416   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
417   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
418   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f128 , Custom);
422   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f128 , Custom);
429   setOperationAction(ISD::SETCCE          , MVT::i8   , Custom);
430   setOperationAction(ISD::SETCCE          , MVT::i16  , Custom);
431   setOperationAction(ISD::SETCCE          , MVT::i32  , Custom);
432   if (Subtarget->is64Bit()) {
433     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
434     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
435     setOperationAction(ISD::SETCCE        , MVT::i64  , Custom);
436   }
437   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
438   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
439   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
440   // support continuation, user-level threading, and etc.. As a result, no
441   // other SjLj exception interfaces are implemented and please don't build
442   // your own exception handling based on them.
443   // LLVM/Clang supports zero-cost DWARF exception handling.
444   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
445   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
446
447   // Darwin ABI issue.
448   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
449   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
450   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
451   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
452   if (Subtarget->is64Bit())
453     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
454   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
455   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
456   if (Subtarget->is64Bit()) {
457     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
458     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
459     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
460     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
461     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
462   }
463   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
464   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
465   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
466   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
467   if (Subtarget->is64Bit()) {
468     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
469     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
470     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
471   }
472
473   if (Subtarget->hasSSE1())
474     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
475
476   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
477
478   // Expand certain atomics
479   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
480     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
481     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
482     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
483   }
484
485   if (Subtarget->hasCmpxchg16b()) {
486     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
487   }
488
489   // FIXME - use subtarget debug flags
490   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
491       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
492     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
493   }
494
495   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
496   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
497
498   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
499   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
500
501   setOperationAction(ISD::TRAP, MVT::Other, Legal);
502   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
503
504   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
505   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
506   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
507   if (Subtarget->is64Bit()) {
508     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
509     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
510   } else {
511     // TargetInfo::CharPtrBuiltinVaList
512     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
513     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
514   }
515
516   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
517   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
518
519   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
520
521   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
522   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
523   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
524
525   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
526     // f32 and f64 use SSE.
527     // Set up the FP register classes.
528     addRegisterClass(MVT::f32, &X86::FR32RegClass);
529     addRegisterClass(MVT::f64, &X86::FR64RegClass);
530
531     // Use ANDPD to simulate FABS.
532     setOperationAction(ISD::FABS , MVT::f64, Custom);
533     setOperationAction(ISD::FABS , MVT::f32, Custom);
534
535     // Use XORP to simulate FNEG.
536     setOperationAction(ISD::FNEG , MVT::f64, Custom);
537     setOperationAction(ISD::FNEG , MVT::f32, Custom);
538
539     // Use ANDPD and ORPD to simulate FCOPYSIGN.
540     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
541     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
542
543     // Lower this to FGETSIGNx86 plus an AND.
544     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
545     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
546
547     // We don't support sin/cos/fmod
548     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
549     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
550     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
551     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
552     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
553     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
554
555     // Expand FP immediates into loads from the stack, except for the special
556     // cases we handle.
557     addLegalFPImmediate(APFloat(+0.0)); // xorpd
558     addLegalFPImmediate(APFloat(+0.0f)); // xorps
559   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
560     // Use SSE for f32, x87 for f64.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, &X86::FR32RegClass);
563     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
564
565     // Use ANDPS to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f32, Custom);
567
568     // Use XORP to simulate FNEG.
569     setOperationAction(ISD::FNEG , MVT::f32, Custom);
570
571     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
572
573     // Use ANDPS and ORPS to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // We don't support sin/cos/fmod
578     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
579     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
580     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
581
582     // Special cases we handle for FP constants.
583     addLegalFPImmediate(APFloat(+0.0f)); // xorps
584     addLegalFPImmediate(APFloat(+0.0)); // FLD0
585     addLegalFPImmediate(APFloat(+1.0)); // FLD1
586     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
587     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
588
589     if (!TM.Options.UnsafeFPMath) {
590       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
591       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
592       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
593     }
594   } else if (!Subtarget->useSoftFloat()) {
595     // f32 and f64 in x87.
596     // Set up the FP register classes.
597     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
598     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
599
600     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
601     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
604
605     if (!TM.Options.UnsafeFPMath) {
606       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
607       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
608       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
609       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
610       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
611       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
612     }
613     addLegalFPImmediate(APFloat(+0.0)); // FLD0
614     addLegalFPImmediate(APFloat(+1.0)); // FLD1
615     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
616     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
617     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
618     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
619     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
620     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
621   }
622
623   // We don't support FMA.
624   setOperationAction(ISD::FMA, MVT::f64, Expand);
625   setOperationAction(ISD::FMA, MVT::f32, Expand);
626
627   // Long double always uses X87, except f128 in MMX.
628   if (!Subtarget->useSoftFloat()) {
629     if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
630       addRegisterClass(MVT::f128, &X86::FR128RegClass);
631       ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
632       setOperationAction(ISD::FABS , MVT::f128, Custom);
633       setOperationAction(ISD::FNEG , MVT::f128, Custom);
634       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
635     }
636
637     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
638     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
639     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
640     {
641       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
642       addLegalFPImmediate(TmpFlt);  // FLD0
643       TmpFlt.changeSign();
644       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
645
646       bool ignored;
647       APFloat TmpFlt2(+1.0);
648       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
649                       &ignored);
650       addLegalFPImmediate(TmpFlt2);  // FLD1
651       TmpFlt2.changeSign();
652       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
653     }
654
655     if (!TM.Options.UnsafeFPMath) {
656       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
657       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
658       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
659     }
660
661     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
662     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
663     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
664     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
665     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
666     setOperationAction(ISD::FMA, MVT::f80, Expand);
667   }
668
669   // Always use a library call for pow.
670   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
671   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
673
674   setOperationAction(ISD::FLOG, MVT::f80, Expand);
675   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677   setOperationAction(ISD::FEXP, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
679   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
680   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
681
682   // First set operation action for all vector types to either promote
683   // (for widening) or expand (for scalarization). Then we will selectively
684   // turn on ones that can be effectively codegen'd.
685   for (MVT VT : MVT::vector_valuetypes()) {
686     setOperationAction(ISD::ADD , VT, Expand);
687     setOperationAction(ISD::SUB , VT, Expand);
688     setOperationAction(ISD::FADD, VT, Expand);
689     setOperationAction(ISD::FNEG, VT, Expand);
690     setOperationAction(ISD::FSUB, VT, Expand);
691     setOperationAction(ISD::MUL , VT, Expand);
692     setOperationAction(ISD::FMUL, VT, Expand);
693     setOperationAction(ISD::SDIV, VT, Expand);
694     setOperationAction(ISD::UDIV, VT, Expand);
695     setOperationAction(ISD::FDIV, VT, Expand);
696     setOperationAction(ISD::SREM, VT, Expand);
697     setOperationAction(ISD::UREM, VT, Expand);
698     setOperationAction(ISD::LOAD, VT, Expand);
699     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
700     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
701     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
702     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
703     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
704     setOperationAction(ISD::FABS, VT, Expand);
705     setOperationAction(ISD::FSIN, VT, Expand);
706     setOperationAction(ISD::FSINCOS, VT, Expand);
707     setOperationAction(ISD::FCOS, VT, Expand);
708     setOperationAction(ISD::FSINCOS, VT, Expand);
709     setOperationAction(ISD::FREM, VT, Expand);
710     setOperationAction(ISD::FMA,  VT, Expand);
711     setOperationAction(ISD::FPOWI, VT, Expand);
712     setOperationAction(ISD::FSQRT, VT, Expand);
713     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
714     setOperationAction(ISD::FFLOOR, VT, Expand);
715     setOperationAction(ISD::FCEIL, VT, Expand);
716     setOperationAction(ISD::FTRUNC, VT, Expand);
717     setOperationAction(ISD::FRINT, VT, Expand);
718     setOperationAction(ISD::FNEARBYINT, VT, Expand);
719     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
720     setOperationAction(ISD::MULHS, VT, Expand);
721     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
722     setOperationAction(ISD::MULHU, VT, Expand);
723     setOperationAction(ISD::SDIVREM, VT, Expand);
724     setOperationAction(ISD::UDIVREM, VT, Expand);
725     setOperationAction(ISD::FPOW, VT, Expand);
726     setOperationAction(ISD::CTPOP, VT, Expand);
727     setOperationAction(ISD::CTTZ, VT, Expand);
728     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
729     setOperationAction(ISD::CTLZ, VT, Expand);
730     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
731     setOperationAction(ISD::SHL, VT, Expand);
732     setOperationAction(ISD::SRA, VT, Expand);
733     setOperationAction(ISD::SRL, VT, Expand);
734     setOperationAction(ISD::ROTL, VT, Expand);
735     setOperationAction(ISD::ROTR, VT, Expand);
736     setOperationAction(ISD::BSWAP, VT, Expand);
737     setOperationAction(ISD::SETCC, VT, Expand);
738     setOperationAction(ISD::FLOG, VT, Expand);
739     setOperationAction(ISD::FLOG2, VT, Expand);
740     setOperationAction(ISD::FLOG10, VT, Expand);
741     setOperationAction(ISD::FEXP, VT, Expand);
742     setOperationAction(ISD::FEXP2, VT, Expand);
743     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
744     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
745     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
746     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
747     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
748     setOperationAction(ISD::TRUNCATE, VT, Expand);
749     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
750     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
751     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
752     setOperationAction(ISD::VSELECT, VT, Expand);
753     setOperationAction(ISD::SELECT_CC, VT, Expand);
754     for (MVT InnerVT : MVT::vector_valuetypes()) {
755       setTruncStoreAction(InnerVT, VT, Expand);
756
757       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
758       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
759
760       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
761       // types, we have to deal with them whether we ask for Expansion or not.
762       // Setting Expand causes its own optimisation problems though, so leave
763       // them legal.
764       if (VT.getVectorElementType() == MVT::i1)
765         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
766
767       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
768       // split/scalarized right now.
769       if (VT.getVectorElementType() == MVT::f16)
770         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
771     }
772   }
773
774   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
775   // with -msoft-float, disable use of MMX as well.
776   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
777     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
778     // No operations on x86mmx supported, everything uses intrinsics.
779   }
780
781   // MMX-sized vectors (other than x86mmx) are expected to be expanded
782   // into smaller operations.
783   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
784     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
785     setOperationAction(ISD::AND,                MMXTy,      Expand);
786     setOperationAction(ISD::OR,                 MMXTy,      Expand);
787     setOperationAction(ISD::XOR,                MMXTy,      Expand);
788     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
789     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
790     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
791   }
792   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
795     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
796
797     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
801     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
802     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
803     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
804     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
805     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
806     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
807     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
808     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
809     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
810     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
811   }
812
813   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
814     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
815
816     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
817     // registers cannot be used even for integer operations.
818     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
819     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
820     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
821     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
822
823     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
824     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
825     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
826     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
827     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
828     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
829     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
830     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
831     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
832     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
833     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
834     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
835     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
836     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
837     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
838     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
839     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
840     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
841     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
842     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
843     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
844     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
845     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
846
847     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
848     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
849     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
850     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
851
852     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
853     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
854     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
855     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
856
857     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
858     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
859     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
860     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
861     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
862
863     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
864     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
865     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
866     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
867
868     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
869     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
870     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
871     // ISD::CTTZ v2i64 - scalarization is faster.
872     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
873     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
874     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
875     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
876
877     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
879       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
880       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
881       setOperationAction(ISD::VSELECT,            VT, Custom);
882       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
883     }
884
885     // We support custom legalizing of sext and anyext loads for specific
886     // memory vector types which we can load as a scalar (or sequence of
887     // scalars) and extend in-register to a legal 128-bit vector type. For sext
888     // loads these must work with a single scalar load.
889     for (MVT VT : MVT::integer_vector_valuetypes()) {
890       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
891       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
892       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
893       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
894       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
895       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
896       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
897       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
898       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
899     }
900
901     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
902     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
903     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
904     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
905     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
906     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
907     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
908     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
909
910     if (Subtarget->is64Bit()) {
911       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
912       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
913     }
914
915     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
916     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
917       setOperationAction(ISD::AND,    VT, Promote);
918       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
919       setOperationAction(ISD::OR,     VT, Promote);
920       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
921       setOperationAction(ISD::XOR,    VT, Promote);
922       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
923       setOperationAction(ISD::LOAD,   VT, Promote);
924       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
925       setOperationAction(ISD::SELECT, VT, Promote);
926       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
927     }
928
929     // Custom lower v2i64 and v2f64 selects.
930     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
931     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
932     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
933     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
934
935     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
936     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
937
938     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
939
940     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
941     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
942     // As there is no 64-bit GPR available, we need build a special custom
943     // sequence to convert from v2i32 to v2f32.
944     if (!Subtarget->is64Bit())
945       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
946
947     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
948     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
949
950     for (MVT VT : MVT::fp_vector_valuetypes())
951       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
952
953     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
954     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
955     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
956   }
957
958   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
959     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
960       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
961       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
962       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
963       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
964       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
965     }
966
967     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
968     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
969     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
970     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
971     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
972     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
973     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
974     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
975
976     // FIXME: Do we need to handle scalar-to-vector here?
977     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
978
979     // We directly match byte blends in the backend as they match the VSELECT
980     // condition form.
981     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
982
983     // SSE41 brings specific instructions for doing vector sign extend even in
984     // cases where we don't have SRA.
985     for (MVT VT : MVT::integer_vector_valuetypes()) {
986       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
988       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
989     }
990
991     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
997     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
998
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1004     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1005
1006     // i8 and i16 vectors are custom because the source register and source
1007     // source memory operand types are not the same width.  f32 vectors are
1008     // custom since the immediate controlling the insert encodes additional
1009     // information.
1010     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1013     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1014
1015     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1018     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1019
1020     // FIXME: these should be Legal, but that's only for the case where
1021     // the index is constant.  For now custom expand to deal with that.
1022     if (Subtarget->is64Bit()) {
1023       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1024       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1025     }
1026   }
1027
1028   if (Subtarget->hasSSE2()) {
1029     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1031     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1032
1033     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1034     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1035
1036     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1037     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1038
1039     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1040     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1041
1042     // In the customized shift lowering, the legal cases in AVX2 will be
1043     // recognized.
1044     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1045     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1046
1047     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1048     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1049
1050     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1051     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1052   }
1053
1054   if (Subtarget->hasXOP()) {
1055     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1056     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1059     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1060     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1061     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1062     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1063   }
1064
1065   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1066     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1067     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1068     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1069     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1070     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1071     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1072
1073     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1074     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1075     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1076
1077     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1078     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1080     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1081     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1085     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1087     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1088     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1089
1090     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1091     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1092     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1093     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1094     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1095     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1096     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1097     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1098     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1099     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1100     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1101     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1102
1103     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1104     // even though v8i16 is a legal type.
1105     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1106     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1107     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1108
1109     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1110     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1111     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1112
1113     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1114     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1115
1116     for (MVT VT : MVT::fp_vector_valuetypes())
1117       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1118
1119     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1120     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1121
1122     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1123     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1124
1125     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1126     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1127
1128     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1129     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1130     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1131     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1132
1133     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1134     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1135     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1136
1137     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1138     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1139     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1140     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1141     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1142     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1143     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1144     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1145     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1146     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1147     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1148     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1149
1150     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1151     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1152     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1153     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1154
1155     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1156     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1157     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1158     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1159     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1160     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1161     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1162     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1163
1164     if (Subtarget->hasAnyFMA()) {
1165       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1166       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1169       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1170       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1171     }
1172
1173     if (Subtarget->hasInt256()) {
1174       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1175       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1178
1179       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1180       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1183
1184       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1185       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1186       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1187       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1188
1189       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1190       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1191       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1192       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1193
1194       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1195       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1196       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1197       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1198       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1199       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1200       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1201       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1202       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1203       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1204       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1205       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1206
1207       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1208       // when we have a 256bit-wide blend with immediate.
1209       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1210
1211       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1212       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1214       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1215       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1216       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1217       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1218
1219       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1221       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1222       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1223       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1224       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1225     } else {
1226       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1227       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1228       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1229       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1230
1231       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1232       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1233       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1234       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1235
1236       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1237       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1238       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1239       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1240
1241       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1242       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1243       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1244       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1245       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1246       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1247       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1248       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1249       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1250       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1251       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1252       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1253     }
1254
1255     // In the customized shift lowering, the legal cases in AVX2 will be
1256     // recognized.
1257     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1258     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1259
1260     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1261     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1262
1263     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1264     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1265
1266     // Custom lower several nodes for 256-bit types.
1267     for (MVT VT : MVT::vector_valuetypes()) {
1268       if (VT.getScalarSizeInBits() >= 32) {
1269         setOperationAction(ISD::MLOAD,  VT, Legal);
1270         setOperationAction(ISD::MSTORE, VT, Legal);
1271       }
1272       // Extract subvector is special because the value type
1273       // (result) is 128-bit but the source is 256-bit wide.
1274       if (VT.is128BitVector()) {
1275         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1276       }
1277       // Do not attempt to custom lower other non-256-bit vectors
1278       if (!VT.is256BitVector())
1279         continue;
1280
1281       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1282       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1283       setOperationAction(ISD::VSELECT,            VT, Custom);
1284       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1285       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1286       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1287       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1288       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1289     }
1290
1291     if (Subtarget->hasInt256())
1292       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1293
1294     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1295     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1296       setOperationAction(ISD::AND,    VT, Promote);
1297       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1298       setOperationAction(ISD::OR,     VT, Promote);
1299       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1300       setOperationAction(ISD::XOR,    VT, Promote);
1301       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1302       setOperationAction(ISD::LOAD,   VT, Promote);
1303       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1304       setOperationAction(ISD::SELECT, VT, Promote);
1305       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1306     }
1307   }
1308
1309   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1310     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1311     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1312     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1313     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1314
1315     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1316     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1317     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1318
1319     for (MVT VT : MVT::fp_vector_valuetypes())
1320       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1321
1322     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1323     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1324     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1325     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1326     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1327     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1328     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1329     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1330     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1331     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1332     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1333     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1334
1335     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1336     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1337     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1338     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1339     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1340     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1341     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1342     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1343     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1344     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1349
1350     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1351     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1355     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1356     setOperationAction(ISD::FABS,               MVT::v16f32, Custom);
1357
1358     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1359     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1363     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1364     setOperationAction(ISD::FABS,               MVT::v8f64, Custom);
1365     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1366     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1367
1368     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1372     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1376     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1377     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1379     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1382     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1383     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1384
1385     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1386     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1387     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1388     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1389     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1390     if (Subtarget->hasVLX()){
1391       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1392       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1393       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1394       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1395       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1396
1397       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1398       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1399       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1400       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1401       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1402     } else {
1403       setOperationAction(ISD::MLOAD,    MVT::v8i32, Custom);
1404       setOperationAction(ISD::MLOAD,    MVT::v8f32, Custom);
1405       setOperationAction(ISD::MSTORE,   MVT::v8i32, Custom);
1406       setOperationAction(ISD::MSTORE,   MVT::v8f32, Custom);
1407     }
1408     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1409     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1410     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1411     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1412     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1413     if (Subtarget->hasDQI()) {
1414       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1415       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1416
1417       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1418       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1419       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1420       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1421       if (Subtarget->hasVLX()) {
1422         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1423         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1424         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1425         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1426         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1427         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1428         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1429         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1430       }
1431     }
1432     if (Subtarget->hasVLX()) {
1433       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1434       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1435       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1436       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1437       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1438       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1439       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1440       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1441     }
1442     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1443     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1444     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1445     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1446     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1447     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1448     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1449     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1450     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1451     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1452     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1453     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1454     if (Subtarget->hasDQI()) {
1455       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1456       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1457     }
1458     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1459     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1460     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1461     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1462     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1463     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1464     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1465     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1466     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1467     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1468
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1470     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1471     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1,   Custom);
1474
1475     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1476     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1477
1478     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1479
1480     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1481     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1482     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v16i1, Custom);
1483     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1484     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1485     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1486     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1487     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1488     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1489     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1490     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1491     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1492
1493     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1494     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1495     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1496     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1497     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1498     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1499     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1500     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1501
1502     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1503     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1504
1505     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1506     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1507
1508     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1509
1510     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1511     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1512
1513     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1514     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1515
1516     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1517     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1518
1519     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1520     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1521     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1522     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1523     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1524     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1525
1526     if (Subtarget->hasCDI()) {
1527       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1528       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1529       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Expand);
1530       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Expand);
1531
1532       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1533       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1534       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1535       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1536       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Expand);
1537       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Expand);
1538       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Expand);
1539       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Expand);
1540
1541       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1542       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1543
1544       if (Subtarget->hasVLX()) {
1545         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1546         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1547         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1548         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1549         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1550         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1551         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1552         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1553
1554         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1555         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1556         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1557         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1558       } else {
1559         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1560         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1561         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1562         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1563         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1564         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1565         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1566         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1567       }
1568     } // Subtarget->hasCDI()
1569
1570     if (Subtarget->hasDQI()) {
1571       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1572       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1573       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1574     }
1575     // Custom lower several nodes.
1576     for (MVT VT : MVT::vector_valuetypes()) {
1577       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1578       if (EltSize == 1) {
1579         setOperationAction(ISD::AND, VT, Legal);
1580         setOperationAction(ISD::OR,  VT, Legal);
1581         setOperationAction(ISD::XOR,  VT, Legal);
1582       }
1583       if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1584         setOperationAction(ISD::MGATHER,  VT, Custom);
1585         setOperationAction(ISD::MSCATTER, VT, Custom);
1586       }
1587       // Extract subvector is special because the value type
1588       // (result) is 256/128-bit but the source is 512-bit wide.
1589       if (VT.is128BitVector() || VT.is256BitVector()) {
1590         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1591       }
1592       if (VT.getVectorElementType() == MVT::i1)
1593         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1594
1595       // Do not attempt to custom lower other non-512-bit vectors
1596       if (!VT.is512BitVector())
1597         continue;
1598
1599       if (EltSize >= 32) {
1600         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1601         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1602         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1603         setOperationAction(ISD::VSELECT,             VT, Legal);
1604         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1605         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1606         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1607         setOperationAction(ISD::MLOAD,               VT, Legal);
1608         setOperationAction(ISD::MSTORE,              VT, Legal);
1609         setOperationAction(ISD::MGATHER,  VT, Legal);
1610         setOperationAction(ISD::MSCATTER, VT, Custom);
1611       }
1612     }
1613     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1614       setOperationAction(ISD::SELECT, VT, Promote);
1615       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1616     }
1617   }// has  AVX-512
1618
1619   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1620     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1621     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1622
1623     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1624     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1625
1626     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1627     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1628     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1629     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1630     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1631     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1632     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1633     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1634     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1635     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1636     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1637     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1638     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1639     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1640     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1641     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1644     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1645     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1646     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1647     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1648     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1649     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1650     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1651     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1652     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1653     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1654     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1655     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1656     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1657     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1658     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1659     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1660     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1661     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1662     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1663     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1664     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1665     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1666     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1667     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1668
1669     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1670     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1671     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1672     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1673     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1674     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1675     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1676     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1677
1678     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1679     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1680     if (Subtarget->hasVLX())
1681       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1682
1683     if (Subtarget->hasCDI()) {
1684       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1685       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1686       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1687       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Expand);
1688     }
1689
1690     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1691       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1692       setOperationAction(ISD::VSELECT,             VT, Legal);
1693       setOperationAction(ISD::SRL,                 VT, Custom);
1694       setOperationAction(ISD::SHL,                 VT, Custom);
1695       setOperationAction(ISD::SRA,                 VT, Custom);
1696
1697       setOperationAction(ISD::AND,    VT, Promote);
1698       AddPromotedToType (ISD::AND,    VT, MVT::v8i64);
1699       setOperationAction(ISD::OR,     VT, Promote);
1700       AddPromotedToType (ISD::OR,     VT, MVT::v8i64);
1701       setOperationAction(ISD::XOR,    VT, Promote);
1702       AddPromotedToType (ISD::XOR,    VT, MVT::v8i64);
1703     }
1704   }
1705
1706   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1707     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1708     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1709
1710     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1711     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1712     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1713     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1714     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1715     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1716     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1717     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1718     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1719     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1720     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1721     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1722
1723     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1724     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1725     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1726     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1727     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1728     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1729     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1730     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1731
1732     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1733     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1734     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1735     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1736     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1737     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1738     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1739     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1740   }
1741
1742   // We want to custom lower some of our intrinsics.
1743   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1744   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1745   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1746   if (!Subtarget->is64Bit()) {
1747     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1748     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1749   }
1750
1751   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1752   // handle type legalization for these operations here.
1753   //
1754   // FIXME: We really should do custom legalization for addition and
1755   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1756   // than generic legalization for 64-bit multiplication-with-overflow, though.
1757   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1758     if (VT == MVT::i64 && !Subtarget->is64Bit())
1759       continue;
1760     // Add/Sub/Mul with overflow operations are custom lowered.
1761     setOperationAction(ISD::SADDO, VT, Custom);
1762     setOperationAction(ISD::UADDO, VT, Custom);
1763     setOperationAction(ISD::SSUBO, VT, Custom);
1764     setOperationAction(ISD::USUBO, VT, Custom);
1765     setOperationAction(ISD::SMULO, VT, Custom);
1766     setOperationAction(ISD::UMULO, VT, Custom);
1767   }
1768
1769   if (!Subtarget->is64Bit()) {
1770     // These libcalls are not available in 32-bit.
1771     setLibcallName(RTLIB::SHL_I128, nullptr);
1772     setLibcallName(RTLIB::SRL_I128, nullptr);
1773     setLibcallName(RTLIB::SRA_I128, nullptr);
1774   }
1775
1776   // Combine sin / cos into one node or libcall if possible.
1777   if (Subtarget->hasSinCos()) {
1778     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1779     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1780     if (Subtarget->isTargetDarwin()) {
1781       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1782       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1783       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1784       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1785     }
1786   }
1787
1788   if (Subtarget->isTargetWin64()) {
1789     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1790     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1791     setOperationAction(ISD::SREM, MVT::i128, Custom);
1792     setOperationAction(ISD::UREM, MVT::i128, Custom);
1793     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1794     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1795   }
1796
1797   // We have target-specific dag combine patterns for the following nodes:
1798   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1799   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1800   setTargetDAGCombine(ISD::BITCAST);
1801   setTargetDAGCombine(ISD::VSELECT);
1802   setTargetDAGCombine(ISD::SELECT);
1803   setTargetDAGCombine(ISD::SHL);
1804   setTargetDAGCombine(ISD::SRA);
1805   setTargetDAGCombine(ISD::SRL);
1806   setTargetDAGCombine(ISD::OR);
1807   setTargetDAGCombine(ISD::AND);
1808   setTargetDAGCombine(ISD::ADD);
1809   setTargetDAGCombine(ISD::FADD);
1810   setTargetDAGCombine(ISD::FSUB);
1811   setTargetDAGCombine(ISD::FNEG);
1812   setTargetDAGCombine(ISD::FMA);
1813   setTargetDAGCombine(ISD::FMINNUM);
1814   setTargetDAGCombine(ISD::FMAXNUM);
1815   setTargetDAGCombine(ISD::SUB);
1816   setTargetDAGCombine(ISD::LOAD);
1817   setTargetDAGCombine(ISD::MLOAD);
1818   setTargetDAGCombine(ISD::STORE);
1819   setTargetDAGCombine(ISD::MSTORE);
1820   setTargetDAGCombine(ISD::TRUNCATE);
1821   setTargetDAGCombine(ISD::ZERO_EXTEND);
1822   setTargetDAGCombine(ISD::ANY_EXTEND);
1823   setTargetDAGCombine(ISD::SIGN_EXTEND);
1824   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1825   setTargetDAGCombine(ISD::SINT_TO_FP);
1826   setTargetDAGCombine(ISD::UINT_TO_FP);
1827   setTargetDAGCombine(ISD::SETCC);
1828   setTargetDAGCombine(ISD::BUILD_VECTOR);
1829   setTargetDAGCombine(ISD::MUL);
1830   setTargetDAGCombine(ISD::XOR);
1831   setTargetDAGCombine(ISD::MSCATTER);
1832   setTargetDAGCombine(ISD::MGATHER);
1833
1834   computeRegisterProperties(Subtarget->getRegisterInfo());
1835
1836   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1837   MaxStoresPerMemsetOptSize = 8;
1838   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1839   MaxStoresPerMemcpyOptSize = 4;
1840   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1841   MaxStoresPerMemmoveOptSize = 4;
1842   setPrefLoopAlignment(4); // 2^4 bytes.
1843
1844   // A predictable cmov does not hurt on an in-order CPU.
1845   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1846   PredictableSelectIsExpensive = !Subtarget->isAtom();
1847   EnableExtLdPromotion = true;
1848   setPrefFunctionAlignment(4); // 2^4 bytes.
1849
1850   verifyIntrinsicTables();
1851 }
1852
1853 // This has so far only been implemented for 64-bit MachO.
1854 bool X86TargetLowering::useLoadStackGuardNode() const {
1855   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1856 }
1857
1858 TargetLoweringBase::LegalizeTypeAction
1859 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1860   if (ExperimentalVectorWideningLegalization &&
1861       VT.getVectorNumElements() != 1 &&
1862       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1863     return TypeWidenVector;
1864
1865   return TargetLoweringBase::getPreferredVectorAction(VT);
1866 }
1867
1868 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1869                                           EVT VT) const {
1870   if (!VT.isVector())
1871     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1872
1873   if (VT.isSimple()) {
1874     MVT VVT = VT.getSimpleVT();
1875     const unsigned NumElts = VVT.getVectorNumElements();
1876     const MVT EltVT = VVT.getVectorElementType();
1877     if (VVT.is512BitVector()) {
1878       if (Subtarget->hasAVX512())
1879         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1880             EltVT == MVT::f32 || EltVT == MVT::f64)
1881           switch(NumElts) {
1882           case  8: return MVT::v8i1;
1883           case 16: return MVT::v16i1;
1884         }
1885       if (Subtarget->hasBWI())
1886         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1887           switch(NumElts) {
1888           case 32: return MVT::v32i1;
1889           case 64: return MVT::v64i1;
1890         }
1891     }
1892
1893     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1894       if (Subtarget->hasVLX())
1895         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1896             EltVT == MVT::f32 || EltVT == MVT::f64)
1897           switch(NumElts) {
1898           case 2: return MVT::v2i1;
1899           case 4: return MVT::v4i1;
1900           case 8: return MVT::v8i1;
1901         }
1902       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1903         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1904           switch(NumElts) {
1905           case  8: return MVT::v8i1;
1906           case 16: return MVT::v16i1;
1907           case 32: return MVT::v32i1;
1908         }
1909     }
1910   }
1911
1912   return VT.changeVectorElementTypeToInteger();
1913 }
1914
1915 /// Helper for getByValTypeAlignment to determine
1916 /// the desired ByVal argument alignment.
1917 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1918   if (MaxAlign == 16)
1919     return;
1920   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1921     if (VTy->getBitWidth() == 128)
1922       MaxAlign = 16;
1923   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1924     unsigned EltAlign = 0;
1925     getMaxByValAlign(ATy->getElementType(), EltAlign);
1926     if (EltAlign > MaxAlign)
1927       MaxAlign = EltAlign;
1928   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1929     for (auto *EltTy : STy->elements()) {
1930       unsigned EltAlign = 0;
1931       getMaxByValAlign(EltTy, EltAlign);
1932       if (EltAlign > MaxAlign)
1933         MaxAlign = EltAlign;
1934       if (MaxAlign == 16)
1935         break;
1936     }
1937   }
1938 }
1939
1940 /// Return the desired alignment for ByVal aggregate
1941 /// function arguments in the caller parameter area. For X86, aggregates
1942 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1943 /// are at 4-byte boundaries.
1944 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1945                                                   const DataLayout &DL) const {
1946   if (Subtarget->is64Bit()) {
1947     // Max of 8 and alignment of type.
1948     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1949     if (TyAlign > 8)
1950       return TyAlign;
1951     return 8;
1952   }
1953
1954   unsigned Align = 4;
1955   if (Subtarget->hasSSE1())
1956     getMaxByValAlign(Ty, Align);
1957   return Align;
1958 }
1959
1960 /// Returns the target specific optimal type for load
1961 /// and store operations as a result of memset, memcpy, and memmove
1962 /// lowering. If DstAlign is zero that means it's safe to destination
1963 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1964 /// means there isn't a need to check it against alignment requirement,
1965 /// probably because the source does not need to be loaded. If 'IsMemset' is
1966 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1967 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1968 /// source is constant so it does not need to be loaded.
1969 /// It returns EVT::Other if the type should be determined using generic
1970 /// target-independent logic.
1971 EVT
1972 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1973                                        unsigned DstAlign, unsigned SrcAlign,
1974                                        bool IsMemset, bool ZeroMemset,
1975                                        bool MemcpyStrSrc,
1976                                        MachineFunction &MF) const {
1977   const Function *F = MF.getFunction();
1978   if ((!IsMemset || ZeroMemset) &&
1979       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1980     if (Size >= 16 &&
1981         (!Subtarget->isUnalignedMem16Slow() ||
1982          ((DstAlign == 0 || DstAlign >= 16) &&
1983           (SrcAlign == 0 || SrcAlign >= 16)))) {
1984       if (Size >= 32) {
1985         // FIXME: Check if unaligned 32-byte accesses are slow.
1986         if (Subtarget->hasInt256())
1987           return MVT::v8i32;
1988         if (Subtarget->hasFp256())
1989           return MVT::v8f32;
1990       }
1991       if (Subtarget->hasSSE2())
1992         return MVT::v4i32;
1993       if (Subtarget->hasSSE1())
1994         return MVT::v4f32;
1995     } else if (!MemcpyStrSrc && Size >= 8 &&
1996                !Subtarget->is64Bit() &&
1997                Subtarget->hasSSE2()) {
1998       // Do not use f64 to lower memcpy if source is string constant. It's
1999       // better to use i32 to avoid the loads.
2000       return MVT::f64;
2001     }
2002   }
2003   // This is a compromise. If we reach here, unaligned accesses may be slow on
2004   // this target. However, creating smaller, aligned accesses could be even
2005   // slower and would certainly be a lot more code.
2006   if (Subtarget->is64Bit() && Size >= 8)
2007     return MVT::i64;
2008   return MVT::i32;
2009 }
2010
2011 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2012   if (VT == MVT::f32)
2013     return X86ScalarSSEf32;
2014   else if (VT == MVT::f64)
2015     return X86ScalarSSEf64;
2016   return true;
2017 }
2018
2019 bool
2020 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2021                                                   unsigned,
2022                                                   unsigned,
2023                                                   bool *Fast) const {
2024   if (Fast) {
2025     switch (VT.getSizeInBits()) {
2026     default:
2027       // 8-byte and under are always assumed to be fast.
2028       *Fast = true;
2029       break;
2030     case 128:
2031       *Fast = !Subtarget->isUnalignedMem16Slow();
2032       break;
2033     case 256:
2034       *Fast = !Subtarget->isUnalignedMem32Slow();
2035       break;
2036     // TODO: What about AVX-512 (512-bit) accesses?
2037     }
2038   }
2039   // Misaligned accesses of any size are always allowed.
2040   return true;
2041 }
2042
2043 /// Return the entry encoding for a jump table in the
2044 /// current function.  The returned value is a member of the
2045 /// MachineJumpTableInfo::JTEntryKind enum.
2046 unsigned X86TargetLowering::getJumpTableEncoding() const {
2047   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2048   // symbol.
2049   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2050       Subtarget->isPICStyleGOT())
2051     return MachineJumpTableInfo::EK_Custom32;
2052
2053   // Otherwise, use the normal jump table encoding heuristics.
2054   return TargetLowering::getJumpTableEncoding();
2055 }
2056
2057 bool X86TargetLowering::useSoftFloat() const {
2058   return Subtarget->useSoftFloat();
2059 }
2060
2061 const MCExpr *
2062 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2063                                              const MachineBasicBlock *MBB,
2064                                              unsigned uid,MCContext &Ctx) const{
2065   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2066          Subtarget->isPICStyleGOT());
2067   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2068   // entries.
2069   return MCSymbolRefExpr::create(MBB->getSymbol(),
2070                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2071 }
2072
2073 /// Returns relocation base for the given PIC jumptable.
2074 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2075                                                     SelectionDAG &DAG) const {
2076   if (!Subtarget->is64Bit())
2077     // This doesn't have SDLoc associated with it, but is not really the
2078     // same as a Register.
2079     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2080                        getPointerTy(DAG.getDataLayout()));
2081   return Table;
2082 }
2083
2084 /// This returns the relocation base for the given PIC jumptable,
2085 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2086 const MCExpr *X86TargetLowering::
2087 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2088                              MCContext &Ctx) const {
2089   // X86-64 uses RIP relative addressing based on the jump table label.
2090   if (Subtarget->isPICStyleRIPRel())
2091     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2092
2093   // Otherwise, the reference is relative to the PIC base.
2094   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2095 }
2096
2097 std::pair<const TargetRegisterClass *, uint8_t>
2098 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2099                                            MVT VT) const {
2100   const TargetRegisterClass *RRC = nullptr;
2101   uint8_t Cost = 1;
2102   switch (VT.SimpleTy) {
2103   default:
2104     return TargetLowering::findRepresentativeClass(TRI, VT);
2105   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2106     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2107     break;
2108   case MVT::x86mmx:
2109     RRC = &X86::VR64RegClass;
2110     break;
2111   case MVT::f32: case MVT::f64:
2112   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2113   case MVT::v4f32: case MVT::v2f64:
2114   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2115   case MVT::v4f64:
2116     RRC = &X86::VR128RegClass;
2117     break;
2118   }
2119   return std::make_pair(RRC, Cost);
2120 }
2121
2122 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2123                                                unsigned &Offset) const {
2124   if (!Subtarget->isTargetLinux())
2125     return false;
2126
2127   if (Subtarget->is64Bit()) {
2128     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2129     Offset = 0x28;
2130     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2131       AddressSpace = 256;
2132     else
2133       AddressSpace = 257;
2134   } else {
2135     // %gs:0x14 on i386
2136     Offset = 0x14;
2137     AddressSpace = 256;
2138   }
2139   return true;
2140 }
2141
2142 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2143   if (!Subtarget->isTargetAndroid())
2144     return TargetLowering::getSafeStackPointerLocation(IRB);
2145
2146   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2147   // definition of TLS_SLOT_SAFESTACK in
2148   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2149   unsigned AddressSpace, Offset;
2150   if (Subtarget->is64Bit()) {
2151     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2152     Offset = 0x48;
2153     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2154       AddressSpace = 256;
2155     else
2156       AddressSpace = 257;
2157   } else {
2158     // %gs:0x24 on i386
2159     Offset = 0x24;
2160     AddressSpace = 256;
2161   }
2162
2163   return ConstantExpr::getIntToPtr(
2164       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2165       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2166 }
2167
2168 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2169                                             unsigned DestAS) const {
2170   assert(SrcAS != DestAS && "Expected different address spaces!");
2171
2172   return SrcAS < 256 && DestAS < 256;
2173 }
2174
2175 //===----------------------------------------------------------------------===//
2176 //               Return Value Calling Convention Implementation
2177 //===----------------------------------------------------------------------===//
2178
2179 #include "X86GenCallingConv.inc"
2180
2181 bool X86TargetLowering::CanLowerReturn(
2182     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2183     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2184   SmallVector<CCValAssign, 16> RVLocs;
2185   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2186   return CCInfo.CheckReturn(Outs, RetCC_X86);
2187 }
2188
2189 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2190   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2191   return ScratchRegs;
2192 }
2193
2194 SDValue
2195 X86TargetLowering::LowerReturn(SDValue Chain,
2196                                CallingConv::ID CallConv, bool isVarArg,
2197                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2198                                const SmallVectorImpl<SDValue> &OutVals,
2199                                SDLoc dl, SelectionDAG &DAG) const {
2200   MachineFunction &MF = DAG.getMachineFunction();
2201   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2202
2203   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2204     report_fatal_error("X86 interrupts may not return any value");
2205
2206   SmallVector<CCValAssign, 16> RVLocs;
2207   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2208   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2209
2210   SDValue Flag;
2211   SmallVector<SDValue, 6> RetOps;
2212   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2213   // Operand #1 = Bytes To Pop
2214   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2215                    MVT::i16));
2216
2217   // Copy the result values into the output registers.
2218   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2219     CCValAssign &VA = RVLocs[i];
2220     assert(VA.isRegLoc() && "Can only return in registers!");
2221     SDValue ValToCopy = OutVals[i];
2222     EVT ValVT = ValToCopy.getValueType();
2223
2224     // Promote values to the appropriate types.
2225     if (VA.getLocInfo() == CCValAssign::SExt)
2226       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2227     else if (VA.getLocInfo() == CCValAssign::ZExt)
2228       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2229     else if (VA.getLocInfo() == CCValAssign::AExt) {
2230       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2231         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2232       else
2233         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2234     }
2235     else if (VA.getLocInfo() == CCValAssign::BCvt)
2236       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2237
2238     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2239            "Unexpected FP-extend for return value.");
2240
2241     // If this is x86-64, and we disabled SSE, we can't return FP values,
2242     // or SSE or MMX vectors.
2243     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2244          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2245           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2246       report_fatal_error("SSE register return with SSE disabled");
2247     }
2248     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2249     // llvm-gcc has never done it right and no one has noticed, so this
2250     // should be OK for now.
2251     if (ValVT == MVT::f64 &&
2252         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2253       report_fatal_error("SSE2 register return with SSE2 disabled");
2254
2255     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2256     // the RET instruction and handled by the FP Stackifier.
2257     if (VA.getLocReg() == X86::FP0 ||
2258         VA.getLocReg() == X86::FP1) {
2259       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2260       // change the value to the FP stack register class.
2261       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2262         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2263       RetOps.push_back(ValToCopy);
2264       // Don't emit a copytoreg.
2265       continue;
2266     }
2267
2268     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2269     // which is returned in RAX / RDX.
2270     if (Subtarget->is64Bit()) {
2271       if (ValVT == MVT::x86mmx) {
2272         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2273           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2274           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2275                                   ValToCopy);
2276           // If we don't have SSE2 available, convert to v4f32 so the generated
2277           // register is legal.
2278           if (!Subtarget->hasSSE2())
2279             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2280         }
2281       }
2282     }
2283
2284     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2285     Flag = Chain.getValue(1);
2286     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2287   }
2288
2289   // All x86 ABIs require that for returning structs by value we copy
2290   // the sret argument into %rax/%eax (depending on ABI) for the return.
2291   // We saved the argument into a virtual register in the entry block,
2292   // so now we copy the value out and into %rax/%eax.
2293   //
2294   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2295   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2296   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2297   // either case FuncInfo->setSRetReturnReg() will have been called.
2298   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2299     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2300                                      getPointerTy(MF.getDataLayout()));
2301
2302     unsigned RetValReg
2303         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2304           X86::RAX : X86::EAX;
2305     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2306     Flag = Chain.getValue(1);
2307
2308     // RAX/EAX now acts like a return value.
2309     RetOps.push_back(
2310         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2311   }
2312
2313   RetOps[0] = Chain;  // Update chain.
2314
2315   // Add the flag if we have it.
2316   if (Flag.getNode())
2317     RetOps.push_back(Flag);
2318
2319   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2320   if (CallConv == CallingConv::X86_INTR)
2321     opcode = X86ISD::IRET;
2322   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2323 }
2324
2325 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2326   if (N->getNumValues() != 1)
2327     return false;
2328   if (!N->hasNUsesOfValue(1, 0))
2329     return false;
2330
2331   SDValue TCChain = Chain;
2332   SDNode *Copy = *N->use_begin();
2333   if (Copy->getOpcode() == ISD::CopyToReg) {
2334     // If the copy has a glue operand, we conservatively assume it isn't safe to
2335     // perform a tail call.
2336     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2337       return false;
2338     TCChain = Copy->getOperand(0);
2339   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2340     return false;
2341
2342   bool HasRet = false;
2343   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2344        UI != UE; ++UI) {
2345     if (UI->getOpcode() != X86ISD::RET_FLAG)
2346       return false;
2347     // If we are returning more than one value, we can definitely
2348     // not make a tail call see PR19530
2349     if (UI->getNumOperands() > 4)
2350       return false;
2351     if (UI->getNumOperands() == 4 &&
2352         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2353       return false;
2354     HasRet = true;
2355   }
2356
2357   if (!HasRet)
2358     return false;
2359
2360   Chain = TCChain;
2361   return true;
2362 }
2363
2364 EVT
2365 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2366                                             ISD::NodeType ExtendKind) const {
2367   MVT ReturnMVT;
2368   // TODO: Is this also valid on 32-bit?
2369   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2370     ReturnMVT = MVT::i8;
2371   else
2372     ReturnMVT = MVT::i32;
2373
2374   EVT MinVT = getRegisterType(Context, ReturnMVT);
2375   return VT.bitsLT(MinVT) ? MinVT : VT;
2376 }
2377
2378 /// Lower the result values of a call into the
2379 /// appropriate copies out of appropriate physical registers.
2380 ///
2381 SDValue
2382 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2383                                    CallingConv::ID CallConv, bool isVarArg,
2384                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2385                                    SDLoc dl, SelectionDAG &DAG,
2386                                    SmallVectorImpl<SDValue> &InVals) const {
2387
2388   // Assign locations to each value returned by this call.
2389   SmallVector<CCValAssign, 16> RVLocs;
2390   bool Is64Bit = Subtarget->is64Bit();
2391   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2392                  *DAG.getContext());
2393   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2394
2395   // Copy all of the result registers out of their specified physreg.
2396   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2397     CCValAssign &VA = RVLocs[i];
2398     EVT CopyVT = VA.getLocVT();
2399
2400     // If this is x86-64, and we disabled SSE, we can't return FP values
2401     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2402         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2403       report_fatal_error("SSE register return with SSE disabled");
2404     }
2405
2406     // If we prefer to use the value in xmm registers, copy it out as f80 and
2407     // use a truncate to move it from fp stack reg to xmm reg.
2408     bool RoundAfterCopy = false;
2409     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2410         isScalarFPTypeInSSEReg(VA.getValVT())) {
2411       CopyVT = MVT::f80;
2412       RoundAfterCopy = (CopyVT != VA.getLocVT());
2413     }
2414
2415     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2416                                CopyVT, InFlag).getValue(1);
2417     SDValue Val = Chain.getValue(0);
2418
2419     if (RoundAfterCopy)
2420       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2421                         // This truncation won't change the value.
2422                         DAG.getIntPtrConstant(1, dl));
2423
2424     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2425       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2426
2427     InFlag = Chain.getValue(2);
2428     InVals.push_back(Val);
2429   }
2430
2431   return Chain;
2432 }
2433
2434 //===----------------------------------------------------------------------===//
2435 //                C & StdCall & Fast Calling Convention implementation
2436 //===----------------------------------------------------------------------===//
2437 //  StdCall calling convention seems to be standard for many Windows' API
2438 //  routines and around. It differs from C calling convention just a little:
2439 //  callee should clean up the stack, not caller. Symbols should be also
2440 //  decorated in some fancy way :) It doesn't support any vector arguments.
2441 //  For info on fast calling convention see Fast Calling Convention (tail call)
2442 //  implementation LowerX86_32FastCCCallTo.
2443
2444 /// CallIsStructReturn - Determines whether a call uses struct return
2445 /// semantics.
2446 enum StructReturnType {
2447   NotStructReturn,
2448   RegStructReturn,
2449   StackStructReturn
2450 };
2451 static StructReturnType
2452 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2453   if (Outs.empty())
2454     return NotStructReturn;
2455
2456   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2457   if (!Flags.isSRet())
2458     return NotStructReturn;
2459   if (Flags.isInReg() || IsMCU)
2460     return RegStructReturn;
2461   return StackStructReturn;
2462 }
2463
2464 /// Determines whether a function uses struct return semantics.
2465 static StructReturnType
2466 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2467   if (Ins.empty())
2468     return NotStructReturn;
2469
2470   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2471   if (!Flags.isSRet())
2472     return NotStructReturn;
2473   if (Flags.isInReg() || IsMCU)
2474     return RegStructReturn;
2475   return StackStructReturn;
2476 }
2477
2478 /// Make a copy of an aggregate at address specified by "Src" to address
2479 /// "Dst" with size and alignment information specified by the specific
2480 /// parameter attribute. The copy will be passed as a byval function parameter.
2481 static SDValue
2482 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2483                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2484                           SDLoc dl) {
2485   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2486
2487   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2488                        /*isVolatile*/false, /*AlwaysInline=*/true,
2489                        /*isTailCall*/false,
2490                        MachinePointerInfo(), MachinePointerInfo());
2491 }
2492
2493 /// Return true if the calling convention is one that we can guarantee TCO for.
2494 static bool canGuaranteeTCO(CallingConv::ID CC) {
2495   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2496           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2497 }
2498
2499 /// Return true if we might ever do TCO for calls with this calling convention.
2500 static bool mayTailCallThisCC(CallingConv::ID CC) {
2501   switch (CC) {
2502   // C calling conventions:
2503   case CallingConv::C:
2504   case CallingConv::X86_64_Win64:
2505   case CallingConv::X86_64_SysV:
2506   // Callee pop conventions:
2507   case CallingConv::X86_ThisCall:
2508   case CallingConv::X86_StdCall:
2509   case CallingConv::X86_VectorCall:
2510   case CallingConv::X86_FastCall:
2511     return true;
2512   default:
2513     return canGuaranteeTCO(CC);
2514   }
2515 }
2516
2517 /// Return true if the function is being made into a tailcall target by
2518 /// changing its ABI.
2519 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2520   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2521 }
2522
2523 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2524   auto Attr =
2525       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2526   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2527     return false;
2528
2529   CallSite CS(CI);
2530   CallingConv::ID CalleeCC = CS.getCallingConv();
2531   if (!mayTailCallThisCC(CalleeCC))
2532     return false;
2533
2534   return true;
2535 }
2536
2537 SDValue
2538 X86TargetLowering::LowerMemArgument(SDValue Chain,
2539                                     CallingConv::ID CallConv,
2540                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2541                                     SDLoc dl, SelectionDAG &DAG,
2542                                     const CCValAssign &VA,
2543                                     MachineFrameInfo *MFI,
2544                                     unsigned i) const {
2545   // Create the nodes corresponding to a load from this parameter slot.
2546   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2547   bool AlwaysUseMutable = shouldGuaranteeTCO(
2548       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2549   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2550   EVT ValVT;
2551
2552   // If value is passed by pointer we have address passed instead of the value
2553   // itself.
2554   bool ExtendedInMem = VA.isExtInLoc() &&
2555     VA.getValVT().getScalarType() == MVT::i1;
2556
2557   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2558     ValVT = VA.getLocVT();
2559   else
2560     ValVT = VA.getValVT();
2561
2562   // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2563   // taken by a return address.
2564   int Offset = 0;
2565   if (CallConv == CallingConv::X86_INTR) {
2566     const X86Subtarget& Subtarget =
2567         static_cast<const X86Subtarget&>(DAG.getSubtarget());
2568     // X86 interrupts may take one or two arguments.
2569     // On the stack there will be no return address as in regular call.
2570     // Offset of last argument need to be set to -4/-8 bytes.
2571     // Where offset of the first argument out of two, should be set to 0 bytes.
2572     Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2573   }
2574
2575   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2576   // changed with more analysis.
2577   // In case of tail call optimization mark all arguments mutable. Since they
2578   // could be overwritten by lowering of arguments in case of a tail call.
2579   if (Flags.isByVal()) {
2580     unsigned Bytes = Flags.getByValSize();
2581     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2582     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2583     // Adjust SP offset of interrupt parameter.
2584     if (CallConv == CallingConv::X86_INTR) {
2585       MFI->setObjectOffset(FI, Offset);
2586     }
2587     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2588   } else {
2589     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2590                                     VA.getLocMemOffset(), isImmutable);
2591     // Adjust SP offset of interrupt parameter.
2592     if (CallConv == CallingConv::X86_INTR) {
2593       MFI->setObjectOffset(FI, Offset);
2594     }
2595
2596     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2597     SDValue Val = DAG.getLoad(
2598         ValVT, dl, Chain, FIN,
2599         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2600         false, false, 0);
2601     return ExtendedInMem ?
2602       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2603   }
2604 }
2605
2606 // FIXME: Get this from tablegen.
2607 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2608                                                 const X86Subtarget *Subtarget) {
2609   assert(Subtarget->is64Bit());
2610
2611   if (Subtarget->isCallingConvWin64(CallConv)) {
2612     static const MCPhysReg GPR64ArgRegsWin64[] = {
2613       X86::RCX, X86::RDX, X86::R8,  X86::R9
2614     };
2615     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2616   }
2617
2618   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2619     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2620   };
2621   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2622 }
2623
2624 // FIXME: Get this from tablegen.
2625 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2626                                                 CallingConv::ID CallConv,
2627                                                 const X86Subtarget *Subtarget) {
2628   assert(Subtarget->is64Bit());
2629   if (Subtarget->isCallingConvWin64(CallConv)) {
2630     // The XMM registers which might contain var arg parameters are shadowed
2631     // in their paired GPR.  So we only need to save the GPR to their home
2632     // slots.
2633     // TODO: __vectorcall will change this.
2634     return None;
2635   }
2636
2637   const Function *Fn = MF.getFunction();
2638   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2639   bool isSoftFloat = Subtarget->useSoftFloat();
2640   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2641          "SSE register cannot be used when SSE is disabled!");
2642   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2643     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2644     // registers.
2645     return None;
2646
2647   static const MCPhysReg XMMArgRegs64Bit[] = {
2648     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2649     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2650   };
2651   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2652 }
2653
2654 SDValue X86TargetLowering::LowerFormalArguments(
2655     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2656     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2657     SmallVectorImpl<SDValue> &InVals) const {
2658   MachineFunction &MF = DAG.getMachineFunction();
2659   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2660   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2661
2662   const Function* Fn = MF.getFunction();
2663   if (Fn->hasExternalLinkage() &&
2664       Subtarget->isTargetCygMing() &&
2665       Fn->getName() == "main")
2666     FuncInfo->setForceFramePointer(true);
2667
2668   MachineFrameInfo *MFI = MF.getFrameInfo();
2669   bool Is64Bit = Subtarget->is64Bit();
2670   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2671
2672   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2673          "Var args not supported with calling convention fastcc, ghc or hipe");
2674
2675   if (CallConv == CallingConv::X86_INTR) {
2676     bool isLegal = Ins.size() == 1 ||
2677                    (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2678                                         (!Is64Bit && Ins[1].VT == MVT::i32)));
2679     if (!isLegal)
2680       report_fatal_error("X86 interrupts may take one or two arguments");
2681   }
2682
2683   // Assign locations to all of the incoming arguments.
2684   SmallVector<CCValAssign, 16> ArgLocs;
2685   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2686
2687   // Allocate shadow area for Win64
2688   if (IsWin64)
2689     CCInfo.AllocateStack(32, 8);
2690
2691   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2692
2693   unsigned LastVal = ~0U;
2694   SDValue ArgValue;
2695   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696     CCValAssign &VA = ArgLocs[i];
2697     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2698     // places.
2699     assert(VA.getValNo() != LastVal &&
2700            "Don't support value assigned to multiple locs yet");
2701     (void)LastVal;
2702     LastVal = VA.getValNo();
2703
2704     if (VA.isRegLoc()) {
2705       EVT RegVT = VA.getLocVT();
2706       const TargetRegisterClass *RC;
2707       if (RegVT == MVT::i32)
2708         RC = &X86::GR32RegClass;
2709       else if (Is64Bit && RegVT == MVT::i64)
2710         RC = &X86::GR64RegClass;
2711       else if (RegVT == MVT::f32)
2712         RC = &X86::FR32RegClass;
2713       else if (RegVT == MVT::f64)
2714         RC = &X86::FR64RegClass;
2715       else if (RegVT == MVT::f128)
2716         RC = &X86::FR128RegClass;
2717       else if (RegVT.is512BitVector())
2718         RC = &X86::VR512RegClass;
2719       else if (RegVT.is256BitVector())
2720         RC = &X86::VR256RegClass;
2721       else if (RegVT.is128BitVector())
2722         RC = &X86::VR128RegClass;
2723       else if (RegVT == MVT::x86mmx)
2724         RC = &X86::VR64RegClass;
2725       else if (RegVT == MVT::i1)
2726         RC = &X86::VK1RegClass;
2727       else if (RegVT == MVT::v8i1)
2728         RC = &X86::VK8RegClass;
2729       else if (RegVT == MVT::v16i1)
2730         RC = &X86::VK16RegClass;
2731       else if (RegVT == MVT::v32i1)
2732         RC = &X86::VK32RegClass;
2733       else if (RegVT == MVT::v64i1)
2734         RC = &X86::VK64RegClass;
2735       else
2736         llvm_unreachable("Unknown argument type!");
2737
2738       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2739       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2740
2741       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2742       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2743       // right size.
2744       if (VA.getLocInfo() == CCValAssign::SExt)
2745         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2746                                DAG.getValueType(VA.getValVT()));
2747       else if (VA.getLocInfo() == CCValAssign::ZExt)
2748         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2749                                DAG.getValueType(VA.getValVT()));
2750       else if (VA.getLocInfo() == CCValAssign::BCvt)
2751         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2752
2753       if (VA.isExtInLoc()) {
2754         // Handle MMX values passed in XMM regs.
2755         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2756           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2757         else
2758           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2759       }
2760     } else {
2761       assert(VA.isMemLoc());
2762       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2763     }
2764
2765     // If value is passed via pointer - do a load.
2766     if (VA.getLocInfo() == CCValAssign::Indirect)
2767       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2768                              MachinePointerInfo(), false, false, false, 0);
2769
2770     InVals.push_back(ArgValue);
2771   }
2772
2773   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2774     // All x86 ABIs require that for returning structs by value we copy the
2775     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2776     // the argument into a virtual register so that we can access it from the
2777     // return points.
2778     if (Ins[i].Flags.isSRet()) {
2779       unsigned Reg = FuncInfo->getSRetReturnReg();
2780       if (!Reg) {
2781         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2782         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2783         FuncInfo->setSRetReturnReg(Reg);
2784       }
2785       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2786       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2787       break;
2788     }
2789   }
2790
2791   unsigned StackSize = CCInfo.getNextStackOffset();
2792   // Align stack specially for tail calls.
2793   if (shouldGuaranteeTCO(CallConv,
2794                          MF.getTarget().Options.GuaranteedTailCallOpt))
2795     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2796
2797   // If the function takes variable number of arguments, make a frame index for
2798   // the start of the first vararg value... for expansion of llvm.va_start. We
2799   // can skip this if there are no va_start calls.
2800   if (MFI->hasVAStart() &&
2801       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2802                    CallConv != CallingConv::X86_ThisCall))) {
2803     FuncInfo->setVarArgsFrameIndex(
2804         MFI->CreateFixedObject(1, StackSize, true));
2805   }
2806
2807   // Figure out if XMM registers are in use.
2808   assert(!(Subtarget->useSoftFloat() &&
2809            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2810          "SSE register cannot be used when SSE is disabled!");
2811
2812   // 64-bit calling conventions support varargs and register parameters, so we
2813   // have to do extra work to spill them in the prologue.
2814   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2815     // Find the first unallocated argument registers.
2816     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2817     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2818     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2819     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2820     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2821            "SSE register cannot be used when SSE is disabled!");
2822
2823     // Gather all the live in physical registers.
2824     SmallVector<SDValue, 6> LiveGPRs;
2825     SmallVector<SDValue, 8> LiveXMMRegs;
2826     SDValue ALVal;
2827     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2828       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2829       LiveGPRs.push_back(
2830           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2831     }
2832     if (!ArgXMMs.empty()) {
2833       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2834       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2835       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2836         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2837         LiveXMMRegs.push_back(
2838             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2839       }
2840     }
2841
2842     if (IsWin64) {
2843       // Get to the caller-allocated home save location.  Add 8 to account
2844       // for the return address.
2845       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2846       FuncInfo->setRegSaveFrameIndex(
2847           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2848       // Fixup to set vararg frame on shadow area (4 x i64).
2849       if (NumIntRegs < 4)
2850         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2851     } else {
2852       // For X86-64, if there are vararg parameters that are passed via
2853       // registers, then we must store them to their spots on the stack so
2854       // they may be loaded by deferencing the result of va_next.
2855       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2856       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2857       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2858           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2859     }
2860
2861     // Store the integer parameter registers.
2862     SmallVector<SDValue, 8> MemOps;
2863     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2864                                       getPointerTy(DAG.getDataLayout()));
2865     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2866     for (SDValue Val : LiveGPRs) {
2867       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2868                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2869       SDValue Store =
2870           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2871                        MachinePointerInfo::getFixedStack(
2872                            DAG.getMachineFunction(),
2873                            FuncInfo->getRegSaveFrameIndex(), Offset),
2874                        false, false, 0);
2875       MemOps.push_back(Store);
2876       Offset += 8;
2877     }
2878
2879     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2880       // Now store the XMM (fp + vector) parameter registers.
2881       SmallVector<SDValue, 12> SaveXMMOps;
2882       SaveXMMOps.push_back(Chain);
2883       SaveXMMOps.push_back(ALVal);
2884       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2885                              FuncInfo->getRegSaveFrameIndex(), dl));
2886       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2887                              FuncInfo->getVarArgsFPOffset(), dl));
2888       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2889                         LiveXMMRegs.end());
2890       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2891                                    MVT::Other, SaveXMMOps));
2892     }
2893
2894     if (!MemOps.empty())
2895       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2896   }
2897
2898   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2899     // Find the largest legal vector type.
2900     MVT VecVT = MVT::Other;
2901     // FIXME: Only some x86_32 calling conventions support AVX512.
2902     if (Subtarget->hasAVX512() &&
2903         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2904                      CallConv == CallingConv::Intel_OCL_BI)))
2905       VecVT = MVT::v16f32;
2906     else if (Subtarget->hasAVX())
2907       VecVT = MVT::v8f32;
2908     else if (Subtarget->hasSSE2())
2909       VecVT = MVT::v4f32;
2910
2911     // We forward some GPRs and some vector types.
2912     SmallVector<MVT, 2> RegParmTypes;
2913     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2914     RegParmTypes.push_back(IntVT);
2915     if (VecVT != MVT::Other)
2916       RegParmTypes.push_back(VecVT);
2917
2918     // Compute the set of forwarded registers. The rest are scratch.
2919     SmallVectorImpl<ForwardedRegister> &Forwards =
2920         FuncInfo->getForwardedMustTailRegParms();
2921     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2922
2923     // Conservatively forward AL on x86_64, since it might be used for varargs.
2924     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2925       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2926       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2927     }
2928
2929     // Copy all forwards from physical to virtual registers.
2930     for (ForwardedRegister &F : Forwards) {
2931       // FIXME: Can we use a less constrained schedule?
2932       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2933       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2934       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2935     }
2936   }
2937
2938   // Some CCs need callee pop.
2939   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2940                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2941     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2942   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2943     // X86 interrupts must pop the error code if present
2944     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2945   } else {
2946     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2947     // If this is an sret function, the return should pop the hidden pointer.
2948     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2949         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2950         argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2951       FuncInfo->setBytesToPopOnReturn(4);
2952   }
2953
2954   if (!Is64Bit) {
2955     // RegSaveFrameIndex is X86-64 only.
2956     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2957     if (CallConv == CallingConv::X86_FastCall ||
2958         CallConv == CallingConv::X86_ThisCall)
2959       // fastcc functions can't have varargs.
2960       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2961   }
2962
2963   FuncInfo->setArgumentStackSize(StackSize);
2964
2965   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2966     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2967     if (Personality == EHPersonality::CoreCLR) {
2968       assert(Is64Bit);
2969       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2970       // that we'd prefer this slot be allocated towards the bottom of the frame
2971       // (i.e. near the stack pointer after allocating the frame).  Every
2972       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2973       // offset from the bottom of this and each funclet's frame must be the
2974       // same, so the size of funclets' (mostly empty) frames is dictated by
2975       // how far this slot is from the bottom (since they allocate just enough
2976       // space to accomodate holding this slot at the correct offset).
2977       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2978       EHInfo->PSPSymFrameIdx = PSPSymFI;
2979     }
2980   }
2981
2982   return Chain;
2983 }
2984
2985 SDValue
2986 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2987                                     SDValue StackPtr, SDValue Arg,
2988                                     SDLoc dl, SelectionDAG &DAG,
2989                                     const CCValAssign &VA,
2990                                     ISD::ArgFlagsTy Flags) const {
2991   unsigned LocMemOffset = VA.getLocMemOffset();
2992   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2993   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2994                        StackPtr, PtrOff);
2995   if (Flags.isByVal())
2996     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2997
2998   return DAG.getStore(
2999       Chain, dl, Arg, PtrOff,
3000       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3001       false, false, 0);
3002 }
3003
3004 /// Emit a load of return address if tail call
3005 /// optimization is performed and it is required.
3006 SDValue
3007 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3008                                            SDValue &OutRetAddr, SDValue Chain,
3009                                            bool IsTailCall, bool Is64Bit,
3010                                            int FPDiff, SDLoc dl) const {
3011   // Adjust the Return address stack slot.
3012   EVT VT = getPointerTy(DAG.getDataLayout());
3013   OutRetAddr = getReturnAddressFrameIndex(DAG);
3014
3015   // Load the "old" Return address.
3016   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3017                            false, false, false, 0);
3018   return SDValue(OutRetAddr.getNode(), 1);
3019 }
3020
3021 /// Emit a store of the return address if tail call
3022 /// optimization is performed and it is required (FPDiff!=0).
3023 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3024                                         SDValue Chain, SDValue RetAddrFrIdx,
3025                                         EVT PtrVT, unsigned SlotSize,
3026                                         int FPDiff, SDLoc dl) {
3027   // Store the return address to the appropriate stack slot.
3028   if (!FPDiff) return Chain;
3029   // Calculate the new stack slot for the return address.
3030   int NewReturnAddrFI =
3031     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3032                                          false);
3033   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3034   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3035                        MachinePointerInfo::getFixedStack(
3036                            DAG.getMachineFunction(), NewReturnAddrFI),
3037                        false, false, 0);
3038   return Chain;
3039 }
3040
3041 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3042 /// operation of specified width.
3043 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3044                        SDValue V2) {
3045   unsigned NumElems = VT.getVectorNumElements();
3046   SmallVector<int, 8> Mask;
3047   Mask.push_back(NumElems);
3048   for (unsigned i = 1; i != NumElems; ++i)
3049     Mask.push_back(i);
3050   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3051 }
3052
3053 SDValue
3054 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3055                              SmallVectorImpl<SDValue> &InVals) const {
3056   SelectionDAG &DAG                     = CLI.DAG;
3057   SDLoc &dl                             = CLI.DL;
3058   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3059   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3060   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3061   SDValue Chain                         = CLI.Chain;
3062   SDValue Callee                        = CLI.Callee;
3063   CallingConv::ID CallConv              = CLI.CallConv;
3064   bool &isTailCall                      = CLI.IsTailCall;
3065   bool isVarArg                         = CLI.IsVarArg;
3066
3067   MachineFunction &MF = DAG.getMachineFunction();
3068   bool Is64Bit        = Subtarget->is64Bit();
3069   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3070   StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3071   bool IsSibcall      = false;
3072   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3073   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3074
3075   if (CallConv == CallingConv::X86_INTR)
3076     report_fatal_error("X86 interrupts may not be called directly");
3077
3078   if (Attr.getValueAsString() == "true")
3079     isTailCall = false;
3080
3081   if (Subtarget->isPICStyleGOT() &&
3082       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3083     // If we are using a GOT, disable tail calls to external symbols with
3084     // default visibility. Tail calling such a symbol requires using a GOT
3085     // relocation, which forces early binding of the symbol. This breaks code
3086     // that require lazy function symbol resolution. Using musttail or
3087     // GuaranteedTailCallOpt will override this.
3088     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3089     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3090                G->getGlobal()->hasDefaultVisibility()))
3091       isTailCall = false;
3092   }
3093
3094   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3095   if (IsMustTail) {
3096     // Force this to be a tail call.  The verifier rules are enough to ensure
3097     // that we can lower this successfully without moving the return address
3098     // around.
3099     isTailCall = true;
3100   } else if (isTailCall) {
3101     // Check if it's really possible to do a tail call.
3102     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3103                     isVarArg, SR != NotStructReturn,
3104                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3105                     Outs, OutVals, Ins, DAG);
3106
3107     // Sibcalls are automatically detected tailcalls which do not require
3108     // ABI changes.
3109     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3110       IsSibcall = true;
3111
3112     if (isTailCall)
3113       ++NumTailCalls;
3114   }
3115
3116   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3117          "Var args not supported with calling convention fastcc, ghc or hipe");
3118
3119   // Analyze operands of the call, assigning locations to each operand.
3120   SmallVector<CCValAssign, 16> ArgLocs;
3121   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3122
3123   // Allocate shadow area for Win64
3124   if (IsWin64)
3125     CCInfo.AllocateStack(32, 8);
3126
3127   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3128
3129   // Get a count of how many bytes are to be pushed on the stack.
3130   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3131   if (IsSibcall)
3132     // This is a sibcall. The memory operands are available in caller's
3133     // own caller's stack.
3134     NumBytes = 0;
3135   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3136            canGuaranteeTCO(CallConv))
3137     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3138
3139   int FPDiff = 0;
3140   if (isTailCall && !IsSibcall && !IsMustTail) {
3141     // Lower arguments at fp - stackoffset + fpdiff.
3142     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3143
3144     FPDiff = NumBytesCallerPushed - NumBytes;
3145
3146     // Set the delta of movement of the returnaddr stackslot.
3147     // But only set if delta is greater than previous delta.
3148     if (FPDiff < X86Info->getTCReturnAddrDelta())
3149       X86Info->setTCReturnAddrDelta(FPDiff);
3150   }
3151
3152   unsigned NumBytesToPush = NumBytes;
3153   unsigned NumBytesToPop = NumBytes;
3154
3155   // If we have an inalloca argument, all stack space has already been allocated
3156   // for us and be right at the top of the stack.  We don't support multiple
3157   // arguments passed in memory when using inalloca.
3158   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3159     NumBytesToPush = 0;
3160     if (!ArgLocs.back().isMemLoc())
3161       report_fatal_error("cannot use inalloca attribute on a register "
3162                          "parameter");
3163     if (ArgLocs.back().getLocMemOffset() != 0)
3164       report_fatal_error("any parameter with the inalloca attribute must be "
3165                          "the only memory argument");
3166   }
3167
3168   if (!IsSibcall)
3169     Chain = DAG.getCALLSEQ_START(
3170         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3171
3172   SDValue RetAddrFrIdx;
3173   // Load return address for tail calls.
3174   if (isTailCall && FPDiff)
3175     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3176                                     Is64Bit, FPDiff, dl);
3177
3178   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3179   SmallVector<SDValue, 8> MemOpChains;
3180   SDValue StackPtr;
3181
3182   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3183   // of tail call optimization arguments are handle later.
3184   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3185   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3186     // Skip inalloca arguments, they have already been written.
3187     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3188     if (Flags.isInAlloca())
3189       continue;
3190
3191     CCValAssign &VA = ArgLocs[i];
3192     EVT RegVT = VA.getLocVT();
3193     SDValue Arg = OutVals[i];
3194     bool isByVal = Flags.isByVal();
3195
3196     // Promote the value if needed.
3197     switch (VA.getLocInfo()) {
3198     default: llvm_unreachable("Unknown loc info!");
3199     case CCValAssign::Full: break;
3200     case CCValAssign::SExt:
3201       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3202       break;
3203     case CCValAssign::ZExt:
3204       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3205       break;
3206     case CCValAssign::AExt:
3207       if (Arg.getValueType().isVector() &&
3208           Arg.getValueType().getVectorElementType() == MVT::i1)
3209         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3210       else if (RegVT.is128BitVector()) {
3211         // Special case: passing MMX values in XMM registers.
3212         Arg = DAG.getBitcast(MVT::i64, Arg);
3213         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3214         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3215       } else
3216         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3217       break;
3218     case CCValAssign::BCvt:
3219       Arg = DAG.getBitcast(RegVT, Arg);
3220       break;
3221     case CCValAssign::Indirect: {
3222       // Store the argument.
3223       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3224       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3225       Chain = DAG.getStore(
3226           Chain, dl, Arg, SpillSlot,
3227           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3228           false, false, 0);
3229       Arg = SpillSlot;
3230       break;
3231     }
3232     }
3233
3234     if (VA.isRegLoc()) {
3235       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3236       if (isVarArg && IsWin64) {
3237         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3238         // shadow reg if callee is a varargs function.
3239         unsigned ShadowReg = 0;
3240         switch (VA.getLocReg()) {
3241         case X86::XMM0: ShadowReg = X86::RCX; break;
3242         case X86::XMM1: ShadowReg = X86::RDX; break;
3243         case X86::XMM2: ShadowReg = X86::R8; break;
3244         case X86::XMM3: ShadowReg = X86::R9; break;
3245         }
3246         if (ShadowReg)
3247           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3248       }
3249     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3250       assert(VA.isMemLoc());
3251       if (!StackPtr.getNode())
3252         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3253                                       getPointerTy(DAG.getDataLayout()));
3254       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3255                                              dl, DAG, VA, Flags));
3256     }
3257   }
3258
3259   if (!MemOpChains.empty())
3260     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3261
3262   if (Subtarget->isPICStyleGOT()) {
3263     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3264     // GOT pointer.
3265     if (!isTailCall) {
3266       RegsToPass.push_back(std::make_pair(
3267           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3268                                           getPointerTy(DAG.getDataLayout()))));
3269     } else {
3270       // If we are tail calling and generating PIC/GOT style code load the
3271       // address of the callee into ECX. The value in ecx is used as target of
3272       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3273       // for tail calls on PIC/GOT architectures. Normally we would just put the
3274       // address of GOT into ebx and then call target@PLT. But for tail calls
3275       // ebx would be restored (since ebx is callee saved) before jumping to the
3276       // target@PLT.
3277
3278       // Note: The actual moving to ECX is done further down.
3279       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3280       if (G && !G->getGlobal()->hasLocalLinkage() &&
3281           G->getGlobal()->hasDefaultVisibility())
3282         Callee = LowerGlobalAddress(Callee, DAG);
3283       else if (isa<ExternalSymbolSDNode>(Callee))
3284         Callee = LowerExternalSymbol(Callee, DAG);
3285     }
3286   }
3287
3288   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3289     // From AMD64 ABI document:
3290     // For calls that may call functions that use varargs or stdargs
3291     // (prototype-less calls or calls to functions containing ellipsis (...) in
3292     // the declaration) %al is used as hidden argument to specify the number
3293     // of SSE registers used. The contents of %al do not need to match exactly
3294     // the number of registers, but must be an ubound on the number of SSE
3295     // registers used and is in the range 0 - 8 inclusive.
3296
3297     // Count the number of XMM registers allocated.
3298     static const MCPhysReg XMMArgRegs[] = {
3299       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3300       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3301     };
3302     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3303     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3304            && "SSE registers cannot be used when SSE is disabled");
3305
3306     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3307                                         DAG.getConstant(NumXMMRegs, dl,
3308                                                         MVT::i8)));
3309   }
3310
3311   if (isVarArg && IsMustTail) {
3312     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3313     for (const auto &F : Forwards) {
3314       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3315       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3316     }
3317   }
3318
3319   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3320   // don't need this because the eligibility check rejects calls that require
3321   // shuffling arguments passed in memory.
3322   if (!IsSibcall && isTailCall) {
3323     // Force all the incoming stack arguments to be loaded from the stack
3324     // before any new outgoing arguments are stored to the stack, because the
3325     // outgoing stack slots may alias the incoming argument stack slots, and
3326     // the alias isn't otherwise explicit. This is slightly more conservative
3327     // than necessary, because it means that each store effectively depends
3328     // on every argument instead of just those arguments it would clobber.
3329     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3330
3331     SmallVector<SDValue, 8> MemOpChains2;
3332     SDValue FIN;
3333     int FI = 0;
3334     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3335       CCValAssign &VA = ArgLocs[i];
3336       if (VA.isRegLoc())
3337         continue;
3338       assert(VA.isMemLoc());
3339       SDValue Arg = OutVals[i];
3340       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3341       // Skip inalloca arguments.  They don't require any work.
3342       if (Flags.isInAlloca())
3343         continue;
3344       // Create frame index.
3345       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3346       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3347       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3348       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3349
3350       if (Flags.isByVal()) {
3351         // Copy relative to framepointer.
3352         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3353         if (!StackPtr.getNode())
3354           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3355                                         getPointerTy(DAG.getDataLayout()));
3356         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3357                              StackPtr, Source);
3358
3359         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3360                                                          ArgChain,
3361                                                          Flags, DAG, dl));
3362       } else {
3363         // Store relative to framepointer.
3364         MemOpChains2.push_back(DAG.getStore(
3365             ArgChain, dl, Arg, FIN,
3366             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3367             false, false, 0));
3368       }
3369     }
3370
3371     if (!MemOpChains2.empty())
3372       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3373
3374     // Store the return address to the appropriate stack slot.
3375     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3376                                      getPointerTy(DAG.getDataLayout()),
3377                                      RegInfo->getSlotSize(), FPDiff, dl);
3378   }
3379
3380   // Build a sequence of copy-to-reg nodes chained together with token chain
3381   // and flag operands which copy the outgoing args into registers.
3382   SDValue InFlag;
3383   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3384     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3385                              RegsToPass[i].second, InFlag);
3386     InFlag = Chain.getValue(1);
3387   }
3388
3389   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3390     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3391     // In the 64-bit large code model, we have to make all calls
3392     // through a register, since the call instruction's 32-bit
3393     // pc-relative offset may not be large enough to hold the whole
3394     // address.
3395   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3396     // If the callee is a GlobalAddress node (quite common, every direct call
3397     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3398     // it.
3399     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3400
3401     // We should use extra load for direct calls to dllimported functions in
3402     // non-JIT mode.
3403     const GlobalValue *GV = G->getGlobal();
3404     if (!GV->hasDLLImportStorageClass()) {
3405       unsigned char OpFlags = 0;
3406       bool ExtraLoad = false;
3407       unsigned WrapperKind = ISD::DELETED_NODE;
3408
3409       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3410       // external symbols most go through the PLT in PIC mode.  If the symbol
3411       // has hidden or protected visibility, or if it is static or local, then
3412       // we don't need to use the PLT - we can directly call it.
3413       if (Subtarget->isTargetELF() &&
3414           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3415           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3416         OpFlags = X86II::MO_PLT;
3417       } else if (Subtarget->isPICStyleStubAny() &&
3418                  !GV->isStrongDefinitionForLinker() &&
3419                  (!Subtarget->getTargetTriple().isMacOSX() ||
3420                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3421         // PC-relative references to external symbols should go through $stub,
3422         // unless we're building with the leopard linker or later, which
3423         // automatically synthesizes these stubs.
3424         OpFlags = X86II::MO_DARWIN_STUB;
3425       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3426                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3427         // If the function is marked as non-lazy, generate an indirect call
3428         // which loads from the GOT directly. This avoids runtime overhead
3429         // at the cost of eager binding (and one extra byte of encoding).
3430         OpFlags = X86II::MO_GOTPCREL;
3431         WrapperKind = X86ISD::WrapperRIP;
3432         ExtraLoad = true;
3433       }
3434
3435       Callee = DAG.getTargetGlobalAddress(
3436           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3437
3438       // Add a wrapper if needed.
3439       if (WrapperKind != ISD::DELETED_NODE)
3440         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3441                              getPointerTy(DAG.getDataLayout()), Callee);
3442       // Add extra indirection if needed.
3443       if (ExtraLoad)
3444         Callee = DAG.getLoad(
3445             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3446             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3447             false, 0);
3448     }
3449   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3450     unsigned char OpFlags = 0;
3451
3452     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3453     // external symbols should go through the PLT.
3454     if (Subtarget->isTargetELF() &&
3455         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3456       OpFlags = X86II::MO_PLT;
3457     } else if (Subtarget->isPICStyleStubAny() &&
3458                (!Subtarget->getTargetTriple().isMacOSX() ||
3459                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3460       // PC-relative references to external symbols should go through $stub,
3461       // unless we're building with the leopard linker or later, which
3462       // automatically synthesizes these stubs.
3463       OpFlags = X86II::MO_DARWIN_STUB;
3464     }
3465
3466     Callee = DAG.getTargetExternalSymbol(
3467         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3468   } else if (Subtarget->isTarget64BitILP32() &&
3469              Callee->getValueType(0) == MVT::i32) {
3470     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3471     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3472   }
3473
3474   // Returns a chain & a flag for retval copy to use.
3475   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3476   SmallVector<SDValue, 8> Ops;
3477
3478   if (!IsSibcall && isTailCall) {
3479     Chain = DAG.getCALLSEQ_END(Chain,
3480                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3481                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3482     InFlag = Chain.getValue(1);
3483   }
3484
3485   Ops.push_back(Chain);
3486   Ops.push_back(Callee);
3487
3488   if (isTailCall)
3489     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3490
3491   // Add argument registers to the end of the list so that they are known live
3492   // into the call.
3493   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3494     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3495                                   RegsToPass[i].second.getValueType()));
3496
3497   // Add a register mask operand representing the call-preserved registers.
3498   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3499   assert(Mask && "Missing call preserved mask for calling convention");
3500
3501   // If this is an invoke in a 32-bit function using a funclet-based
3502   // personality, assume the function clobbers all registers. If an exception
3503   // is thrown, the runtime will not restore CSRs.
3504   // FIXME: Model this more precisely so that we can register allocate across
3505   // the normal edge and spill and fill across the exceptional edge.
3506   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3507     const Function *CallerFn = MF.getFunction();
3508     EHPersonality Pers =
3509         CallerFn->hasPersonalityFn()
3510             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3511             : EHPersonality::Unknown;
3512     if (isFuncletEHPersonality(Pers))
3513       Mask = RegInfo->getNoPreservedMask();
3514   }
3515
3516   Ops.push_back(DAG.getRegisterMask(Mask));
3517
3518   if (InFlag.getNode())
3519     Ops.push_back(InFlag);
3520
3521   if (isTailCall) {
3522     // We used to do:
3523     //// If this is the first return lowered for this function, add the regs
3524     //// to the liveout set for the function.
3525     // This isn't right, although it's probably harmless on x86; liveouts
3526     // should be computed from returns not tail calls.  Consider a void
3527     // function making a tail call to a function returning int.
3528     MF.getFrameInfo()->setHasTailCall();
3529     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3530   }
3531
3532   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3533   InFlag = Chain.getValue(1);
3534
3535   // Create the CALLSEQ_END node.
3536   unsigned NumBytesForCalleeToPop;
3537   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3538                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3539     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3540   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3541            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3542            SR == StackStructReturn)
3543     // If this is a call to a struct-return function, the callee
3544     // pops the hidden struct pointer, so we have to push it back.
3545     // This is common for Darwin/X86, Linux & Mingw32 targets.
3546     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3547     NumBytesForCalleeToPop = 4;
3548   else
3549     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3550
3551   // Returns a flag for retval copy to use.
3552   if (!IsSibcall) {
3553     Chain = DAG.getCALLSEQ_END(Chain,
3554                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3555                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3556                                                      true),
3557                                InFlag, dl);
3558     InFlag = Chain.getValue(1);
3559   }
3560
3561   // Handle result values, copying them out of physregs into vregs that we
3562   // return.
3563   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3564                          Ins, dl, DAG, InVals);
3565 }
3566
3567 //===----------------------------------------------------------------------===//
3568 //                Fast Calling Convention (tail call) implementation
3569 //===----------------------------------------------------------------------===//
3570
3571 //  Like std call, callee cleans arguments, convention except that ECX is
3572 //  reserved for storing the tail called function address. Only 2 registers are
3573 //  free for argument passing (inreg). Tail call optimization is performed
3574 //  provided:
3575 //                * tailcallopt is enabled
3576 //                * caller/callee are fastcc
3577 //  On X86_64 architecture with GOT-style position independent code only local
3578 //  (within module) calls are supported at the moment.
3579 //  To keep the stack aligned according to platform abi the function
3580 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3581 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3582 //  If a tail called function callee has more arguments than the caller the
3583 //  caller needs to make sure that there is room to move the RETADDR to. This is
3584 //  achieved by reserving an area the size of the argument delta right after the
3585 //  original RETADDR, but before the saved framepointer or the spilled registers
3586 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3587 //  stack layout:
3588 //    arg1
3589 //    arg2
3590 //    RETADDR
3591 //    [ new RETADDR
3592 //      move area ]
3593 //    (possible EBP)
3594 //    ESI
3595 //    EDI
3596 //    local1 ..
3597
3598 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3599 /// requirement.
3600 unsigned
3601 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3602                                                SelectionDAG& DAG) const {
3603   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3604   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3605   unsigned StackAlignment = TFI.getStackAlignment();
3606   uint64_t AlignMask = StackAlignment - 1;
3607   int64_t Offset = StackSize;
3608   unsigned SlotSize = RegInfo->getSlotSize();
3609   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3610     // Number smaller than 12 so just add the difference.
3611     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3612   } else {
3613     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3614     Offset = ((~AlignMask) & Offset) + StackAlignment +
3615       (StackAlignment-SlotSize);
3616   }
3617   return Offset;
3618 }
3619
3620 /// Return true if the given stack call argument is already available in the
3621 /// same position (relatively) of the caller's incoming argument stack.
3622 static
3623 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3624                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3625                          const X86InstrInfo *TII) {
3626   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3627   int FI = INT_MAX;
3628   if (Arg.getOpcode() == ISD::CopyFromReg) {
3629     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3630     if (!TargetRegisterInfo::isVirtualRegister(VR))
3631       return false;
3632     MachineInstr *Def = MRI->getVRegDef(VR);
3633     if (!Def)
3634       return false;
3635     if (!Flags.isByVal()) {
3636       if (!TII->isLoadFromStackSlot(Def, FI))
3637         return false;
3638     } else {
3639       unsigned Opcode = Def->getOpcode();
3640       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3641            Opcode == X86::LEA64_32r) &&
3642           Def->getOperand(1).isFI()) {
3643         FI = Def->getOperand(1).getIndex();
3644         Bytes = Flags.getByValSize();
3645       } else
3646         return false;
3647     }
3648   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3649     if (Flags.isByVal())
3650       // ByVal argument is passed in as a pointer but it's now being
3651       // dereferenced. e.g.
3652       // define @foo(%struct.X* %A) {
3653       //   tail call @bar(%struct.X* byval %A)
3654       // }
3655       return false;
3656     SDValue Ptr = Ld->getBasePtr();
3657     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3658     if (!FINode)
3659       return false;
3660     FI = FINode->getIndex();
3661   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3662     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3663     FI = FINode->getIndex();
3664     Bytes = Flags.getByValSize();
3665   } else
3666     return false;
3667
3668   assert(FI != INT_MAX);
3669   if (!MFI->isFixedObjectIndex(FI))
3670     return false;
3671   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3672 }
3673
3674 /// Check whether the call is eligible for tail call optimization. Targets
3675 /// that want to do tail call optimization should implement this function.
3676 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3677     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3678     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3679     const SmallVectorImpl<ISD::OutputArg> &Outs,
3680     const SmallVectorImpl<SDValue> &OutVals,
3681     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3682   if (!mayTailCallThisCC(CalleeCC))
3683     return false;
3684
3685   // If -tailcallopt is specified, make fastcc functions tail-callable.
3686   MachineFunction &MF = DAG.getMachineFunction();
3687   const Function *CallerF = MF.getFunction();
3688
3689   // If the function return type is x86_fp80 and the callee return type is not,
3690   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3691   // perform a tailcall optimization here.
3692   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3693     return false;
3694
3695   CallingConv::ID CallerCC = CallerF->getCallingConv();
3696   bool CCMatch = CallerCC == CalleeCC;
3697   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3698   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3699
3700   // Win64 functions have extra shadow space for argument homing. Don't do the
3701   // sibcall if the caller and callee have mismatched expectations for this
3702   // space.
3703   if (IsCalleeWin64 != IsCallerWin64)
3704     return false;
3705
3706   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3707     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3708       return true;
3709     return false;
3710   }
3711
3712   // Look for obvious safe cases to perform tail call optimization that do not
3713   // require ABI changes. This is what gcc calls sibcall.
3714
3715   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3716   // emit a special epilogue.
3717   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3718   if (RegInfo->needsStackRealignment(MF))
3719     return false;
3720
3721   // Also avoid sibcall optimization if either caller or callee uses struct
3722   // return semantics.
3723   if (isCalleeStructRet || isCallerStructRet)
3724     return false;
3725
3726   // Do not sibcall optimize vararg calls unless all arguments are passed via
3727   // registers.
3728   if (isVarArg && !Outs.empty()) {
3729     // Optimizing for varargs on Win64 is unlikely to be safe without
3730     // additional testing.
3731     if (IsCalleeWin64 || IsCallerWin64)
3732       return false;
3733
3734     SmallVector<CCValAssign, 16> ArgLocs;
3735     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3736                    *DAG.getContext());
3737
3738     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3739     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3740       if (!ArgLocs[i].isRegLoc())
3741         return false;
3742   }
3743
3744   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3745   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3746   // this into a sibcall.
3747   bool Unused = false;
3748   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3749     if (!Ins[i].Used) {
3750       Unused = true;
3751       break;
3752     }
3753   }
3754   if (Unused) {
3755     SmallVector<CCValAssign, 16> RVLocs;
3756     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3757                    *DAG.getContext());
3758     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3759     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3760       CCValAssign &VA = RVLocs[i];
3761       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3762         return false;
3763     }
3764   }
3765
3766   // If the calling conventions do not match, then we'd better make sure the
3767   // results are returned in the same way as what the caller expects.
3768   if (!CCMatch) {
3769     SmallVector<CCValAssign, 16> RVLocs1;
3770     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3771                     *DAG.getContext());
3772     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3773
3774     SmallVector<CCValAssign, 16> RVLocs2;
3775     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3776                     *DAG.getContext());
3777     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3778
3779     if (RVLocs1.size() != RVLocs2.size())
3780       return false;
3781     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3782       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3783         return false;
3784       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3785         return false;
3786       if (RVLocs1[i].isRegLoc()) {
3787         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3788           return false;
3789       } else {
3790         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3791           return false;
3792       }
3793     }
3794   }
3795
3796   unsigned StackArgsSize = 0;
3797
3798   // If the callee takes no arguments then go on to check the results of the
3799   // call.
3800   if (!Outs.empty()) {
3801     // Check if stack adjustment is needed. For now, do not do this if any
3802     // argument is passed on the stack.
3803     SmallVector<CCValAssign, 16> ArgLocs;
3804     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3805                    *DAG.getContext());
3806
3807     // Allocate shadow area for Win64
3808     if (IsCalleeWin64)
3809       CCInfo.AllocateStack(32, 8);
3810
3811     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3812     StackArgsSize = CCInfo.getNextStackOffset();
3813
3814     if (CCInfo.getNextStackOffset()) {
3815       // Check if the arguments are already laid out in the right way as
3816       // the caller's fixed stack objects.
3817       MachineFrameInfo *MFI = MF.getFrameInfo();
3818       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3819       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3820       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3821         CCValAssign &VA = ArgLocs[i];
3822         SDValue Arg = OutVals[i];
3823         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3824         if (VA.getLocInfo() == CCValAssign::Indirect)
3825           return false;
3826         if (!VA.isRegLoc()) {
3827           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3828                                    MFI, MRI, TII))
3829             return false;
3830         }
3831       }
3832     }
3833
3834     // If the tailcall address may be in a register, then make sure it's
3835     // possible to register allocate for it. In 32-bit, the call address can
3836     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3837     // callee-saved registers are restored. These happen to be the same
3838     // registers used to pass 'inreg' arguments so watch out for those.
3839     if (!Subtarget->is64Bit() &&
3840         ((!isa<GlobalAddressSDNode>(Callee) &&
3841           !isa<ExternalSymbolSDNode>(Callee)) ||
3842          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3843       unsigned NumInRegs = 0;
3844       // In PIC we need an extra register to formulate the address computation
3845       // for the callee.
3846       unsigned MaxInRegs =
3847         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3848
3849       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3850         CCValAssign &VA = ArgLocs[i];
3851         if (!VA.isRegLoc())
3852           continue;
3853         unsigned Reg = VA.getLocReg();
3854         switch (Reg) {
3855         default: break;
3856         case X86::EAX: case X86::EDX: case X86::ECX:
3857           if (++NumInRegs == MaxInRegs)
3858             return false;
3859           break;
3860         }
3861       }
3862     }
3863   }
3864
3865   bool CalleeWillPop =
3866       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3867                        MF.getTarget().Options.GuaranteedTailCallOpt);
3868
3869   if (unsigned BytesToPop =
3870           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3871     // If we have bytes to pop, the callee must pop them.
3872     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3873     if (!CalleePopMatches)
3874       return false;
3875   } else if (CalleeWillPop && StackArgsSize > 0) {
3876     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3877     return false;
3878   }
3879
3880   return true;
3881 }
3882
3883 FastISel *
3884 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3885                                   const TargetLibraryInfo *libInfo) const {
3886   return X86::createFastISel(funcInfo, libInfo);
3887 }
3888
3889 //===----------------------------------------------------------------------===//
3890 //                           Other Lowering Hooks
3891 //===----------------------------------------------------------------------===//
3892
3893 static bool MayFoldLoad(SDValue Op) {
3894   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3895 }
3896
3897 static bool MayFoldIntoStore(SDValue Op) {
3898   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3899 }
3900
3901 static bool isTargetShuffle(unsigned Opcode) {
3902   switch(Opcode) {
3903   default: return false;
3904   case X86ISD::BLENDI:
3905   case X86ISD::PSHUFB:
3906   case X86ISD::PSHUFD:
3907   case X86ISD::PSHUFHW:
3908   case X86ISD::PSHUFLW:
3909   case X86ISD::SHUFP:
3910   case X86ISD::PALIGNR:
3911   case X86ISD::MOVLHPS:
3912   case X86ISD::MOVLHPD:
3913   case X86ISD::MOVHLPS:
3914   case X86ISD::MOVLPS:
3915   case X86ISD::MOVLPD:
3916   case X86ISD::MOVSHDUP:
3917   case X86ISD::MOVSLDUP:
3918   case X86ISD::MOVDDUP:
3919   case X86ISD::MOVSS:
3920   case X86ISD::MOVSD:
3921   case X86ISD::UNPCKL:
3922   case X86ISD::UNPCKH:
3923   case X86ISD::VPERMILPI:
3924   case X86ISD::VPERM2X128:
3925   case X86ISD::VPERMI:
3926   case X86ISD::VPERMV:
3927   case X86ISD::VPERMV3:
3928     return true;
3929   }
3930 }
3931
3932 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3933                                     SDValue V1, unsigned TargetMask,
3934                                     SelectionDAG &DAG) {
3935   switch(Opc) {
3936   default: llvm_unreachable("Unknown x86 shuffle node");
3937   case X86ISD::PSHUFD:
3938   case X86ISD::PSHUFHW:
3939   case X86ISD::PSHUFLW:
3940   case X86ISD::VPERMILPI:
3941   case X86ISD::VPERMI:
3942     return DAG.getNode(Opc, dl, VT, V1,
3943                        DAG.getConstant(TargetMask, dl, MVT::i8));
3944   }
3945 }
3946
3947 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3948                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3949   switch(Opc) {
3950   default: llvm_unreachable("Unknown x86 shuffle node");
3951   case X86ISD::MOVLHPS:
3952   case X86ISD::MOVLHPD:
3953   case X86ISD::MOVHLPS:
3954   case X86ISD::MOVLPS:
3955   case X86ISD::MOVLPD:
3956   case X86ISD::MOVSS:
3957   case X86ISD::MOVSD:
3958   case X86ISD::UNPCKL:
3959   case X86ISD::UNPCKH:
3960     return DAG.getNode(Opc, dl, VT, V1, V2);
3961   }
3962 }
3963
3964 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3965   MachineFunction &MF = DAG.getMachineFunction();
3966   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3967   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3968   int ReturnAddrIndex = FuncInfo->getRAIndex();
3969
3970   if (ReturnAddrIndex == 0) {
3971     // Set up a frame object for the return address.
3972     unsigned SlotSize = RegInfo->getSlotSize();
3973     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3974                                                            -(int64_t)SlotSize,
3975                                                            false);
3976     FuncInfo->setRAIndex(ReturnAddrIndex);
3977   }
3978
3979   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3980 }
3981
3982 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3983                                        bool hasSymbolicDisplacement) {
3984   // Offset should fit into 32 bit immediate field.
3985   if (!isInt<32>(Offset))
3986     return false;
3987
3988   // If we don't have a symbolic displacement - we don't have any extra
3989   // restrictions.
3990   if (!hasSymbolicDisplacement)
3991     return true;
3992
3993   // FIXME: Some tweaks might be needed for medium code model.
3994   if (M != CodeModel::Small && M != CodeModel::Kernel)
3995     return false;
3996
3997   // For small code model we assume that latest object is 16MB before end of 31
3998   // bits boundary. We may also accept pretty large negative constants knowing
3999   // that all objects are in the positive half of address space.
4000   if (M == CodeModel::Small && Offset < 16*1024*1024)
4001     return true;
4002
4003   // For kernel code model we know that all object resist in the negative half
4004   // of 32bits address space. We may not accept negative offsets, since they may
4005   // be just off and we may accept pretty large positive ones.
4006   if (M == CodeModel::Kernel && Offset >= 0)
4007     return true;
4008
4009   return false;
4010 }
4011
4012 /// Determines whether the callee is required to pop its own arguments.
4013 /// Callee pop is necessary to support tail calls.
4014 bool X86::isCalleePop(CallingConv::ID CallingConv,
4015                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4016   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4017   // can guarantee TCO.
4018   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4019     return true;
4020
4021   switch (CallingConv) {
4022   default:
4023     return false;
4024   case CallingConv::X86_StdCall:
4025   case CallingConv::X86_FastCall:
4026   case CallingConv::X86_ThisCall:
4027   case CallingConv::X86_VectorCall:
4028     return !is64Bit;
4029   }
4030 }
4031
4032 /// \brief Return true if the condition is an unsigned comparison operation.
4033 static bool isX86CCUnsigned(unsigned X86CC) {
4034   switch (X86CC) {
4035   default: llvm_unreachable("Invalid integer condition!");
4036   case X86::COND_E:     return true;
4037   case X86::COND_G:     return false;
4038   case X86::COND_GE:    return false;
4039   case X86::COND_L:     return false;
4040   case X86::COND_LE:    return false;
4041   case X86::COND_NE:    return true;
4042   case X86::COND_B:     return true;
4043   case X86::COND_A:     return true;
4044   case X86::COND_BE:    return true;
4045   case X86::COND_AE:    return true;
4046   }
4047 }
4048
4049 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4050   switch (SetCCOpcode) {
4051   default: llvm_unreachable("Invalid integer condition!");
4052   case ISD::SETEQ:  return X86::COND_E;
4053   case ISD::SETGT:  return X86::COND_G;
4054   case ISD::SETGE:  return X86::COND_GE;
4055   case ISD::SETLT:  return X86::COND_L;
4056   case ISD::SETLE:  return X86::COND_LE;
4057   case ISD::SETNE:  return X86::COND_NE;
4058   case ISD::SETULT: return X86::COND_B;
4059   case ISD::SETUGT: return X86::COND_A;
4060   case ISD::SETULE: return X86::COND_BE;
4061   case ISD::SETUGE: return X86::COND_AE;
4062   }
4063 }
4064
4065 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4066 /// condition code, returning the condition code and the LHS/RHS of the
4067 /// comparison to make.
4068 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4069                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4070   if (!isFP) {
4071     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4072       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4073         // X > -1   -> X == 0, jump !sign.
4074         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4075         return X86::COND_NS;
4076       }
4077       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4078         // X < 0   -> X == 0, jump on sign.
4079         return X86::COND_S;
4080       }
4081       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4082         // X < 1   -> X <= 0
4083         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4084         return X86::COND_LE;
4085       }
4086     }
4087
4088     return TranslateIntegerX86CC(SetCCOpcode);
4089   }
4090
4091   // First determine if it is required or is profitable to flip the operands.
4092
4093   // If LHS is a foldable load, but RHS is not, flip the condition.
4094   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4095       !ISD::isNON_EXTLoad(RHS.getNode())) {
4096     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4097     std::swap(LHS, RHS);
4098   }
4099
4100   switch (SetCCOpcode) {
4101   default: break;
4102   case ISD::SETOLT:
4103   case ISD::SETOLE:
4104   case ISD::SETUGT:
4105   case ISD::SETUGE:
4106     std::swap(LHS, RHS);
4107     break;
4108   }
4109
4110   // On a floating point condition, the flags are set as follows:
4111   // ZF  PF  CF   op
4112   //  0 | 0 | 0 | X > Y
4113   //  0 | 0 | 1 | X < Y
4114   //  1 | 0 | 0 | X == Y
4115   //  1 | 1 | 1 | unordered
4116   switch (SetCCOpcode) {
4117   default: llvm_unreachable("Condcode should be pre-legalized away");
4118   case ISD::SETUEQ:
4119   case ISD::SETEQ:   return X86::COND_E;
4120   case ISD::SETOLT:              // flipped
4121   case ISD::SETOGT:
4122   case ISD::SETGT:   return X86::COND_A;
4123   case ISD::SETOLE:              // flipped
4124   case ISD::SETOGE:
4125   case ISD::SETGE:   return X86::COND_AE;
4126   case ISD::SETUGT:              // flipped
4127   case ISD::SETULT:
4128   case ISD::SETLT:   return X86::COND_B;
4129   case ISD::SETUGE:              // flipped
4130   case ISD::SETULE:
4131   case ISD::SETLE:   return X86::COND_BE;
4132   case ISD::SETONE:
4133   case ISD::SETNE:   return X86::COND_NE;
4134   case ISD::SETUO:   return X86::COND_P;
4135   case ISD::SETO:    return X86::COND_NP;
4136   case ISD::SETOEQ:
4137   case ISD::SETUNE:  return X86::COND_INVALID;
4138   }
4139 }
4140
4141 /// Is there a floating point cmov for the specific X86 condition code?
4142 /// Current x86 isa includes the following FP cmov instructions:
4143 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4144 static bool hasFPCMov(unsigned X86CC) {
4145   switch (X86CC) {
4146   default:
4147     return false;
4148   case X86::COND_B:
4149   case X86::COND_BE:
4150   case X86::COND_E:
4151   case X86::COND_P:
4152   case X86::COND_A:
4153   case X86::COND_AE:
4154   case X86::COND_NE:
4155   case X86::COND_NP:
4156     return true;
4157   }
4158 }
4159
4160 /// Returns true if the target can instruction select the
4161 /// specified FP immediate natively. If false, the legalizer will
4162 /// materialize the FP immediate as a load from a constant pool.
4163 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4164   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4165     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4166       return true;
4167   }
4168   return false;
4169 }
4170
4171 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4172                                               ISD::LoadExtType ExtTy,
4173                                               EVT NewVT) const {
4174   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4175   // relocation target a movq or addq instruction: don't let the load shrink.
4176   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4177   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4178     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4179       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4180   return true;
4181 }
4182
4183 /// \brief Returns true if it is beneficial to convert a load of a constant
4184 /// to just the constant itself.
4185 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4186                                                           Type *Ty) const {
4187   assert(Ty->isIntegerTy());
4188
4189   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4190   if (BitSize == 0 || BitSize > 64)
4191     return false;
4192   return true;
4193 }
4194
4195 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4196                                                 unsigned Index) const {
4197   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4198     return false;
4199
4200   return (Index == 0 || Index == ResVT.getVectorNumElements());
4201 }
4202
4203 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4204   // Speculate cttz only if we can directly use TZCNT.
4205   return Subtarget->hasBMI();
4206 }
4207
4208 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4209   // Speculate ctlz only if we can directly use LZCNT.
4210   return Subtarget->hasLZCNT();
4211 }
4212
4213 /// Return true if every element in Mask, beginning
4214 /// from position Pos and ending in Pos+Size is undef.
4215 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4216   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4217     if (0 <= Mask[i])
4218       return false;
4219   return true;
4220 }
4221
4222 /// Return true if Val is undef or if its value falls within the
4223 /// specified range (L, H].
4224 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4225   return (Val < 0) || (Val >= Low && Val < Hi);
4226 }
4227
4228 /// Val is either less than zero (undef) or equal to the specified value.
4229 static bool isUndefOrEqual(int Val, int CmpVal) {
4230   return (Val < 0 || Val == CmpVal);
4231 }
4232
4233 /// Return true if every element in Mask, beginning
4234 /// from position Pos and ending in Pos+Size, falls within the specified
4235 /// sequential range (Low, Low+Size]. or is undef.
4236 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4237                                        unsigned Pos, unsigned Size, int Low) {
4238   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4239     if (!isUndefOrEqual(Mask[i], Low))
4240       return false;
4241   return true;
4242 }
4243
4244 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4245 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4246 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4247   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4248   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4249     return false;
4250
4251   // The index should be aligned on a vecWidth-bit boundary.
4252   uint64_t Index =
4253     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4254
4255   MVT VT = N->getSimpleValueType(0);
4256   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4257   bool Result = (Index * ElSize) % vecWidth == 0;
4258
4259   return Result;
4260 }
4261
4262 /// Return true if the specified INSERT_SUBVECTOR
4263 /// operand specifies a subvector insert that is suitable for input to
4264 /// insertion of 128 or 256-bit subvectors
4265 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4266   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4267   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4268     return false;
4269   // The index should be aligned on a vecWidth-bit boundary.
4270   uint64_t Index =
4271     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4272
4273   MVT VT = N->getSimpleValueType(0);
4274   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4275   bool Result = (Index * ElSize) % vecWidth == 0;
4276
4277   return Result;
4278 }
4279
4280 bool X86::isVINSERT128Index(SDNode *N) {
4281   return isVINSERTIndex(N, 128);
4282 }
4283
4284 bool X86::isVINSERT256Index(SDNode *N) {
4285   return isVINSERTIndex(N, 256);
4286 }
4287
4288 bool X86::isVEXTRACT128Index(SDNode *N) {
4289   return isVEXTRACTIndex(N, 128);
4290 }
4291
4292 bool X86::isVEXTRACT256Index(SDNode *N) {
4293   return isVEXTRACTIndex(N, 256);
4294 }
4295
4296 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4297   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4298   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4299          "Illegal extract subvector for VEXTRACT");
4300
4301   uint64_t Index =
4302     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4303
4304   MVT VecVT = N->getOperand(0).getSimpleValueType();
4305   MVT ElVT = VecVT.getVectorElementType();
4306
4307   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4308   return Index / NumElemsPerChunk;
4309 }
4310
4311 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4312   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4313   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4314          "Illegal insert subvector for VINSERT");
4315
4316   uint64_t Index =
4317     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4318
4319   MVT VecVT = N->getSimpleValueType(0);
4320   MVT ElVT = VecVT.getVectorElementType();
4321
4322   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4323   return Index / NumElemsPerChunk;
4324 }
4325
4326 /// Return the appropriate immediate to extract the specified
4327 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4328 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4329   return getExtractVEXTRACTImmediate(N, 128);
4330 }
4331
4332 /// Return the appropriate immediate to extract the specified
4333 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4334 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4335   return getExtractVEXTRACTImmediate(N, 256);
4336 }
4337
4338 /// Return the appropriate immediate to insert at the specified
4339 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4340 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4341   return getInsertVINSERTImmediate(N, 128);
4342 }
4343
4344 /// Return the appropriate immediate to insert at the specified
4345 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4346 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4347   return getInsertVINSERTImmediate(N, 256);
4348 }
4349
4350 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4351 bool X86::isZeroNode(SDValue Elt) {
4352   return isNullConstant(Elt) || isNullFPConstant(Elt);
4353 }
4354
4355 // Build a vector of constants
4356 // Use an UNDEF node if MaskElt == -1.
4357 // Spilt 64-bit constants in the 32-bit mode.
4358 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4359                               SelectionDAG &DAG,
4360                               SDLoc dl, bool IsMask = false) {
4361
4362   SmallVector<SDValue, 32>  Ops;
4363   bool Split = false;
4364
4365   MVT ConstVecVT = VT;
4366   unsigned NumElts = VT.getVectorNumElements();
4367   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4368   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4369     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4370     Split = true;
4371   }
4372
4373   MVT EltVT = ConstVecVT.getVectorElementType();
4374   for (unsigned i = 0; i < NumElts; ++i) {
4375     bool IsUndef = Values[i] < 0 && IsMask;
4376     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4377       DAG.getConstant(Values[i], dl, EltVT);
4378     Ops.push_back(OpNode);
4379     if (Split)
4380       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4381                     DAG.getConstant(0, dl, EltVT));
4382   }
4383   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4384   if (Split)
4385     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4386   return ConstsNode;
4387 }
4388
4389 /// Returns a vector of specified type with all zero elements.
4390 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4391                              SelectionDAG &DAG, SDLoc dl) {
4392   assert(VT.isVector() && "Expected a vector type");
4393
4394   // Always build SSE zero vectors as <4 x i32> bitcasted
4395   // to their dest type. This ensures they get CSE'd.
4396   SDValue Vec;
4397   if (VT.is128BitVector()) {  // SSE
4398     if (Subtarget->hasSSE2()) {  // SSE2
4399       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4400       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4401     } else { // SSE1
4402       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4403       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4404     }
4405   } else if (VT.is256BitVector()) { // AVX
4406     if (Subtarget->hasInt256()) { // AVX2
4407       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4408       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4409       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4410     } else {
4411       // 256-bit logic and arithmetic instructions in AVX are all
4412       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4413       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4414       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4415       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4416     }
4417   } else if (VT.is512BitVector()) { // AVX-512
4418       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4419       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4420                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4421       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4422   } else if (VT.getVectorElementType() == MVT::i1) {
4423
4424     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4425             && "Unexpected vector type");
4426     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4427             && "Unexpected vector type");
4428     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4429     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4430     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4431   } else
4432     llvm_unreachable("Unexpected vector type");
4433
4434   return DAG.getBitcast(VT, Vec);
4435 }
4436
4437 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4438                                 SelectionDAG &DAG, SDLoc dl,
4439                                 unsigned vectorWidth) {
4440   assert((vectorWidth == 128 || vectorWidth == 256) &&
4441          "Unsupported vector width");
4442   EVT VT = Vec.getValueType();
4443   EVT ElVT = VT.getVectorElementType();
4444   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4445   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4446                                   VT.getVectorNumElements()/Factor);
4447
4448   // Extract from UNDEF is UNDEF.
4449   if (Vec.getOpcode() == ISD::UNDEF)
4450     return DAG.getUNDEF(ResultVT);
4451
4452   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4453   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4454   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4455
4456   // This is the index of the first element of the vectorWidth-bit chunk
4457   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4458   IdxVal &= ~(ElemsPerChunk - 1);
4459
4460   // If the input is a buildvector just emit a smaller one.
4461   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4462     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4463                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4464
4465   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4466   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4467 }
4468
4469 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4470 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4471 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4472 /// instructions or a simple subregister reference. Idx is an index in the
4473 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4474 /// lowering EXTRACT_VECTOR_ELT operations easier.
4475 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4476                                    SelectionDAG &DAG, SDLoc dl) {
4477   assert((Vec.getValueType().is256BitVector() ||
4478           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4479   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4480 }
4481
4482 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4483 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4484                                    SelectionDAG &DAG, SDLoc dl) {
4485   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4486   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4487 }
4488
4489 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4490                                unsigned IdxVal, SelectionDAG &DAG,
4491                                SDLoc dl, unsigned vectorWidth) {
4492   assert((vectorWidth == 128 || vectorWidth == 256) &&
4493          "Unsupported vector width");
4494   // Inserting UNDEF is Result
4495   if (Vec.getOpcode() == ISD::UNDEF)
4496     return Result;
4497   EVT VT = Vec.getValueType();
4498   EVT ElVT = VT.getVectorElementType();
4499   EVT ResultVT = Result.getValueType();
4500
4501   // Insert the relevant vectorWidth bits.
4502   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4503   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4504
4505   // This is the index of the first element of the vectorWidth-bit chunk
4506   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4507   IdxVal &= ~(ElemsPerChunk - 1);
4508
4509   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4510   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4511 }
4512
4513 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4514 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4515 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4516 /// simple superregister reference.  Idx is an index in the 128 bits
4517 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4518 /// lowering INSERT_VECTOR_ELT operations easier.
4519 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4520                                   SelectionDAG &DAG, SDLoc dl) {
4521   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4522
4523   // For insertion into the zero index (low half) of a 256-bit vector, it is
4524   // more efficient to generate a blend with immediate instead of an insert*128.
4525   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4526   // extend the subvector to the size of the result vector. Make sure that
4527   // we are not recursing on that node by checking for undef here.
4528   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4529       Result.getOpcode() != ISD::UNDEF) {
4530     EVT ResultVT = Result.getValueType();
4531     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4532     SDValue Undef = DAG.getUNDEF(ResultVT);
4533     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4534                                  Vec, ZeroIndex);
4535
4536     // The blend instruction, and therefore its mask, depend on the data type.
4537     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4538     if (ScalarType.isFloatingPoint()) {
4539       // Choose either vblendps (float) or vblendpd (double).
4540       unsigned ScalarSize = ScalarType.getSizeInBits();
4541       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4542       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4543       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4544       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4545     }
4546
4547     const X86Subtarget &Subtarget =
4548     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4549
4550     // AVX2 is needed for 256-bit integer blend support.
4551     // Integers must be cast to 32-bit because there is only vpblendd;
4552     // vpblendw can't be used for this because it has a handicapped mask.
4553
4554     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4555     // is still more efficient than using the wrong domain vinsertf128 that
4556     // will be created by InsertSubVector().
4557     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4558
4559     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4560     Vec256 = DAG.getBitcast(CastVT, Vec256);
4561     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4562     return DAG.getBitcast(ResultVT, Vec256);
4563   }
4564
4565   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4566 }
4567
4568 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4569                                   SelectionDAG &DAG, SDLoc dl) {
4570   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4571   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4572 }
4573
4574 /// Insert i1-subvector to i1-vector.
4575 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4576
4577   SDLoc dl(Op);
4578   SDValue Vec = Op.getOperand(0);
4579   SDValue SubVec = Op.getOperand(1);
4580   SDValue Idx = Op.getOperand(2);
4581
4582   if (!isa<ConstantSDNode>(Idx))
4583     return SDValue();
4584
4585   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4586   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4587     return Op;
4588
4589   MVT OpVT = Op.getSimpleValueType();
4590   MVT SubVecVT = SubVec.getSimpleValueType();
4591   unsigned NumElems = OpVT.getVectorNumElements();
4592   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4593
4594   assert(IdxVal + SubVecNumElems <= NumElems &&
4595          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4596          "Unexpected index value in INSERT_SUBVECTOR");
4597
4598   // There are 3 possible cases:
4599   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4600   // 2. Subvector should be inserted in the upper part
4601   //    (IdxVal + SubVecNumElems == NumElems)
4602   // 3. Subvector should be inserted in the middle (for example v2i1
4603   //    to v16i1, index 2)
4604
4605   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4606   SDValue Undef = DAG.getUNDEF(OpVT);
4607   SDValue WideSubVec =
4608     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4609   if (Vec.isUndef())
4610     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4611       DAG.getConstant(IdxVal, dl, MVT::i8));
4612
4613   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4614     unsigned ShiftLeft = NumElems - SubVecNumElems;
4615     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4616     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4617       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4618     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4619       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4620   }
4621
4622   if (IdxVal == 0) {
4623     // Zero lower bits of the Vec
4624     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4625     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4626     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4627     // Merge them together
4628     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4629   }
4630
4631   // Simple case when we put subvector in the upper part
4632   if (IdxVal + SubVecNumElems == NumElems) {
4633     // Zero upper bits of the Vec
4634     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4635                         DAG.getConstant(IdxVal, dl, MVT::i8));
4636     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4637     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4638     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4639     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4640   }
4641   // Subvector should be inserted in the middle - use shuffle
4642   SmallVector<int, 64> Mask;
4643   for (unsigned i = 0; i < NumElems; ++i)
4644     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4645                     i : i + NumElems);
4646   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4647 }
4648
4649 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4650 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4651 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4652 /// large BUILD_VECTORS.
4653 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4654                                    unsigned NumElems, SelectionDAG &DAG,
4655                                    SDLoc dl) {
4656   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4657   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4658 }
4659
4660 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4661                                    unsigned NumElems, SelectionDAG &DAG,
4662                                    SDLoc dl) {
4663   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4664   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4665 }
4666
4667 /// Returns a vector of specified type with all bits set.
4668 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4669 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4670 /// Then bitcast to their original type, ensuring they get CSE'd.
4671 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4672                              SelectionDAG &DAG, SDLoc dl) {
4673   assert(VT.isVector() && "Expected a vector type");
4674
4675   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4676   SDValue Vec;
4677   if (VT.is512BitVector()) {
4678     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4679                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4680     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4681   } else if (VT.is256BitVector()) {
4682     if (Subtarget->hasInt256()) { // AVX2
4683       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4684       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4685     } else { // AVX
4686       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4687       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4688     }
4689   } else if (VT.is128BitVector()) {
4690     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4691   } else
4692     llvm_unreachable("Unexpected vector type");
4693
4694   return DAG.getBitcast(VT, Vec);
4695 }
4696
4697 /// Returns a vector_shuffle node for an unpackl operation.
4698 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4699                           SDValue V2) {
4700   unsigned NumElems = VT.getVectorNumElements();
4701   SmallVector<int, 8> Mask;
4702   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4703     Mask.push_back(i);
4704     Mask.push_back(i + NumElems);
4705   }
4706   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4707 }
4708
4709 /// Returns a vector_shuffle node for an unpackh operation.
4710 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4711                           SDValue V2) {
4712   unsigned NumElems = VT.getVectorNumElements();
4713   SmallVector<int, 8> Mask;
4714   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4715     Mask.push_back(i + Half);
4716     Mask.push_back(i + NumElems + Half);
4717   }
4718   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4719 }
4720
4721 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4722 /// This produces a shuffle where the low element of V2 is swizzled into the
4723 /// zero/undef vector, landing at element Idx.
4724 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4725 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4726                                            bool IsZero,
4727                                            const X86Subtarget *Subtarget,
4728                                            SelectionDAG &DAG) {
4729   MVT VT = V2.getSimpleValueType();
4730   SDValue V1 = IsZero
4731     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4732   unsigned NumElems = VT.getVectorNumElements();
4733   SmallVector<int, 16> MaskVec;
4734   for (unsigned i = 0; i != NumElems; ++i)
4735     // If this is the insertion idx, put the low elt of V2 here.
4736     MaskVec.push_back(i == Idx ? NumElems : i);
4737   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4738 }
4739
4740 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4741 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4742 /// uses one source. Note that this will set IsUnary for shuffles which use a
4743 /// single input multiple times, and in those cases it will
4744 /// adjust the mask to only have indices within that single input.
4745 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4746 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4747                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4748   unsigned NumElems = VT.getVectorNumElements();
4749   SDValue ImmN;
4750
4751   IsUnary = false;
4752   bool IsFakeUnary = false;
4753   switch(N->getOpcode()) {
4754   case X86ISD::BLENDI:
4755     ImmN = N->getOperand(N->getNumOperands()-1);
4756     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4757     break;
4758   case X86ISD::SHUFP:
4759     ImmN = N->getOperand(N->getNumOperands()-1);
4760     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4761     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4762     break;
4763   case X86ISD::UNPCKH:
4764     DecodeUNPCKHMask(VT, Mask);
4765     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4766     break;
4767   case X86ISD::UNPCKL:
4768     DecodeUNPCKLMask(VT, Mask);
4769     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4770     break;
4771   case X86ISD::MOVHLPS:
4772     DecodeMOVHLPSMask(NumElems, Mask);
4773     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4774     break;
4775   case X86ISD::MOVLHPS:
4776     DecodeMOVLHPSMask(NumElems, Mask);
4777     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4778     break;
4779   case X86ISD::PALIGNR:
4780     ImmN = N->getOperand(N->getNumOperands()-1);
4781     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4782     break;
4783   case X86ISD::PSHUFD:
4784   case X86ISD::VPERMILPI:
4785     ImmN = N->getOperand(N->getNumOperands()-1);
4786     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4787     IsUnary = true;
4788     break;
4789   case X86ISD::PSHUFHW:
4790     ImmN = N->getOperand(N->getNumOperands()-1);
4791     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4792     IsUnary = true;
4793     break;
4794   case X86ISD::PSHUFLW:
4795     ImmN = N->getOperand(N->getNumOperands()-1);
4796     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4797     IsUnary = true;
4798     break;
4799   case X86ISD::PSHUFB: {
4800     IsUnary = true;
4801     SDValue MaskNode = N->getOperand(1);
4802     while (MaskNode->getOpcode() == ISD::BITCAST)
4803       MaskNode = MaskNode->getOperand(0);
4804
4805     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4806       // If we have a build-vector, then things are easy.
4807       MVT VT = MaskNode.getSimpleValueType();
4808       assert(VT.isVector() &&
4809              "Can't produce a non-vector with a build_vector!");
4810       if (!VT.isInteger())
4811         return false;
4812
4813       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4814
4815       SmallVector<uint64_t, 32> RawMask;
4816       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4817         SDValue Op = MaskNode->getOperand(i);
4818         if (Op->getOpcode() == ISD::UNDEF) {
4819           RawMask.push_back((uint64_t)SM_SentinelUndef);
4820           continue;
4821         }
4822         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4823         if (!CN)
4824           return false;
4825         APInt MaskElement = CN->getAPIntValue();
4826
4827         // We now have to decode the element which could be any integer size and
4828         // extract each byte of it.
4829         for (int j = 0; j < NumBytesPerElement; ++j) {
4830           // Note that this is x86 and so always little endian: the low byte is
4831           // the first byte of the mask.
4832           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4833           MaskElement = MaskElement.lshr(8);
4834         }
4835       }
4836       DecodePSHUFBMask(RawMask, Mask);
4837       break;
4838     }
4839
4840     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4841     if (!MaskLoad)
4842       return false;
4843
4844     SDValue Ptr = MaskLoad->getBasePtr();
4845     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4846         Ptr->getOpcode() == X86ISD::WrapperRIP)
4847       Ptr = Ptr->getOperand(0);
4848
4849     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4850     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4851       return false;
4852
4853     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4854       DecodePSHUFBMask(C, Mask);
4855       if (Mask.empty())
4856         return false;
4857       break;
4858     }
4859
4860     return false;
4861   }
4862   case X86ISD::VPERMI:
4863     ImmN = N->getOperand(N->getNumOperands()-1);
4864     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4865     IsUnary = true;
4866     break;
4867   case X86ISD::MOVSS:
4868   case X86ISD::MOVSD:
4869     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4870     break;
4871   case X86ISD::VPERM2X128:
4872     ImmN = N->getOperand(N->getNumOperands()-1);
4873     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4874     if (Mask.empty()) return false;
4875     // Mask only contains negative index if an element is zero.
4876     if (std::any_of(Mask.begin(), Mask.end(),
4877                     [](int M){ return M == SM_SentinelZero; }))
4878       return false;
4879     break;
4880   case X86ISD::MOVSLDUP:
4881     DecodeMOVSLDUPMask(VT, Mask);
4882     IsUnary = true;
4883     break;
4884   case X86ISD::MOVSHDUP:
4885     DecodeMOVSHDUPMask(VT, Mask);
4886     IsUnary = true;
4887     break;
4888   case X86ISD::MOVDDUP:
4889     DecodeMOVDDUPMask(VT, Mask);
4890     IsUnary = true;
4891     break;
4892   case X86ISD::MOVLHPD:
4893   case X86ISD::MOVLPD:
4894   case X86ISD::MOVLPS:
4895     // Not yet implemented
4896     return false;
4897   case X86ISD::VPERMV: {
4898     IsUnary = true;
4899     SDValue MaskNode = N->getOperand(0);
4900     while (MaskNode->getOpcode() == ISD::BITCAST)
4901       MaskNode = MaskNode->getOperand(0);
4902
4903     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4904     SmallVector<uint64_t, 32> RawMask;
4905     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4906       // If we have a build-vector, then things are easy.
4907       assert(MaskNode.getSimpleValueType().isInteger() &&
4908              MaskNode.getSimpleValueType().getVectorNumElements() ==
4909              VT.getVectorNumElements());
4910
4911       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4912         SDValue Op = MaskNode->getOperand(i);
4913         if (Op->getOpcode() == ISD::UNDEF)
4914           RawMask.push_back((uint64_t)SM_SentinelUndef);
4915         else if (isa<ConstantSDNode>(Op)) {
4916           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4917           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4918         } else
4919           return false;
4920       }
4921       DecodeVPERMVMask(RawMask, Mask);
4922       break;
4923     }
4924     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4925       unsigned NumEltsInMask = MaskNode->getNumOperands();
4926       MaskNode = MaskNode->getOperand(0);
4927       if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4928         APInt MaskEltValue = CN->getAPIntValue();
4929         for (unsigned i = 0; i < NumEltsInMask; ++i)
4930           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4931         DecodeVPERMVMask(RawMask, Mask);
4932         break;
4933       }
4934       // It may be a scalar load
4935     }
4936
4937     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4938     if (!MaskLoad)
4939       return false;
4940
4941     SDValue Ptr = MaskLoad->getBasePtr();
4942     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4943         Ptr->getOpcode() == X86ISD::WrapperRIP)
4944       Ptr = Ptr->getOperand(0);
4945
4946     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4947     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4948       return false;
4949
4950     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4951       DecodeVPERMVMask(C, VT, Mask);
4952       if (Mask.empty())
4953         return false;
4954       break;
4955     }
4956     return false;
4957   }
4958   case X86ISD::VPERMV3: {
4959     IsUnary = false;
4960     SDValue MaskNode = N->getOperand(1);
4961     while (MaskNode->getOpcode() == ISD::BITCAST)
4962       MaskNode = MaskNode->getOperand(1);
4963
4964     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4965       // If we have a build-vector, then things are easy.
4966       assert(MaskNode.getSimpleValueType().isInteger() &&
4967              MaskNode.getSimpleValueType().getVectorNumElements() ==
4968              VT.getVectorNumElements());
4969
4970       SmallVector<uint64_t, 32> RawMask;
4971       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4972
4973       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4974         SDValue Op = MaskNode->getOperand(i);
4975         if (Op->getOpcode() == ISD::UNDEF)
4976           RawMask.push_back((uint64_t)SM_SentinelUndef);
4977         else {
4978           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4979           if (!CN)
4980             return false;
4981           APInt MaskElement = CN->getAPIntValue();
4982           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4983         }
4984       }
4985       DecodeVPERMV3Mask(RawMask, Mask);
4986       break;
4987     }
4988
4989     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4990     if (!MaskLoad)
4991       return false;
4992
4993     SDValue Ptr = MaskLoad->getBasePtr();
4994     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4995         Ptr->getOpcode() == X86ISD::WrapperRIP)
4996       Ptr = Ptr->getOperand(0);
4997
4998     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4999     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5000       return false;
5001
5002     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5003       DecodeVPERMV3Mask(C, VT, Mask);
5004       if (Mask.empty())
5005         return false;
5006       break;
5007     }
5008     return false;
5009   }
5010   default: llvm_unreachable("unknown target shuffle node");
5011   }
5012
5013   // If we have a fake unary shuffle, the shuffle mask is spread across two
5014   // inputs that are actually the same node. Re-map the mask to always point
5015   // into the first input.
5016   if (IsFakeUnary)
5017     for (int &M : Mask)
5018       if (M >= (int)Mask.size())
5019         M -= Mask.size();
5020
5021   return true;
5022 }
5023
5024 /// Returns the scalar element that will make up the ith
5025 /// element of the result of the vector shuffle.
5026 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5027                                    unsigned Depth) {
5028   if (Depth == 6)
5029     return SDValue();  // Limit search depth.
5030
5031   SDValue V = SDValue(N, 0);
5032   EVT VT = V.getValueType();
5033   unsigned Opcode = V.getOpcode();
5034
5035   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5036   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5037     int Elt = SV->getMaskElt(Index);
5038
5039     if (Elt < 0)
5040       return DAG.getUNDEF(VT.getVectorElementType());
5041
5042     unsigned NumElems = VT.getVectorNumElements();
5043     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5044                                          : SV->getOperand(1);
5045     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5046   }
5047
5048   // Recurse into target specific vector shuffles to find scalars.
5049   if (isTargetShuffle(Opcode)) {
5050     MVT ShufVT = V.getSimpleValueType();
5051     unsigned NumElems = ShufVT.getVectorNumElements();
5052     SmallVector<int, 16> ShuffleMask;
5053     bool IsUnary;
5054
5055     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5056       return SDValue();
5057
5058     int Elt = ShuffleMask[Index];
5059     if (Elt < 0)
5060       return DAG.getUNDEF(ShufVT.getVectorElementType());
5061
5062     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5063                                          : N->getOperand(1);
5064     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5065                                Depth+1);
5066   }
5067
5068   // Actual nodes that may contain scalar elements
5069   if (Opcode == ISD::BITCAST) {
5070     V = V.getOperand(0);
5071     EVT SrcVT = V.getValueType();
5072     unsigned NumElems = VT.getVectorNumElements();
5073
5074     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5075       return SDValue();
5076   }
5077
5078   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5079     return (Index == 0) ? V.getOperand(0)
5080                         : DAG.getUNDEF(VT.getVectorElementType());
5081
5082   if (V.getOpcode() == ISD::BUILD_VECTOR)
5083     return V.getOperand(Index);
5084
5085   return SDValue();
5086 }
5087
5088 /// Custom lower build_vector of v16i8.
5089 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5090                                        unsigned NumNonZero, unsigned NumZero,
5091                                        SelectionDAG &DAG,
5092                                        const X86Subtarget* Subtarget,
5093                                        const TargetLowering &TLI) {
5094   if (NumNonZero > 8)
5095     return SDValue();
5096
5097   SDLoc dl(Op);
5098   SDValue V;
5099   bool First = true;
5100
5101   // SSE4.1 - use PINSRB to insert each byte directly.
5102   if (Subtarget->hasSSE41()) {
5103     for (unsigned i = 0; i < 16; ++i) {
5104       bool isNonZero = (NonZeros & (1 << i)) != 0;
5105       if (isNonZero) {
5106         if (First) {
5107           if (NumZero)
5108             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5109           else
5110             V = DAG.getUNDEF(MVT::v16i8);
5111           First = false;
5112         }
5113         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5114                         MVT::v16i8, V, Op.getOperand(i),
5115                         DAG.getIntPtrConstant(i, dl));
5116       }
5117     }
5118
5119     return V;
5120   }
5121
5122   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5123   for (unsigned i = 0; i < 16; ++i) {
5124     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5125     if (ThisIsNonZero && First) {
5126       if (NumZero)
5127         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5128       else
5129         V = DAG.getUNDEF(MVT::v8i16);
5130       First = false;
5131     }
5132
5133     if ((i & 1) != 0) {
5134       SDValue ThisElt, LastElt;
5135       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5136       if (LastIsNonZero) {
5137         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5138                               MVT::i16, Op.getOperand(i-1));
5139       }
5140       if (ThisIsNonZero) {
5141         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5142         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5143                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5144         if (LastIsNonZero)
5145           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5146       } else
5147         ThisElt = LastElt;
5148
5149       if (ThisElt.getNode())
5150         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5151                         DAG.getIntPtrConstant(i/2, dl));
5152     }
5153   }
5154
5155   return DAG.getBitcast(MVT::v16i8, V);
5156 }
5157
5158 /// Custom lower build_vector of v8i16.
5159 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5160                                      unsigned NumNonZero, unsigned NumZero,
5161                                      SelectionDAG &DAG,
5162                                      const X86Subtarget* Subtarget,
5163                                      const TargetLowering &TLI) {
5164   if (NumNonZero > 4)
5165     return SDValue();
5166
5167   SDLoc dl(Op);
5168   SDValue V;
5169   bool First = true;
5170   for (unsigned i = 0; i < 8; ++i) {
5171     bool isNonZero = (NonZeros & (1 << i)) != 0;
5172     if (isNonZero) {
5173       if (First) {
5174         if (NumZero)
5175           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5176         else
5177           V = DAG.getUNDEF(MVT::v8i16);
5178         First = false;
5179       }
5180       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5181                       MVT::v8i16, V, Op.getOperand(i),
5182                       DAG.getIntPtrConstant(i, dl));
5183     }
5184   }
5185
5186   return V;
5187 }
5188
5189 /// Custom lower build_vector of v4i32 or v4f32.
5190 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5191                                      const X86Subtarget *Subtarget,
5192                                      const TargetLowering &TLI) {
5193   // Find all zeroable elements.
5194   std::bitset<4> Zeroable;
5195   for (int i=0; i < 4; ++i) {
5196     SDValue Elt = Op->getOperand(i);
5197     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5198   }
5199   assert(Zeroable.size() - Zeroable.count() > 1 &&
5200          "We expect at least two non-zero elements!");
5201
5202   // We only know how to deal with build_vector nodes where elements are either
5203   // zeroable or extract_vector_elt with constant index.
5204   SDValue FirstNonZero;
5205   unsigned FirstNonZeroIdx;
5206   for (unsigned i=0; i < 4; ++i) {
5207     if (Zeroable[i])
5208       continue;
5209     SDValue Elt = Op->getOperand(i);
5210     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5211         !isa<ConstantSDNode>(Elt.getOperand(1)))
5212       return SDValue();
5213     // Make sure that this node is extracting from a 128-bit vector.
5214     MVT VT = Elt.getOperand(0).getSimpleValueType();
5215     if (!VT.is128BitVector())
5216       return SDValue();
5217     if (!FirstNonZero.getNode()) {
5218       FirstNonZero = Elt;
5219       FirstNonZeroIdx = i;
5220     }
5221   }
5222
5223   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5224   SDValue V1 = FirstNonZero.getOperand(0);
5225   MVT VT = V1.getSimpleValueType();
5226
5227   // See if this build_vector can be lowered as a blend with zero.
5228   SDValue Elt;
5229   unsigned EltMaskIdx, EltIdx;
5230   int Mask[4];
5231   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5232     if (Zeroable[EltIdx]) {
5233       // The zero vector will be on the right hand side.
5234       Mask[EltIdx] = EltIdx+4;
5235       continue;
5236     }
5237
5238     Elt = Op->getOperand(EltIdx);
5239     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5240     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5241     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5242       break;
5243     Mask[EltIdx] = EltIdx;
5244   }
5245
5246   if (EltIdx == 4) {
5247     // Let the shuffle legalizer deal with blend operations.
5248     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5249     if (V1.getSimpleValueType() != VT)
5250       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5251     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5252   }
5253
5254   // See if we can lower this build_vector to a INSERTPS.
5255   if (!Subtarget->hasSSE41())
5256     return SDValue();
5257
5258   SDValue V2 = Elt.getOperand(0);
5259   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5260     V1 = SDValue();
5261
5262   bool CanFold = true;
5263   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5264     if (Zeroable[i])
5265       continue;
5266
5267     SDValue Current = Op->getOperand(i);
5268     SDValue SrcVector = Current->getOperand(0);
5269     if (!V1.getNode())
5270       V1 = SrcVector;
5271     CanFold = SrcVector == V1 &&
5272       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5273   }
5274
5275   if (!CanFold)
5276     return SDValue();
5277
5278   assert(V1.getNode() && "Expected at least two non-zero elements!");
5279   if (V1.getSimpleValueType() != MVT::v4f32)
5280     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5281   if (V2.getSimpleValueType() != MVT::v4f32)
5282     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5283
5284   // Ok, we can emit an INSERTPS instruction.
5285   unsigned ZMask = Zeroable.to_ulong();
5286
5287   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5288   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5289   SDLoc DL(Op);
5290   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5291                                DAG.getIntPtrConstant(InsertPSMask, DL));
5292   return DAG.getBitcast(VT, Result);
5293 }
5294
5295 /// Return a vector logical shift node.
5296 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5297                          unsigned NumBits, SelectionDAG &DAG,
5298                          const TargetLowering &TLI, SDLoc dl) {
5299   assert(VT.is128BitVector() && "Unknown type for VShift");
5300   MVT ShVT = MVT::v2i64;
5301   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5302   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5303   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5304   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5305   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5306   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5307 }
5308
5309 static SDValue
5310 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5311
5312   // Check if the scalar load can be widened into a vector load. And if
5313   // the address is "base + cst" see if the cst can be "absorbed" into
5314   // the shuffle mask.
5315   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5316     SDValue Ptr = LD->getBasePtr();
5317     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5318       return SDValue();
5319     EVT PVT = LD->getValueType(0);
5320     if (PVT != MVT::i32 && PVT != MVT::f32)
5321       return SDValue();
5322
5323     int FI = -1;
5324     int64_t Offset = 0;
5325     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5326       FI = FINode->getIndex();
5327       Offset = 0;
5328     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5329                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5330       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5331       Offset = Ptr.getConstantOperandVal(1);
5332       Ptr = Ptr.getOperand(0);
5333     } else {
5334       return SDValue();
5335     }
5336
5337     // FIXME: 256-bit vector instructions don't require a strict alignment,
5338     // improve this code to support it better.
5339     unsigned RequiredAlign = VT.getSizeInBits()/8;
5340     SDValue Chain = LD->getChain();
5341     // Make sure the stack object alignment is at least 16 or 32.
5342     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5343     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5344       if (MFI->isFixedObjectIndex(FI)) {
5345         // Can't change the alignment. FIXME: It's possible to compute
5346         // the exact stack offset and reference FI + adjust offset instead.
5347         // If someone *really* cares about this. That's the way to implement it.
5348         return SDValue();
5349       } else {
5350         MFI->setObjectAlignment(FI, RequiredAlign);
5351       }
5352     }
5353
5354     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5355     // Ptr + (Offset & ~15).
5356     if (Offset < 0)
5357       return SDValue();
5358     if ((Offset % RequiredAlign) & 3)
5359       return SDValue();
5360     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5361     if (StartOffset) {
5362       SDLoc DL(Ptr);
5363       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5364                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5365     }
5366
5367     int EltNo = (Offset - StartOffset) >> 2;
5368     unsigned NumElems = VT.getVectorNumElements();
5369
5370     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5371     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5372                              LD->getPointerInfo().getWithOffset(StartOffset),
5373                              false, false, false, 0);
5374
5375     SmallVector<int, 8> Mask(NumElems, EltNo);
5376
5377     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5378   }
5379
5380   return SDValue();
5381 }
5382
5383 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5384 /// elements can be replaced by a single large load which has the same value as
5385 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5386 ///
5387 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5388 ///
5389 /// FIXME: we'd also like to handle the case where the last elements are zero
5390 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5391 /// There's even a handy isZeroNode for that purpose.
5392 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5393                                         SDLoc &DL, SelectionDAG &DAG,
5394                                         bool isAfterLegalize) {
5395   unsigned NumElems = Elts.size();
5396
5397   LoadSDNode *LDBase = nullptr;
5398   unsigned LastLoadedElt = -1U;
5399
5400   // For each element in the initializer, see if we've found a load or an undef.
5401   // If we don't find an initial load element, or later load elements are
5402   // non-consecutive, bail out.
5403   for (unsigned i = 0; i < NumElems; ++i) {
5404     SDValue Elt = Elts[i];
5405     // Look through a bitcast.
5406     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5407       Elt = Elt.getOperand(0);
5408     if (!Elt.getNode() ||
5409         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5410       return SDValue();
5411     if (!LDBase) {
5412       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5413         return SDValue();
5414       LDBase = cast<LoadSDNode>(Elt.getNode());
5415       LastLoadedElt = i;
5416       continue;
5417     }
5418     if (Elt.getOpcode() == ISD::UNDEF)
5419       continue;
5420
5421     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5422     EVT LdVT = Elt.getValueType();
5423     // Each loaded element must be the correct fractional portion of the
5424     // requested vector load.
5425     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5426       return SDValue();
5427     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5428       return SDValue();
5429     LastLoadedElt = i;
5430   }
5431
5432   // If we have found an entire vector of loads and undefs, then return a large
5433   // load of the entire vector width starting at the base pointer.  If we found
5434   // consecutive loads for the low half, generate a vzext_load node.
5435   if (LastLoadedElt == NumElems - 1) {
5436     assert(LDBase && "Did not find base load for merging consecutive loads");
5437     EVT EltVT = LDBase->getValueType(0);
5438     // Ensure that the input vector size for the merged loads matches the
5439     // cumulative size of the input elements.
5440     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5441       return SDValue();
5442
5443     if (isAfterLegalize &&
5444         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5445       return SDValue();
5446
5447     SDValue NewLd = SDValue();
5448
5449     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5450                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5451                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5452                         LDBase->getAlignment());
5453
5454     if (LDBase->hasAnyUseOfValue(1)) {
5455       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5456                                      SDValue(LDBase, 1),
5457                                      SDValue(NewLd.getNode(), 1));
5458       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5459       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5460                              SDValue(NewLd.getNode(), 1));
5461     }
5462
5463     return NewLd;
5464   }
5465
5466   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5467   //of a v4i32 / v4f32. It's probably worth generalizing.
5468   EVT EltVT = VT.getVectorElementType();
5469   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5470       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5471     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5472     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5473     SDValue ResNode =
5474         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5475                                 LDBase->getPointerInfo(),
5476                                 LDBase->getAlignment(),
5477                                 false/*isVolatile*/, true/*ReadMem*/,
5478                                 false/*WriteMem*/);
5479
5480     // Make sure the newly-created LOAD is in the same position as LDBase in
5481     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5482     // update uses of LDBase's output chain to use the TokenFactor.
5483     if (LDBase->hasAnyUseOfValue(1)) {
5484       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5485                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5486       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5487       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5488                              SDValue(ResNode.getNode(), 1));
5489     }
5490
5491     return DAG.getBitcast(VT, ResNode);
5492   }
5493   return SDValue();
5494 }
5495
5496 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5497 /// to generate a splat value for the following cases:
5498 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5499 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5500 /// a scalar load, or a constant.
5501 /// The VBROADCAST node is returned when a pattern is found,
5502 /// or SDValue() otherwise.
5503 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5504                                     SelectionDAG &DAG) {
5505   // VBROADCAST requires AVX.
5506   // TODO: Splats could be generated for non-AVX CPUs using SSE
5507   // instructions, but there's less potential gain for only 128-bit vectors.
5508   if (!Subtarget->hasAVX())
5509     return SDValue();
5510
5511   MVT VT = Op.getSimpleValueType();
5512   SDLoc dl(Op);
5513
5514   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5515          "Unsupported vector type for broadcast.");
5516
5517   SDValue Ld;
5518   bool ConstSplatVal;
5519
5520   switch (Op.getOpcode()) {
5521     default:
5522       // Unknown pattern found.
5523       return SDValue();
5524
5525     case ISD::BUILD_VECTOR: {
5526       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5527       BitVector UndefElements;
5528       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5529
5530       // We need a splat of a single value to use broadcast, and it doesn't
5531       // make any sense if the value is only in one element of the vector.
5532       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5533         return SDValue();
5534
5535       Ld = Splat;
5536       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5537                        Ld.getOpcode() == ISD::ConstantFP);
5538
5539       // Make sure that all of the users of a non-constant load are from the
5540       // BUILD_VECTOR node.
5541       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5542         return SDValue();
5543       break;
5544     }
5545
5546     case ISD::VECTOR_SHUFFLE: {
5547       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5548
5549       // Shuffles must have a splat mask where the first element is
5550       // broadcasted.
5551       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5552         return SDValue();
5553
5554       SDValue Sc = Op.getOperand(0);
5555       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5556           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5557
5558         if (!Subtarget->hasInt256())
5559           return SDValue();
5560
5561         // Use the register form of the broadcast instruction available on AVX2.
5562         if (VT.getSizeInBits() >= 256)
5563           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5564         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5565       }
5566
5567       Ld = Sc.getOperand(0);
5568       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5569                        Ld.getOpcode() == ISD::ConstantFP);
5570
5571       // The scalar_to_vector node and the suspected
5572       // load node must have exactly one user.
5573       // Constants may have multiple users.
5574
5575       // AVX-512 has register version of the broadcast
5576       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5577         Ld.getValueType().getSizeInBits() >= 32;
5578       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5579           !hasRegVer))
5580         return SDValue();
5581       break;
5582     }
5583   }
5584
5585   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5586   bool IsGE256 = (VT.getSizeInBits() >= 256);
5587
5588   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5589   // instruction to save 8 or more bytes of constant pool data.
5590   // TODO: If multiple splats are generated to load the same constant,
5591   // it may be detrimental to overall size. There needs to be a way to detect
5592   // that condition to know if this is truly a size win.
5593   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5594
5595   // Handle broadcasting a single constant scalar from the constant pool
5596   // into a vector.
5597   // On Sandybridge (no AVX2), it is still better to load a constant vector
5598   // from the constant pool and not to broadcast it from a scalar.
5599   // But override that restriction when optimizing for size.
5600   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5601   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5602     EVT CVT = Ld.getValueType();
5603     assert(!CVT.isVector() && "Must not broadcast a vector type");
5604
5605     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5606     // For size optimization, also splat v2f64 and v2i64, and for size opt
5607     // with AVX2, also splat i8 and i16.
5608     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5609     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5610         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5611       const Constant *C = nullptr;
5612       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5613         C = CI->getConstantIntValue();
5614       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5615         C = CF->getConstantFPValue();
5616
5617       assert(C && "Invalid constant type");
5618
5619       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5620       SDValue CP =
5621           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5622       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5623       Ld = DAG.getLoad(
5624           CVT, dl, DAG.getEntryNode(), CP,
5625           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5626           false, false, Alignment);
5627
5628       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5629     }
5630   }
5631
5632   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5633
5634   // Handle AVX2 in-register broadcasts.
5635   if (!IsLoad && Subtarget->hasInt256() &&
5636       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5637     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5638
5639   // The scalar source must be a normal load.
5640   if (!IsLoad)
5641     return SDValue();
5642
5643   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5644       (Subtarget->hasVLX() && ScalarSize == 64))
5645     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5646
5647   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5648   // double since there is no vbroadcastsd xmm
5649   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5650     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5651       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5652   }
5653
5654   // Unsupported broadcast.
5655   return SDValue();
5656 }
5657
5658 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5659 /// underlying vector and index.
5660 ///
5661 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5662 /// index.
5663 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5664                                          SDValue ExtIdx) {
5665   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5666   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5667     return Idx;
5668
5669   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5670   // lowered this:
5671   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5672   // to:
5673   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5674   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5675   //                           undef)
5676   //                       Constant<0>)
5677   // In this case the vector is the extract_subvector expression and the index
5678   // is 2, as specified by the shuffle.
5679   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5680   SDValue ShuffleVec = SVOp->getOperand(0);
5681   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5682   assert(ShuffleVecVT.getVectorElementType() ==
5683          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5684
5685   int ShuffleIdx = SVOp->getMaskElt(Idx);
5686   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5687     ExtractedFromVec = ShuffleVec;
5688     return ShuffleIdx;
5689   }
5690   return Idx;
5691 }
5692
5693 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5694   MVT VT = Op.getSimpleValueType();
5695
5696   // Skip if insert_vec_elt is not supported.
5697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5698   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5699     return SDValue();
5700
5701   SDLoc DL(Op);
5702   unsigned NumElems = Op.getNumOperands();
5703
5704   SDValue VecIn1;
5705   SDValue VecIn2;
5706   SmallVector<unsigned, 4> InsertIndices;
5707   SmallVector<int, 8> Mask(NumElems, -1);
5708
5709   for (unsigned i = 0; i != NumElems; ++i) {
5710     unsigned Opc = Op.getOperand(i).getOpcode();
5711
5712     if (Opc == ISD::UNDEF)
5713       continue;
5714
5715     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5716       // Quit if more than 1 elements need inserting.
5717       if (InsertIndices.size() > 1)
5718         return SDValue();
5719
5720       InsertIndices.push_back(i);
5721       continue;
5722     }
5723
5724     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5725     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5726     // Quit if non-constant index.
5727     if (!isa<ConstantSDNode>(ExtIdx))
5728       return SDValue();
5729     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5730
5731     // Quit if extracted from vector of different type.
5732     if (ExtractedFromVec.getValueType() != VT)
5733       return SDValue();
5734
5735     if (!VecIn1.getNode())
5736       VecIn1 = ExtractedFromVec;
5737     else if (VecIn1 != ExtractedFromVec) {
5738       if (!VecIn2.getNode())
5739         VecIn2 = ExtractedFromVec;
5740       else if (VecIn2 != ExtractedFromVec)
5741         // Quit if more than 2 vectors to shuffle
5742         return SDValue();
5743     }
5744
5745     if (ExtractedFromVec == VecIn1)
5746       Mask[i] = Idx;
5747     else if (ExtractedFromVec == VecIn2)
5748       Mask[i] = Idx + NumElems;
5749   }
5750
5751   if (!VecIn1.getNode())
5752     return SDValue();
5753
5754   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5755   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5756   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5757     unsigned Idx = InsertIndices[i];
5758     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5759                      DAG.getIntPtrConstant(Idx, DL));
5760   }
5761
5762   return NV;
5763 }
5764
5765 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5766   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5767          Op.getScalarValueSizeInBits() == 1 &&
5768          "Can not convert non-constant vector");
5769   uint64_t Immediate = 0;
5770   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5771     SDValue In = Op.getOperand(idx);
5772     if (In.getOpcode() != ISD::UNDEF)
5773       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5774   }
5775   SDLoc dl(Op);
5776   MVT VT =
5777    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5778   return DAG.getConstant(Immediate, dl, VT);
5779 }
5780 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5781 SDValue
5782 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5783
5784   MVT VT = Op.getSimpleValueType();
5785   assert((VT.getVectorElementType() == MVT::i1) &&
5786          "Unexpected type in LowerBUILD_VECTORvXi1!");
5787
5788   SDLoc dl(Op);
5789   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5790     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5791     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5792     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5793   }
5794
5795   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5796     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5797     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5798     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5799   }
5800
5801   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5802     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5803     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5804       return DAG.getBitcast(VT, Imm);
5805     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5806     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5807                         DAG.getIntPtrConstant(0, dl));
5808   }
5809
5810   // Vector has one or more non-const elements
5811   uint64_t Immediate = 0;
5812   SmallVector<unsigned, 16> NonConstIdx;
5813   bool IsSplat = true;
5814   bool HasConstElts = false;
5815   int SplatIdx = -1;
5816   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5817     SDValue In = Op.getOperand(idx);
5818     if (In.getOpcode() == ISD::UNDEF)
5819       continue;
5820     if (!isa<ConstantSDNode>(In))
5821       NonConstIdx.push_back(idx);
5822     else {
5823       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5824       HasConstElts = true;
5825     }
5826     if (SplatIdx == -1)
5827       SplatIdx = idx;
5828     else if (In != Op.getOperand(SplatIdx))
5829       IsSplat = false;
5830   }
5831
5832   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5833   if (IsSplat)
5834     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5835                        DAG.getConstant(1, dl, VT),
5836                        DAG.getConstant(0, dl, VT));
5837
5838   // insert elements one by one
5839   SDValue DstVec;
5840   SDValue Imm;
5841   if (Immediate) {
5842     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5843     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5844   }
5845   else if (HasConstElts)
5846     Imm = DAG.getConstant(0, dl, VT);
5847   else
5848     Imm = DAG.getUNDEF(VT);
5849   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5850     DstVec = DAG.getBitcast(VT, Imm);
5851   else {
5852     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5853     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5854                          DAG.getIntPtrConstant(0, dl));
5855   }
5856
5857   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5858     unsigned InsertIdx = NonConstIdx[i];
5859     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5860                          Op.getOperand(InsertIdx),
5861                          DAG.getIntPtrConstant(InsertIdx, dl));
5862   }
5863   return DstVec;
5864 }
5865
5866 /// \brief Return true if \p N implements a horizontal binop and return the
5867 /// operands for the horizontal binop into V0 and V1.
5868 ///
5869 /// This is a helper function of LowerToHorizontalOp().
5870 /// This function checks that the build_vector \p N in input implements a
5871 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5872 /// operation to match.
5873 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5874 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5875 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5876 /// arithmetic sub.
5877 ///
5878 /// This function only analyzes elements of \p N whose indices are
5879 /// in range [BaseIdx, LastIdx).
5880 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5881                               SelectionDAG &DAG,
5882                               unsigned BaseIdx, unsigned LastIdx,
5883                               SDValue &V0, SDValue &V1) {
5884   EVT VT = N->getValueType(0);
5885
5886   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5887   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5888          "Invalid Vector in input!");
5889
5890   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5891   bool CanFold = true;
5892   unsigned ExpectedVExtractIdx = BaseIdx;
5893   unsigned NumElts = LastIdx - BaseIdx;
5894   V0 = DAG.getUNDEF(VT);
5895   V1 = DAG.getUNDEF(VT);
5896
5897   // Check if N implements a horizontal binop.
5898   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5899     SDValue Op = N->getOperand(i + BaseIdx);
5900
5901     // Skip UNDEFs.
5902     if (Op->getOpcode() == ISD::UNDEF) {
5903       // Update the expected vector extract index.
5904       if (i * 2 == NumElts)
5905         ExpectedVExtractIdx = BaseIdx;
5906       ExpectedVExtractIdx += 2;
5907       continue;
5908     }
5909
5910     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5911
5912     if (!CanFold)
5913       break;
5914
5915     SDValue Op0 = Op.getOperand(0);
5916     SDValue Op1 = Op.getOperand(1);
5917
5918     // Try to match the following pattern:
5919     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5920     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5921         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5922         Op0.getOperand(0) == Op1.getOperand(0) &&
5923         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5924         isa<ConstantSDNode>(Op1.getOperand(1)));
5925     if (!CanFold)
5926       break;
5927
5928     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5929     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5930
5931     if (i * 2 < NumElts) {
5932       if (V0.getOpcode() == ISD::UNDEF) {
5933         V0 = Op0.getOperand(0);
5934         if (V0.getValueType() != VT)
5935           return false;
5936       }
5937     } else {
5938       if (V1.getOpcode() == ISD::UNDEF) {
5939         V1 = Op0.getOperand(0);
5940         if (V1.getValueType() != VT)
5941           return false;
5942       }
5943       if (i * 2 == NumElts)
5944         ExpectedVExtractIdx = BaseIdx;
5945     }
5946
5947     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5948     if (I0 == ExpectedVExtractIdx)
5949       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5950     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5951       // Try to match the following dag sequence:
5952       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5953       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5954     } else
5955       CanFold = false;
5956
5957     ExpectedVExtractIdx += 2;
5958   }
5959
5960   return CanFold;
5961 }
5962
5963 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5964 /// a concat_vector.
5965 ///
5966 /// This is a helper function of LowerToHorizontalOp().
5967 /// This function expects two 256-bit vectors called V0 and V1.
5968 /// At first, each vector is split into two separate 128-bit vectors.
5969 /// Then, the resulting 128-bit vectors are used to implement two
5970 /// horizontal binary operations.
5971 ///
5972 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5973 ///
5974 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5975 /// the two new horizontal binop.
5976 /// When Mode is set, the first horizontal binop dag node would take as input
5977 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5978 /// horizontal binop dag node would take as input the lower 128-bit of V1
5979 /// and the upper 128-bit of V1.
5980 ///   Example:
5981 ///     HADD V0_LO, V0_HI
5982 ///     HADD V1_LO, V1_HI
5983 ///
5984 /// Otherwise, the first horizontal binop dag node takes as input the lower
5985 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5986 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5987 ///   Example:
5988 ///     HADD V0_LO, V1_LO
5989 ///     HADD V0_HI, V1_HI
5990 ///
5991 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5992 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5993 /// the upper 128-bits of the result.
5994 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5995                                      SDLoc DL, SelectionDAG &DAG,
5996                                      unsigned X86Opcode, bool Mode,
5997                                      bool isUndefLO, bool isUndefHI) {
5998   EVT VT = V0.getValueType();
5999   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6000          "Invalid nodes in input!");
6001
6002   unsigned NumElts = VT.getVectorNumElements();
6003   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6004   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6005   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6006   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6007   EVT NewVT = V0_LO.getValueType();
6008
6009   SDValue LO = DAG.getUNDEF(NewVT);
6010   SDValue HI = DAG.getUNDEF(NewVT);
6011
6012   if (Mode) {
6013     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6014     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6015       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6016     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6017       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6018   } else {
6019     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6020     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6021                        V1_LO->getOpcode() != ISD::UNDEF))
6022       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6023
6024     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6025                        V1_HI->getOpcode() != ISD::UNDEF))
6026       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6027   }
6028
6029   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6030 }
6031
6032 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6033 /// node.
6034 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6035                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6036   MVT VT = BV->getSimpleValueType(0);
6037   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6038       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6039     return SDValue();
6040
6041   SDLoc DL(BV);
6042   unsigned NumElts = VT.getVectorNumElements();
6043   SDValue InVec0 = DAG.getUNDEF(VT);
6044   SDValue InVec1 = DAG.getUNDEF(VT);
6045
6046   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6047           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6048
6049   // Odd-numbered elements in the input build vector are obtained from
6050   // adding two integer/float elements.
6051   // Even-numbered elements in the input build vector are obtained from
6052   // subtracting two integer/float elements.
6053   unsigned ExpectedOpcode = ISD::FSUB;
6054   unsigned NextExpectedOpcode = ISD::FADD;
6055   bool AddFound = false;
6056   bool SubFound = false;
6057
6058   for (unsigned i = 0, e = NumElts; i != e; ++i) {
6059     SDValue Op = BV->getOperand(i);
6060
6061     // Skip 'undef' values.
6062     unsigned Opcode = Op.getOpcode();
6063     if (Opcode == ISD::UNDEF) {
6064       std::swap(ExpectedOpcode, NextExpectedOpcode);
6065       continue;
6066     }
6067
6068     // Early exit if we found an unexpected opcode.
6069     if (Opcode != ExpectedOpcode)
6070       return SDValue();
6071
6072     SDValue Op0 = Op.getOperand(0);
6073     SDValue Op1 = Op.getOperand(1);
6074
6075     // Try to match the following pattern:
6076     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6077     // Early exit if we cannot match that sequence.
6078     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6079         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6080         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6081         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6082         Op0.getOperand(1) != Op1.getOperand(1))
6083       return SDValue();
6084
6085     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6086     if (I0 != i)
6087       return SDValue();
6088
6089     // We found a valid add/sub node. Update the information accordingly.
6090     if (i & 1)
6091       AddFound = true;
6092     else
6093       SubFound = true;
6094
6095     // Update InVec0 and InVec1.
6096     if (InVec0.getOpcode() == ISD::UNDEF) {
6097       InVec0 = Op0.getOperand(0);
6098       if (InVec0.getSimpleValueType() != VT)
6099         return SDValue();
6100     }
6101     if (InVec1.getOpcode() == ISD::UNDEF) {
6102       InVec1 = Op1.getOperand(0);
6103       if (InVec1.getSimpleValueType() != VT)
6104         return SDValue();
6105     }
6106
6107     // Make sure that operands in input to each add/sub node always
6108     // come from a same pair of vectors.
6109     if (InVec0 != Op0.getOperand(0)) {
6110       if (ExpectedOpcode == ISD::FSUB)
6111         return SDValue();
6112
6113       // FADD is commutable. Try to commute the operands
6114       // and then test again.
6115       std::swap(Op0, Op1);
6116       if (InVec0 != Op0.getOperand(0))
6117         return SDValue();
6118     }
6119
6120     if (InVec1 != Op1.getOperand(0))
6121       return SDValue();
6122
6123     // Update the pair of expected opcodes.
6124     std::swap(ExpectedOpcode, NextExpectedOpcode);
6125   }
6126
6127   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6128   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6129       InVec1.getOpcode() != ISD::UNDEF)
6130     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6131
6132   return SDValue();
6133 }
6134
6135 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6136 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6137                                    const X86Subtarget *Subtarget,
6138                                    SelectionDAG &DAG) {
6139   MVT VT = BV->getSimpleValueType(0);
6140   unsigned NumElts = VT.getVectorNumElements();
6141   unsigned NumUndefsLO = 0;
6142   unsigned NumUndefsHI = 0;
6143   unsigned Half = NumElts/2;
6144
6145   // Count the number of UNDEF operands in the build_vector in input.
6146   for (unsigned i = 0, e = Half; i != e; ++i)
6147     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6148       NumUndefsLO++;
6149
6150   for (unsigned i = Half, e = NumElts; i != e; ++i)
6151     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6152       NumUndefsHI++;
6153
6154   // Early exit if this is either a build_vector of all UNDEFs or all the
6155   // operands but one are UNDEF.
6156   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6157     return SDValue();
6158
6159   SDLoc DL(BV);
6160   SDValue InVec0, InVec1;
6161   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6162     // Try to match an SSE3 float HADD/HSUB.
6163     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6164       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6165
6166     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6167       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6168   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6169     // Try to match an SSSE3 integer HADD/HSUB.
6170     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6171       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6172
6173     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6174       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6175   }
6176
6177   if (!Subtarget->hasAVX())
6178     return SDValue();
6179
6180   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6181     // Try to match an AVX horizontal add/sub of packed single/double
6182     // precision floating point values from 256-bit vectors.
6183     SDValue InVec2, InVec3;
6184     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6185         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6186         ((InVec0.getOpcode() == ISD::UNDEF ||
6187           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6188         ((InVec1.getOpcode() == ISD::UNDEF ||
6189           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6190       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6191
6192     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6193         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6194         ((InVec0.getOpcode() == ISD::UNDEF ||
6195           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6196         ((InVec1.getOpcode() == ISD::UNDEF ||
6197           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6198       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6199   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6200     // Try to match an AVX2 horizontal add/sub of signed integers.
6201     SDValue InVec2, InVec3;
6202     unsigned X86Opcode;
6203     bool CanFold = true;
6204
6205     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6206         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6207         ((InVec0.getOpcode() == ISD::UNDEF ||
6208           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6209         ((InVec1.getOpcode() == ISD::UNDEF ||
6210           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6211       X86Opcode = X86ISD::HADD;
6212     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6213         isHorizontalBinOp(BV, ISD::SUB, 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::HSUB;
6219     else
6220       CanFold = false;
6221
6222     if (CanFold) {
6223       // Fold this build_vector into a single horizontal add/sub.
6224       // Do this only if the target has AVX2.
6225       if (Subtarget->hasAVX2())
6226         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6227
6228       // Do not try to expand this build_vector into a pair of horizontal
6229       // add/sub if we can emit a pair of scalar add/sub.
6230       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6231         return SDValue();
6232
6233       // Convert this build_vector into a pair of horizontal binop followed by
6234       // a concat vector.
6235       bool isUndefLO = NumUndefsLO == Half;
6236       bool isUndefHI = NumUndefsHI == Half;
6237       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6238                                    isUndefLO, isUndefHI);
6239     }
6240   }
6241
6242   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6243        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6244     unsigned X86Opcode;
6245     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6246       X86Opcode = X86ISD::HADD;
6247     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6248       X86Opcode = X86ISD::HSUB;
6249     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6250       X86Opcode = X86ISD::FHADD;
6251     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6252       X86Opcode = X86ISD::FHSUB;
6253     else
6254       return SDValue();
6255
6256     // Don't try to expand this build_vector into a pair of horizontal add/sub
6257     // if we can simply emit a pair of scalar add/sub.
6258     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6259       return SDValue();
6260
6261     // Convert this build_vector into two horizontal add/sub followed by
6262     // a concat vector.
6263     bool isUndefLO = NumUndefsLO == Half;
6264     bool isUndefHI = NumUndefsHI == Half;
6265     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6266                                  isUndefLO, isUndefHI);
6267   }
6268
6269   return SDValue();
6270 }
6271
6272 SDValue
6273 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6274   SDLoc dl(Op);
6275
6276   MVT VT = Op.getSimpleValueType();
6277   MVT ExtVT = VT.getVectorElementType();
6278   unsigned NumElems = Op.getNumOperands();
6279
6280   // Generate vectors for predicate vectors.
6281   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6282     return LowerBUILD_VECTORvXi1(Op, DAG);
6283
6284   // Vectors containing all zeros can be matched by pxor and xorps later
6285   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6286     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6287     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6288     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6289       return Op;
6290
6291     return getZeroVector(VT, Subtarget, DAG, dl);
6292   }
6293
6294   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6295   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6296   // vpcmpeqd on 256-bit vectors.
6297   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6298     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6299       return Op;
6300
6301     if (!VT.is512BitVector())
6302       return getOnesVector(VT, Subtarget, DAG, dl);
6303   }
6304
6305   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6306   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6307     return AddSub;
6308   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6309     return HorizontalOp;
6310   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6311     return Broadcast;
6312
6313   unsigned EVTBits = ExtVT.getSizeInBits();
6314
6315   unsigned NumZero  = 0;
6316   unsigned NumNonZero = 0;
6317   uint64_t NonZeros = 0;
6318   bool IsAllConstants = true;
6319   SmallSet<SDValue, 8> Values;
6320   for (unsigned i = 0; i < NumElems; ++i) {
6321     SDValue Elt = Op.getOperand(i);
6322     if (Elt.getOpcode() == ISD::UNDEF)
6323       continue;
6324     Values.insert(Elt);
6325     if (Elt.getOpcode() != ISD::Constant &&
6326         Elt.getOpcode() != ISD::ConstantFP)
6327       IsAllConstants = false;
6328     if (X86::isZeroNode(Elt))
6329       NumZero++;
6330     else {
6331       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6332       NonZeros |= ((uint64_t)1 << i);
6333       NumNonZero++;
6334     }
6335   }
6336
6337   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6338   if (NumNonZero == 0)
6339     return DAG.getUNDEF(VT);
6340
6341   // Special case for single non-zero, non-undef, element.
6342   if (NumNonZero == 1) {
6343     unsigned Idx = countTrailingZeros(NonZeros);
6344     SDValue Item = Op.getOperand(Idx);
6345
6346     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6347     // the value are obviously zero, truncate the value to i32 and do the
6348     // insertion that way.  Only do this if the value is non-constant or if the
6349     // value is a constant being inserted into element 0.  It is cheaper to do
6350     // a constant pool load than it is to do a movd + shuffle.
6351     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6352         (!IsAllConstants || Idx == 0)) {
6353       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6354         // Handle SSE only.
6355         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6356         MVT VecVT = MVT::v4i32;
6357
6358         // Truncate the value (which may itself be a constant) to i32, and
6359         // convert it to a vector with movd (S2V+shuffle to zero extend).
6360         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6361         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6362         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6363                                       Item, Idx * 2, true, Subtarget, DAG));
6364       }
6365     }
6366
6367     // If we have a constant or non-constant insertion into the low element of
6368     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6369     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6370     // depending on what the source datatype is.
6371     if (Idx == 0) {
6372       if (NumZero == 0)
6373         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6374
6375       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6376           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6377         if (VT.is512BitVector()) {
6378           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6379           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6380                              Item, DAG.getIntPtrConstant(0, dl));
6381         }
6382         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6383                "Expected an SSE value type!");
6384         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6385         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6386         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6387       }
6388
6389       // We can't directly insert an i8 or i16 into a vector, so zero extend
6390       // it to i32 first.
6391       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6392         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6393         if (VT.is256BitVector()) {
6394           if (Subtarget->hasAVX()) {
6395             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6396             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6397           } else {
6398             // Without AVX, we need to extend to a 128-bit vector and then
6399             // insert into the 256-bit vector.
6400             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6401             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6402             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6403           }
6404         } else {
6405           assert(VT.is128BitVector() && "Expected an SSE value type!");
6406           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6407           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6408         }
6409         return DAG.getBitcast(VT, Item);
6410       }
6411     }
6412
6413     // Is it a vector logical left shift?
6414     if (NumElems == 2 && Idx == 1 &&
6415         X86::isZeroNode(Op.getOperand(0)) &&
6416         !X86::isZeroNode(Op.getOperand(1))) {
6417       unsigned NumBits = VT.getSizeInBits();
6418       return getVShift(true, VT,
6419                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6420                                    VT, Op.getOperand(1)),
6421                        NumBits/2, DAG, *this, dl);
6422     }
6423
6424     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6425       return SDValue();
6426
6427     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6428     // is a non-constant being inserted into an element other than the low one,
6429     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6430     // movd/movss) to move this into the low element, then shuffle it into
6431     // place.
6432     if (EVTBits == 32) {
6433       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6434       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6435     }
6436   }
6437
6438   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6439   if (Values.size() == 1) {
6440     if (EVTBits == 32) {
6441       // Instead of a shuffle like this:
6442       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6443       // Check if it's possible to issue this instead.
6444       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6445       unsigned Idx = countTrailingZeros(NonZeros);
6446       SDValue Item = Op.getOperand(Idx);
6447       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6448         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6449     }
6450     return SDValue();
6451   }
6452
6453   // A vector full of immediates; various special cases are already
6454   // handled, so this is best done with a single constant-pool load.
6455   if (IsAllConstants)
6456     return SDValue();
6457
6458   // For AVX-length vectors, see if we can use a vector load to get all of the
6459   // elements, otherwise build the individual 128-bit pieces and use
6460   // shuffles to put them in place.
6461   if (VT.is256BitVector() || VT.is512BitVector()) {
6462     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6463
6464     // Check for a build vector of consecutive loads.
6465     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6466       return LD;
6467
6468     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6469
6470     // Build both the lower and upper subvector.
6471     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6472                                 makeArrayRef(&V[0], NumElems/2));
6473     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6474                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6475
6476     // Recreate the wider vector with the lower and upper part.
6477     if (VT.is256BitVector())
6478       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6479     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6480   }
6481
6482   // Let legalizer expand 2-wide build_vectors.
6483   if (EVTBits == 64) {
6484     if (NumNonZero == 1) {
6485       // One half is zero or undef.
6486       unsigned Idx = countTrailingZeros(NonZeros);
6487       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6488                                Op.getOperand(Idx));
6489       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6490     }
6491     return SDValue();
6492   }
6493
6494   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6495   if (EVTBits == 8 && NumElems == 16)
6496     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6497                                           DAG, Subtarget, *this))
6498       return V;
6499
6500   if (EVTBits == 16 && NumElems == 8)
6501     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6502                                           DAG, Subtarget, *this))
6503       return V;
6504
6505   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6506   if (EVTBits == 32 && NumElems == 4)
6507     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6508       return V;
6509
6510   // If element VT is == 32 bits, turn it into a number of shuffles.
6511   SmallVector<SDValue, 8> V(NumElems);
6512   if (NumElems == 4 && NumZero > 0) {
6513     for (unsigned i = 0; i < 4; ++i) {
6514       bool isZero = !(NonZeros & (1ULL << i));
6515       if (isZero)
6516         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6517       else
6518         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6519     }
6520
6521     for (unsigned i = 0; i < 2; ++i) {
6522       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6523         default: break;
6524         case 0:
6525           V[i] = V[i*2];  // Must be a zero vector.
6526           break;
6527         case 1:
6528           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6529           break;
6530         case 2:
6531           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6532           break;
6533         case 3:
6534           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6535           break;
6536       }
6537     }
6538
6539     bool Reverse1 = (NonZeros & 0x3) == 2;
6540     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6541     int MaskVec[] = {
6542       Reverse1 ? 1 : 0,
6543       Reverse1 ? 0 : 1,
6544       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6545       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6546     };
6547     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6548   }
6549
6550   if (Values.size() > 1 && VT.is128BitVector()) {
6551     // Check for a build vector of consecutive loads.
6552     for (unsigned i = 0; i < NumElems; ++i)
6553       V[i] = Op.getOperand(i);
6554
6555     // Check for elements which are consecutive loads.
6556     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6557       return LD;
6558
6559     // Check for a build vector from mostly shuffle plus few inserting.
6560     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6561       return Sh;
6562
6563     // For SSE 4.1, use insertps to put the high elements into the low element.
6564     if (Subtarget->hasSSE41()) {
6565       SDValue Result;
6566       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6567         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6568       else
6569         Result = DAG.getUNDEF(VT);
6570
6571       for (unsigned i = 1; i < NumElems; ++i) {
6572         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6573         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6574                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6575       }
6576       return Result;
6577     }
6578
6579     // Otherwise, expand into a number of unpckl*, start by extending each of
6580     // our (non-undef) elements to the full vector width with the element in the
6581     // bottom slot of the vector (which generates no code for SSE).
6582     for (unsigned i = 0; i < NumElems; ++i) {
6583       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6584         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6585       else
6586         V[i] = DAG.getUNDEF(VT);
6587     }
6588
6589     // Next, we iteratively mix elements, e.g. for v4f32:
6590     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6591     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6592     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6593     unsigned EltStride = NumElems >> 1;
6594     while (EltStride != 0) {
6595       for (unsigned i = 0; i < EltStride; ++i) {
6596         // If V[i+EltStride] is undef and this is the first round of mixing,
6597         // then it is safe to just drop this shuffle: V[i] is already in the
6598         // right place, the one element (since it's the first round) being
6599         // inserted as undef can be dropped.  This isn't safe for successive
6600         // rounds because they will permute elements within both vectors.
6601         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6602             EltStride == NumElems/2)
6603           continue;
6604
6605         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6606       }
6607       EltStride >>= 1;
6608     }
6609     return V[0];
6610   }
6611   return SDValue();
6612 }
6613
6614 // 256-bit AVX can use the vinsertf128 instruction
6615 // to create 256-bit vectors from two other 128-bit ones.
6616 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6617   SDLoc dl(Op);
6618   MVT ResVT = Op.getSimpleValueType();
6619
6620   assert((ResVT.is256BitVector() ||
6621           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6622
6623   SDValue V1 = Op.getOperand(0);
6624   SDValue V2 = Op.getOperand(1);
6625   unsigned NumElems = ResVT.getVectorNumElements();
6626   if (ResVT.is256BitVector())
6627     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6628
6629   if (Op.getNumOperands() == 4) {
6630     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6631                                   ResVT.getVectorNumElements()/2);
6632     SDValue V3 = Op.getOperand(2);
6633     SDValue V4 = Op.getOperand(3);
6634     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6635       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6636   }
6637   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6638 }
6639
6640 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6641                                        const X86Subtarget *Subtarget,
6642                                        SelectionDAG & DAG) {
6643   SDLoc dl(Op);
6644   MVT ResVT = Op.getSimpleValueType();
6645   unsigned NumOfOperands = Op.getNumOperands();
6646
6647   assert(isPowerOf2_32(NumOfOperands) &&
6648          "Unexpected number of operands in CONCAT_VECTORS");
6649
6650   SDValue Undef = DAG.getUNDEF(ResVT);
6651   if (NumOfOperands > 2) {
6652     // Specialize the cases when all, or all but one, of the operands are undef.
6653     unsigned NumOfDefinedOps = 0;
6654     unsigned OpIdx = 0;
6655     for (unsigned i = 0; i < NumOfOperands; i++)
6656       if (!Op.getOperand(i).isUndef()) {
6657         NumOfDefinedOps++;
6658         OpIdx = i;
6659       }
6660     if (NumOfDefinedOps == 0)
6661       return Undef;
6662     if (NumOfDefinedOps == 1) {
6663       unsigned SubVecNumElts =
6664         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6665       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6666       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6667                          Op.getOperand(OpIdx), IdxVal);
6668     }
6669
6670     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6671                                   ResVT.getVectorNumElements()/2);
6672     SmallVector<SDValue, 2> Ops;
6673     for (unsigned i = 0; i < NumOfOperands/2; i++)
6674       Ops.push_back(Op.getOperand(i));
6675     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6676     Ops.clear();
6677     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6678       Ops.push_back(Op.getOperand(i));
6679     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6680     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6681   }
6682
6683   // 2 operands
6684   SDValue V1 = Op.getOperand(0);
6685   SDValue V2 = Op.getOperand(1);
6686   unsigned NumElems = ResVT.getVectorNumElements();
6687   assert(V1.getValueType() == V2.getValueType() &&
6688          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6689          "Unexpected operands in CONCAT_VECTORS");
6690
6691   if (ResVT.getSizeInBits() >= 16)
6692     return Op; // The operation is legal with KUNPCK
6693
6694   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6695   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6696   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6697   if (IsZeroV1 && IsZeroV2)
6698     return ZeroVec;
6699
6700   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6701   if (V2.isUndef())
6702     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6703   if (IsZeroV2)
6704     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6705
6706   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6707   if (V1.isUndef())
6708     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6709
6710   if (IsZeroV1)
6711     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6712
6713   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6714   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6715 }
6716
6717 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6718                                    const X86Subtarget *Subtarget,
6719                                    SelectionDAG &DAG) {
6720   MVT VT = Op.getSimpleValueType();
6721   if (VT.getVectorElementType() == MVT::i1)
6722     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6723
6724   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6725          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6726           Op.getNumOperands() == 4)));
6727
6728   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6729   // from two other 128-bit ones.
6730
6731   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6732   return LowerAVXCONCAT_VECTORS(Op, DAG);
6733 }
6734
6735 //===----------------------------------------------------------------------===//
6736 // Vector shuffle lowering
6737 //
6738 // This is an experimental code path for lowering vector shuffles on x86. It is
6739 // designed to handle arbitrary vector shuffles and blends, gracefully
6740 // degrading performance as necessary. It works hard to recognize idiomatic
6741 // shuffles and lower them to optimal instruction patterns without leaving
6742 // a framework that allows reasonably efficient handling of all vector shuffle
6743 // patterns.
6744 //===----------------------------------------------------------------------===//
6745
6746 /// \brief Tiny helper function to identify a no-op mask.
6747 ///
6748 /// This is a somewhat boring predicate function. It checks whether the mask
6749 /// array input, which is assumed to be a single-input shuffle mask of the kind
6750 /// used by the X86 shuffle instructions (not a fully general
6751 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6752 /// in-place shuffle are 'no-op's.
6753 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6754   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6755     if (Mask[i] != -1 && Mask[i] != i)
6756       return false;
6757   return true;
6758 }
6759
6760 /// \brief Helper function to classify a mask as a single-input mask.
6761 ///
6762 /// This isn't a generic single-input test because in the vector shuffle
6763 /// lowering we canonicalize single inputs to be the first input operand. This
6764 /// means we can more quickly test for a single input by only checking whether
6765 /// an input from the second operand exists. We also assume that the size of
6766 /// mask corresponds to the size of the input vectors which isn't true in the
6767 /// fully general case.
6768 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6769   for (int M : Mask)
6770     if (M >= (int)Mask.size())
6771       return false;
6772   return true;
6773 }
6774
6775 /// \brief Test whether there are elements crossing 128-bit lanes in this
6776 /// shuffle mask.
6777 ///
6778 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6779 /// and we routinely test for these.
6780 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6781   int LaneSize = 128 / VT.getScalarSizeInBits();
6782   int Size = Mask.size();
6783   for (int i = 0; i < Size; ++i)
6784     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6785       return true;
6786   return false;
6787 }
6788
6789 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6790 ///
6791 /// This checks a shuffle mask to see if it is performing the same
6792 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6793 /// that it is also not lane-crossing. It may however involve a blend from the
6794 /// same lane of a second vector.
6795 ///
6796 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6797 /// non-trivial to compute in the face of undef lanes. The representation is
6798 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6799 /// entries from both V1 and V2 inputs to the wider mask.
6800 static bool
6801 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6802                                 SmallVectorImpl<int> &RepeatedMask) {
6803   int LaneSize = 128 / VT.getScalarSizeInBits();
6804   RepeatedMask.resize(LaneSize, -1);
6805   int Size = Mask.size();
6806   for (int i = 0; i < Size; ++i) {
6807     if (Mask[i] < 0)
6808       continue;
6809     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6810       // This entry crosses lanes, so there is no way to model this shuffle.
6811       return false;
6812
6813     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6814     if (RepeatedMask[i % LaneSize] == -1)
6815       // This is the first non-undef entry in this slot of a 128-bit lane.
6816       RepeatedMask[i % LaneSize] =
6817           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6818     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6819       // Found a mismatch with the repeated mask.
6820       return false;
6821   }
6822   return true;
6823 }
6824
6825 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6826 /// arguments.
6827 ///
6828 /// This is a fast way to test a shuffle mask against a fixed pattern:
6829 ///
6830 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6831 ///
6832 /// It returns true if the mask is exactly as wide as the argument list, and
6833 /// each element of the mask is either -1 (signifying undef) or the value given
6834 /// in the argument.
6835 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6836                                 ArrayRef<int> ExpectedMask) {
6837   if (Mask.size() != ExpectedMask.size())
6838     return false;
6839
6840   int Size = Mask.size();
6841
6842   // If the values are build vectors, we can look through them to find
6843   // equivalent inputs that make the shuffles equivalent.
6844   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6845   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6846
6847   for (int i = 0; i < Size; ++i)
6848     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6849       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6850       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6851       if (!MaskBV || !ExpectedBV ||
6852           MaskBV->getOperand(Mask[i] % Size) !=
6853               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6854         return false;
6855     }
6856
6857   return true;
6858 }
6859
6860 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6861 ///
6862 /// This helper function produces an 8-bit shuffle immediate corresponding to
6863 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6864 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6865 /// example.
6866 ///
6867 /// NB: We rely heavily on "undef" masks preserving the input lane.
6868 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6869                                           SelectionDAG &DAG) {
6870   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6871   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6872   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6873   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6874   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6875
6876   unsigned Imm = 0;
6877   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6878   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6879   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6880   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6881   return DAG.getConstant(Imm, DL, MVT::i8);
6882 }
6883
6884 /// \brief Compute whether each element of a shuffle is zeroable.
6885 ///
6886 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6887 /// Either it is an undef element in the shuffle mask, the element of the input
6888 /// referenced is undef, or the element of the input referenced is known to be
6889 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6890 /// as many lanes with this technique as possible to simplify the remaining
6891 /// shuffle.
6892 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6893                                                      SDValue V1, SDValue V2) {
6894   SmallBitVector Zeroable(Mask.size(), false);
6895
6896   while (V1.getOpcode() == ISD::BITCAST)
6897     V1 = V1->getOperand(0);
6898   while (V2.getOpcode() == ISD::BITCAST)
6899     V2 = V2->getOperand(0);
6900
6901   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6902   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6903
6904   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6905     int M = Mask[i];
6906     // Handle the easy cases.
6907     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6908       Zeroable[i] = true;
6909       continue;
6910     }
6911
6912     // If this is an index into a build_vector node (which has the same number
6913     // of elements), dig out the input value and use it.
6914     SDValue V = M < Size ? V1 : V2;
6915     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6916       continue;
6917
6918     SDValue Input = V.getOperand(M % Size);
6919     // The UNDEF opcode check really should be dead code here, but not quite
6920     // worth asserting on (it isn't invalid, just unexpected).
6921     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6922       Zeroable[i] = true;
6923   }
6924
6925   return Zeroable;
6926 }
6927
6928 // X86 has dedicated unpack instructions that can handle specific blend
6929 // operations: UNPCKH and UNPCKL.
6930 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6931                                            SDValue V1, SDValue V2,
6932                                            SelectionDAG &DAG) {
6933   int NumElts = VT.getVectorNumElements();
6934   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6935   SmallVector<int, 8> Unpckl;
6936   SmallVector<int, 8> Unpckh;
6937
6938   for (int i = 0; i < NumElts; ++i) {
6939     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6940     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6941     int HiPos = LoPos + NumEltsInLane / 2;
6942     Unpckl.push_back(LoPos);
6943     Unpckh.push_back(HiPos);
6944   }
6945
6946   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6947     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6948   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6949     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6950
6951   // Commute and try again.
6952   ShuffleVectorSDNode::commuteMask(Unpckl);
6953   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6954     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6955
6956   ShuffleVectorSDNode::commuteMask(Unpckh);
6957   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6958     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6959
6960   return SDValue();
6961 }
6962
6963 /// \brief Try to emit a bitmask instruction for a shuffle.
6964 ///
6965 /// This handles cases where we can model a blend exactly as a bitmask due to
6966 /// one of the inputs being zeroable.
6967 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6968                                            SDValue V2, ArrayRef<int> Mask,
6969                                            SelectionDAG &DAG) {
6970   MVT EltVT = VT.getVectorElementType();
6971   int NumEltBits = EltVT.getSizeInBits();
6972   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6973   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6974   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6975                                     IntEltVT);
6976   if (EltVT.isFloatingPoint()) {
6977     Zero = DAG.getBitcast(EltVT, Zero);
6978     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6979   }
6980   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6981   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6982   SDValue V;
6983   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6984     if (Zeroable[i])
6985       continue;
6986     if (Mask[i] % Size != i)
6987       return SDValue(); // Not a blend.
6988     if (!V)
6989       V = Mask[i] < Size ? V1 : V2;
6990     else if (V != (Mask[i] < Size ? V1 : V2))
6991       return SDValue(); // Can only let one input through the mask.
6992
6993     VMaskOps[i] = AllOnes;
6994   }
6995   if (!V)
6996     return SDValue(); // No non-zeroable elements!
6997
6998   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6999   V = DAG.getNode(VT.isFloatingPoint()
7000                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7001                   DL, VT, V, VMask);
7002   return V;
7003 }
7004
7005 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7006 ///
7007 /// This is used as a fallback approach when first class blend instructions are
7008 /// unavailable. Currently it is only suitable for integer vectors, but could
7009 /// be generalized for floating point vectors if desirable.
7010 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7011                                             SDValue V2, ArrayRef<int> Mask,
7012                                             SelectionDAG &DAG) {
7013   assert(VT.isInteger() && "Only supports integer vector types!");
7014   MVT EltVT = VT.getVectorElementType();
7015   int NumEltBits = EltVT.getSizeInBits();
7016   SDValue Zero = DAG.getConstant(0, DL, EltVT);
7017   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7018                                     EltVT);
7019   SmallVector<SDValue, 16> MaskOps;
7020   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7021     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7022       return SDValue(); // Shuffled input!
7023     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7024   }
7025
7026   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7027   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7028   // We have to cast V2 around.
7029   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7030   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7031                                       DAG.getBitcast(MaskVT, V1Mask),
7032                                       DAG.getBitcast(MaskVT, V2)));
7033   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7034 }
7035
7036 /// \brief Try to emit a blend instruction for a shuffle.
7037 ///
7038 /// This doesn't do any checks for the availability of instructions for blending
7039 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7040 /// be matched in the backend with the type given. What it does check for is
7041 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7042 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7043                                          SDValue V2, ArrayRef<int> Original,
7044                                          const X86Subtarget *Subtarget,
7045                                          SelectionDAG &DAG) {
7046   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7047   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7048   SmallVector<int, 8> Mask(Original.begin(), Original.end());
7049   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7050   bool ForceV1Zero = false, ForceV2Zero = false;
7051
7052   // Attempt to generate the binary blend mask. If an input is zero then
7053   // we can use any lane.
7054   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7055   unsigned BlendMask = 0;
7056   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7057     int M = Mask[i];
7058     if (M < 0)
7059       continue;
7060     if (M == i)
7061       continue;
7062     if (M == i + Size) {
7063       BlendMask |= 1u << i;
7064       continue;
7065     }
7066     if (Zeroable[i]) {
7067       if (V1IsZero) {
7068         ForceV1Zero = true;
7069         Mask[i] = i;
7070         continue;
7071       }
7072       if (V2IsZero) {
7073         ForceV2Zero = true;
7074         BlendMask |= 1u << i;
7075         Mask[i] = i + Size;
7076         continue;
7077       }
7078     }
7079     return SDValue(); // Shuffled input!
7080   }
7081
7082   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7083   if (ForceV1Zero)
7084     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7085   if (ForceV2Zero)
7086     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7087
7088   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7089     unsigned ScaledMask = 0;
7090     for (int i = 0; i != Size; ++i)
7091       if (BlendMask & (1u << i))
7092         for (int j = 0; j != Scale; ++j)
7093           ScaledMask |= 1u << (i * Scale + j);
7094     return ScaledMask;
7095   };
7096
7097   switch (VT.SimpleTy) {
7098   case MVT::v2f64:
7099   case MVT::v4f32:
7100   case MVT::v4f64:
7101   case MVT::v8f32:
7102     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7103                        DAG.getConstant(BlendMask, DL, MVT::i8));
7104
7105   case MVT::v4i64:
7106   case MVT::v8i32:
7107     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7108     // FALLTHROUGH
7109   case MVT::v2i64:
7110   case MVT::v4i32:
7111     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7112     // that instruction.
7113     if (Subtarget->hasAVX2()) {
7114       // Scale the blend by the number of 32-bit dwords per element.
7115       int Scale =  VT.getScalarSizeInBits() / 32;
7116       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7117       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7118       V1 = DAG.getBitcast(BlendVT, V1);
7119       V2 = DAG.getBitcast(BlendVT, V2);
7120       return DAG.getBitcast(
7121           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7122                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7123     }
7124     // FALLTHROUGH
7125   case MVT::v8i16: {
7126     // For integer shuffles we need to expand the mask and cast the inputs to
7127     // v8i16s prior to blending.
7128     int Scale = 8 / VT.getVectorNumElements();
7129     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7130     V1 = DAG.getBitcast(MVT::v8i16, V1);
7131     V2 = DAG.getBitcast(MVT::v8i16, V2);
7132     return DAG.getBitcast(VT,
7133                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7134                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7135   }
7136
7137   case MVT::v16i16: {
7138     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7139     SmallVector<int, 8> RepeatedMask;
7140     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7141       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7142       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7143       BlendMask = 0;
7144       for (int i = 0; i < 8; ++i)
7145         if (RepeatedMask[i] >= 16)
7146           BlendMask |= 1u << i;
7147       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7148                          DAG.getConstant(BlendMask, DL, MVT::i8));
7149     }
7150   }
7151     // FALLTHROUGH
7152   case MVT::v16i8:
7153   case MVT::v32i8: {
7154     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7155            "256-bit byte-blends require AVX2 support!");
7156
7157     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7158     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7159       return Masked;
7160
7161     // Scale the blend by the number of bytes per element.
7162     int Scale = VT.getScalarSizeInBits() / 8;
7163
7164     // This form of blend is always done on bytes. Compute the byte vector
7165     // type.
7166     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7167
7168     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7169     // mix of LLVM's code generator and the x86 backend. We tell the code
7170     // generator that boolean values in the elements of an x86 vector register
7171     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7172     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7173     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7174     // of the element (the remaining are ignored) and 0 in that high bit would
7175     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7176     // the LLVM model for boolean values in vector elements gets the relevant
7177     // bit set, it is set backwards and over constrained relative to x86's
7178     // actual model.
7179     SmallVector<SDValue, 32> VSELECTMask;
7180     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7181       for (int j = 0; j < Scale; ++j)
7182         VSELECTMask.push_back(
7183             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7184                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7185                                           MVT::i8));
7186
7187     V1 = DAG.getBitcast(BlendVT, V1);
7188     V2 = DAG.getBitcast(BlendVT, V2);
7189     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7190                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7191                                                       BlendVT, VSELECTMask),
7192                                           V1, V2));
7193   }
7194
7195   default:
7196     llvm_unreachable("Not a supported integer vector type!");
7197   }
7198 }
7199
7200 /// \brief Try to lower as a blend of elements from two inputs followed by
7201 /// a single-input permutation.
7202 ///
7203 /// This matches the pattern where we can blend elements from two inputs and
7204 /// then reduce the shuffle to a single-input permutation.
7205 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7206                                                    SDValue V2,
7207                                                    ArrayRef<int> Mask,
7208                                                    SelectionDAG &DAG) {
7209   // We build up the blend mask while checking whether a blend is a viable way
7210   // to reduce the shuffle.
7211   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7212   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7213
7214   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7215     if (Mask[i] < 0)
7216       continue;
7217
7218     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7219
7220     if (BlendMask[Mask[i] % Size] == -1)
7221       BlendMask[Mask[i] % Size] = Mask[i];
7222     else if (BlendMask[Mask[i] % Size] != Mask[i])
7223       return SDValue(); // Can't blend in the needed input!
7224
7225     PermuteMask[i] = Mask[i] % Size;
7226   }
7227
7228   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7229   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7230 }
7231
7232 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7233 /// blends and permutes.
7234 ///
7235 /// This matches the extremely common pattern for handling combined
7236 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7237 /// operations. It will try to pick the best arrangement of shuffles and
7238 /// blends.
7239 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7240                                                           SDValue V1,
7241                                                           SDValue V2,
7242                                                           ArrayRef<int> Mask,
7243                                                           SelectionDAG &DAG) {
7244   // Shuffle the input elements into the desired positions in V1 and V2 and
7245   // blend them together.
7246   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7247   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7248   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7249   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7250     if (Mask[i] >= 0 && Mask[i] < Size) {
7251       V1Mask[i] = Mask[i];
7252       BlendMask[i] = i;
7253     } else if (Mask[i] >= Size) {
7254       V2Mask[i] = Mask[i] - Size;
7255       BlendMask[i] = i + Size;
7256     }
7257
7258   // Try to lower with the simpler initial blend strategy unless one of the
7259   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7260   // shuffle may be able to fold with a load or other benefit. However, when
7261   // we'll have to do 2x as many shuffles in order to achieve this, blending
7262   // first is a better strategy.
7263   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7264     if (SDValue BlendPerm =
7265             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7266       return BlendPerm;
7267
7268   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7269   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7270   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7271 }
7272
7273 /// \brief Try to lower a vector shuffle as a byte rotation.
7274 ///
7275 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7276 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7277 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7278 /// try to generically lower a vector shuffle through such an pattern. It
7279 /// does not check for the profitability of lowering either as PALIGNR or
7280 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7281 /// This matches shuffle vectors that look like:
7282 ///
7283 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7284 ///
7285 /// Essentially it concatenates V1 and V2, shifts right by some number of
7286 /// elements, and takes the low elements as the result. Note that while this is
7287 /// specified as a *right shift* because x86 is little-endian, it is a *left
7288 /// rotate* of the vector lanes.
7289 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7290                                               SDValue V2,
7291                                               ArrayRef<int> Mask,
7292                                               const X86Subtarget *Subtarget,
7293                                               SelectionDAG &DAG) {
7294   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7295
7296   int NumElts = Mask.size();
7297   int NumLanes = VT.getSizeInBits() / 128;
7298   int NumLaneElts = NumElts / NumLanes;
7299
7300   // We need to detect various ways of spelling a rotation:
7301   //   [11, 12, 13, 14, 15,  0,  1,  2]
7302   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7303   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7304   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7305   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7306   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7307   int Rotation = 0;
7308   SDValue Lo, Hi;
7309   for (int l = 0; l < NumElts; l += NumLaneElts) {
7310     for (int i = 0; i < NumLaneElts; ++i) {
7311       if (Mask[l + i] == -1)
7312         continue;
7313       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7314
7315       // Get the mod-Size index and lane correct it.
7316       int LaneIdx = (Mask[l + i] % NumElts) - l;
7317       // Make sure it was in this lane.
7318       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7319         return SDValue();
7320
7321       // Determine where a rotated vector would have started.
7322       int StartIdx = i - LaneIdx;
7323       if (StartIdx == 0)
7324         // The identity rotation isn't interesting, stop.
7325         return SDValue();
7326
7327       // If we found the tail of a vector the rotation must be the missing
7328       // front. If we found the head of a vector, it must be how much of the
7329       // head.
7330       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7331
7332       if (Rotation == 0)
7333         Rotation = CandidateRotation;
7334       else if (Rotation != CandidateRotation)
7335         // The rotations don't match, so we can't match this mask.
7336         return SDValue();
7337
7338       // Compute which value this mask is pointing at.
7339       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7340
7341       // Compute which of the two target values this index should be assigned
7342       // to. This reflects whether the high elements are remaining or the low
7343       // elements are remaining.
7344       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7345
7346       // Either set up this value if we've not encountered it before, or check
7347       // that it remains consistent.
7348       if (!TargetV)
7349         TargetV = MaskV;
7350       else if (TargetV != MaskV)
7351         // This may be a rotation, but it pulls from the inputs in some
7352         // unsupported interleaving.
7353         return SDValue();
7354     }
7355   }
7356
7357   // Check that we successfully analyzed the mask, and normalize the results.
7358   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7359   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7360   if (!Lo)
7361     Lo = Hi;
7362   else if (!Hi)
7363     Hi = Lo;
7364
7365   // The actual rotate instruction rotates bytes, so we need to scale the
7366   // rotation based on how many bytes are in the vector lane.
7367   int Scale = 16 / NumLaneElts;
7368
7369   // SSSE3 targets can use the palignr instruction.
7370   if (Subtarget->hasSSSE3()) {
7371     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7372     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7373     Lo = DAG.getBitcast(AlignVT, Lo);
7374     Hi = DAG.getBitcast(AlignVT, Hi);
7375
7376     return DAG.getBitcast(
7377         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7378                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7379   }
7380
7381   assert(VT.is128BitVector() &&
7382          "Rotate-based lowering only supports 128-bit lowering!");
7383   assert(Mask.size() <= 16 &&
7384          "Can shuffle at most 16 bytes in a 128-bit vector!");
7385
7386   // Default SSE2 implementation
7387   int LoByteShift = 16 - Rotation * Scale;
7388   int HiByteShift = Rotation * Scale;
7389
7390   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7391   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7392   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7393
7394   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7395                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7396   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7397                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7398   return DAG.getBitcast(VT,
7399                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7400 }
7401
7402 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7403 ///
7404 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7405 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7406 /// matches elements from one of the input vectors shuffled to the left or
7407 /// right with zeroable elements 'shifted in'. It handles both the strictly
7408 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7409 /// quad word lane.
7410 ///
7411 /// PSHL : (little-endian) left bit shift.
7412 /// [ zz, 0, zz,  2 ]
7413 /// [ -1, 4, zz, -1 ]
7414 /// PSRL : (little-endian) right bit shift.
7415 /// [  1, zz,  3, zz]
7416 /// [ -1, -1,  7, zz]
7417 /// PSLLDQ : (little-endian) left byte shift
7418 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7419 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7420 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7421 /// PSRLDQ : (little-endian) right byte shift
7422 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7423 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7424 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7425 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7426                                          SDValue V2, ArrayRef<int> Mask,
7427                                          SelectionDAG &DAG) {
7428   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7429
7430   int Size = Mask.size();
7431   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7432
7433   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7434     for (int i = 0; i < Size; i += Scale)
7435       for (int j = 0; j < Shift; ++j)
7436         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7437           return false;
7438
7439     return true;
7440   };
7441
7442   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7443     for (int i = 0; i != Size; i += Scale) {
7444       unsigned Pos = Left ? i + Shift : i;
7445       unsigned Low = Left ? i : i + Shift;
7446       unsigned Len = Scale - Shift;
7447       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7448                                       Low + (V == V1 ? 0 : Size)))
7449         return SDValue();
7450     }
7451
7452     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7453     bool ByteShift = ShiftEltBits > 64;
7454     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7455                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7456     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7457
7458     // Normalize the scale for byte shifts to still produce an i64 element
7459     // type.
7460     Scale = ByteShift ? Scale / 2 : Scale;
7461
7462     // We need to round trip through the appropriate type for the shift.
7463     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7464     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7465     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7466            "Illegal integer vector type");
7467     V = DAG.getBitcast(ShiftVT, V);
7468
7469     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7470                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7471     return DAG.getBitcast(VT, V);
7472   };
7473
7474   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7475   // keep doubling the size of the integer elements up to that. We can
7476   // then shift the elements of the integer vector by whole multiples of
7477   // their width within the elements of the larger integer vector. Test each
7478   // multiple to see if we can find a match with the moved element indices
7479   // and that the shifted in elements are all zeroable.
7480   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7481     for (int Shift = 1; Shift != Scale; ++Shift)
7482       for (bool Left : {true, false})
7483         if (CheckZeros(Shift, Scale, Left))
7484           for (SDValue V : {V1, V2})
7485             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7486               return Match;
7487
7488   // no match
7489   return SDValue();
7490 }
7491
7492 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7493 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7494                                            SDValue V2, ArrayRef<int> Mask,
7495                                            SelectionDAG &DAG) {
7496   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7497   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7498
7499   int Size = Mask.size();
7500   int HalfSize = Size / 2;
7501   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7502
7503   // Upper half must be undefined.
7504   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7505     return SDValue();
7506
7507   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7508   // Remainder of lower half result is zero and upper half is all undef.
7509   auto LowerAsEXTRQ = [&]() {
7510     // Determine the extraction length from the part of the
7511     // lower half that isn't zeroable.
7512     int Len = HalfSize;
7513     for (; Len > 0; --Len)
7514       if (!Zeroable[Len - 1])
7515         break;
7516     assert(Len > 0 && "Zeroable shuffle mask");
7517
7518     // Attempt to match first Len sequential elements from the lower half.
7519     SDValue Src;
7520     int Idx = -1;
7521     for (int i = 0; i != Len; ++i) {
7522       int M = Mask[i];
7523       if (M < 0)
7524         continue;
7525       SDValue &V = (M < Size ? V1 : V2);
7526       M = M % Size;
7527
7528       // The extracted elements must start at a valid index and all mask
7529       // elements must be in the lower half.
7530       if (i > M || M >= HalfSize)
7531         return SDValue();
7532
7533       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7534         Src = V;
7535         Idx = M - i;
7536         continue;
7537       }
7538       return SDValue();
7539     }
7540
7541     if (Idx < 0)
7542       return SDValue();
7543
7544     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7545     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7546     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7547     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7548                        DAG.getConstant(BitLen, DL, MVT::i8),
7549                        DAG.getConstant(BitIdx, DL, MVT::i8));
7550   };
7551
7552   if (SDValue ExtrQ = LowerAsEXTRQ())
7553     return ExtrQ;
7554
7555   // INSERTQ: Extract lowest Len elements from lower half of second source and
7556   // insert over first source, starting at Idx.
7557   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7558   auto LowerAsInsertQ = [&]() {
7559     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7560       SDValue Base;
7561
7562       // Attempt to match first source from mask before insertion point.
7563       if (isUndefInRange(Mask, 0, Idx)) {
7564         /* EMPTY */
7565       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7566         Base = V1;
7567       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7568         Base = V2;
7569       } else {
7570         continue;
7571       }
7572
7573       // Extend the extraction length looking to match both the insertion of
7574       // the second source and the remaining elements of the first.
7575       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7576         SDValue Insert;
7577         int Len = Hi - Idx;
7578
7579         // Match insertion.
7580         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7581           Insert = V1;
7582         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7583           Insert = V2;
7584         } else {
7585           continue;
7586         }
7587
7588         // Match the remaining elements of the lower half.
7589         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7590           /* EMPTY */
7591         } else if ((!Base || (Base == V1)) &&
7592                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7593           Base = V1;
7594         } else if ((!Base || (Base == V2)) &&
7595                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7596                                               Size + Hi)) {
7597           Base = V2;
7598         } else {
7599           continue;
7600         }
7601
7602         // We may not have a base (first source) - this can safely be undefined.
7603         if (!Base)
7604           Base = DAG.getUNDEF(VT);
7605
7606         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7607         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7608         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7609                            DAG.getConstant(BitLen, DL, MVT::i8),
7610                            DAG.getConstant(BitIdx, DL, MVT::i8));
7611       }
7612     }
7613
7614     return SDValue();
7615   };
7616
7617   if (SDValue InsertQ = LowerAsInsertQ())
7618     return InsertQ;
7619
7620   return SDValue();
7621 }
7622
7623 /// \brief Lower a vector shuffle as a zero or any extension.
7624 ///
7625 /// Given a specific number of elements, element bit width, and extension
7626 /// stride, produce either a zero or any extension based on the available
7627 /// features of the subtarget. The extended elements are consecutive and
7628 /// begin and can start from an offseted element index in the input; to
7629 /// avoid excess shuffling the offset must either being in the bottom lane
7630 /// or at the start of a higher lane. All extended elements must be from
7631 /// the same lane.
7632 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7633     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7634     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7635   assert(Scale > 1 && "Need a scale to extend.");
7636   int EltBits = VT.getScalarSizeInBits();
7637   int NumElements = VT.getVectorNumElements();
7638   int NumEltsPerLane = 128 / EltBits;
7639   int OffsetLane = Offset / NumEltsPerLane;
7640   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7641          "Only 8, 16, and 32 bit elements can be extended.");
7642   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7643   assert(0 <= Offset && "Extension offset must be positive.");
7644   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7645          "Extension offset must be in the first lane or start an upper lane.");
7646
7647   // Check that an index is in same lane as the base offset.
7648   auto SafeOffset = [&](int Idx) {
7649     return OffsetLane == (Idx / NumEltsPerLane);
7650   };
7651
7652   // Shift along an input so that the offset base moves to the first element.
7653   auto ShuffleOffset = [&](SDValue V) {
7654     if (!Offset)
7655       return V;
7656
7657     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7658     for (int i = 0; i * Scale < NumElements; ++i) {
7659       int SrcIdx = i + Offset;
7660       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7661     }
7662     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7663   };
7664
7665   // Found a valid zext mask! Try various lowering strategies based on the
7666   // input type and available ISA extensions.
7667   if (Subtarget->hasSSE41()) {
7668     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7669     // PUNPCK will catch this in a later shuffle match.
7670     if (Offset && Scale == 2 && VT.is128BitVector())
7671       return SDValue();
7672     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7673                                  NumElements / Scale);
7674     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7675     return DAG.getBitcast(VT, InputV);
7676   }
7677
7678   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7679
7680   // For any extends we can cheat for larger element sizes and use shuffle
7681   // instructions that can fold with a load and/or copy.
7682   if (AnyExt && EltBits == 32) {
7683     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7684                          -1};
7685     return DAG.getBitcast(
7686         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7687                         DAG.getBitcast(MVT::v4i32, InputV),
7688                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7689   }
7690   if (AnyExt && EltBits == 16 && Scale > 2) {
7691     int PSHUFDMask[4] = {Offset / 2, -1,
7692                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7693     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7694                          DAG.getBitcast(MVT::v4i32, InputV),
7695                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7696     int PSHUFWMask[4] = {1, -1, -1, -1};
7697     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7698     return DAG.getBitcast(
7699         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7700                         DAG.getBitcast(MVT::v8i16, InputV),
7701                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7702   }
7703
7704   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7705   // to 64-bits.
7706   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7707     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7708     assert(VT.is128BitVector() && "Unexpected vector width!");
7709
7710     int LoIdx = Offset * EltBits;
7711     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7712                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7713                                          DAG.getConstant(EltBits, DL, MVT::i8),
7714                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7715
7716     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7717         !SafeOffset(Offset + 1))
7718       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7719
7720     int HiIdx = (Offset + 1) * EltBits;
7721     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7722                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7723                                          DAG.getConstant(EltBits, DL, MVT::i8),
7724                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7725     return DAG.getNode(ISD::BITCAST, DL, VT,
7726                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7727   }
7728
7729   // If this would require more than 2 unpack instructions to expand, use
7730   // pshufb when available. We can only use more than 2 unpack instructions
7731   // when zero extending i8 elements which also makes it easier to use pshufb.
7732   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7733     assert(NumElements == 16 && "Unexpected byte vector width!");
7734     SDValue PSHUFBMask[16];
7735     for (int i = 0; i < 16; ++i) {
7736       int Idx = Offset + (i / Scale);
7737       PSHUFBMask[i] = DAG.getConstant(
7738           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7739     }
7740     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7741     return DAG.getBitcast(VT,
7742                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7743                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7744                                                   MVT::v16i8, PSHUFBMask)));
7745   }
7746
7747   // If we are extending from an offset, ensure we start on a boundary that
7748   // we can unpack from.
7749   int AlignToUnpack = Offset % (NumElements / Scale);
7750   if (AlignToUnpack) {
7751     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7752     for (int i = AlignToUnpack; i < NumElements; ++i)
7753       ShMask[i - AlignToUnpack] = i;
7754     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7755     Offset -= AlignToUnpack;
7756   }
7757
7758   // Otherwise emit a sequence of unpacks.
7759   do {
7760     unsigned UnpackLoHi = X86ISD::UNPCKL;
7761     if (Offset >= (NumElements / 2)) {
7762       UnpackLoHi = X86ISD::UNPCKH;
7763       Offset -= (NumElements / 2);
7764     }
7765
7766     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7767     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7768                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7769     InputV = DAG.getBitcast(InputVT, InputV);
7770     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7771     Scale /= 2;
7772     EltBits *= 2;
7773     NumElements /= 2;
7774   } while (Scale > 1);
7775   return DAG.getBitcast(VT, InputV);
7776 }
7777
7778 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7779 ///
7780 /// This routine will try to do everything in its power to cleverly lower
7781 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7782 /// check for the profitability of this lowering,  it tries to aggressively
7783 /// match this pattern. It will use all of the micro-architectural details it
7784 /// can to emit an efficient lowering. It handles both blends with all-zero
7785 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7786 /// masking out later).
7787 ///
7788 /// The reason we have dedicated lowering for zext-style shuffles is that they
7789 /// are both incredibly common and often quite performance sensitive.
7790 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7791     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7792     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7793   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7794
7795   int Bits = VT.getSizeInBits();
7796   int NumLanes = Bits / 128;
7797   int NumElements = VT.getVectorNumElements();
7798   int NumEltsPerLane = NumElements / NumLanes;
7799   assert(VT.getScalarSizeInBits() <= 32 &&
7800          "Exceeds 32-bit integer zero extension limit");
7801   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7802
7803   // Define a helper function to check a particular ext-scale and lower to it if
7804   // valid.
7805   auto Lower = [&](int Scale) -> SDValue {
7806     SDValue InputV;
7807     bool AnyExt = true;
7808     int Offset = 0;
7809     int Matches = 0;
7810     for (int i = 0; i < NumElements; ++i) {
7811       int M = Mask[i];
7812       if (M == -1)
7813         continue; // Valid anywhere but doesn't tell us anything.
7814       if (i % Scale != 0) {
7815         // Each of the extended elements need to be zeroable.
7816         if (!Zeroable[i])
7817           return SDValue();
7818
7819         // We no longer are in the anyext case.
7820         AnyExt = false;
7821         continue;
7822       }
7823
7824       // Each of the base elements needs to be consecutive indices into the
7825       // same input vector.
7826       SDValue V = M < NumElements ? V1 : V2;
7827       M = M % NumElements;
7828       if (!InputV) {
7829         InputV = V;
7830         Offset = M - (i / Scale);
7831       } else if (InputV != V)
7832         return SDValue(); // Flip-flopping inputs.
7833
7834       // Offset must start in the lowest 128-bit lane or at the start of an
7835       // upper lane.
7836       // FIXME: Is it ever worth allowing a negative base offset?
7837       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7838             (Offset % NumEltsPerLane) == 0))
7839         return SDValue();
7840
7841       // If we are offsetting, all referenced entries must come from the same
7842       // lane.
7843       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7844         return SDValue();
7845
7846       if ((M % NumElements) != (Offset + (i / Scale)))
7847         return SDValue(); // Non-consecutive strided elements.
7848       Matches++;
7849     }
7850
7851     // If we fail to find an input, we have a zero-shuffle which should always
7852     // have already been handled.
7853     // FIXME: Maybe handle this here in case during blending we end up with one?
7854     if (!InputV)
7855       return SDValue();
7856
7857     // If we are offsetting, don't extend if we only match a single input, we
7858     // can always do better by using a basic PSHUF or PUNPCK.
7859     if (Offset != 0 && Matches < 2)
7860       return SDValue();
7861
7862     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7863         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7864   };
7865
7866   // The widest scale possible for extending is to a 64-bit integer.
7867   assert(Bits % 64 == 0 &&
7868          "The number of bits in a vector must be divisible by 64 on x86!");
7869   int NumExtElements = Bits / 64;
7870
7871   // Each iteration, try extending the elements half as much, but into twice as
7872   // many elements.
7873   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7874     assert(NumElements % NumExtElements == 0 &&
7875            "The input vector size must be divisible by the extended size.");
7876     if (SDValue V = Lower(NumElements / NumExtElements))
7877       return V;
7878   }
7879
7880   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7881   if (Bits != 128)
7882     return SDValue();
7883
7884   // Returns one of the source operands if the shuffle can be reduced to a
7885   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7886   auto CanZExtLowHalf = [&]() {
7887     for (int i = NumElements / 2; i != NumElements; ++i)
7888       if (!Zeroable[i])
7889         return SDValue();
7890     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7891       return V1;
7892     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7893       return V2;
7894     return SDValue();
7895   };
7896
7897   if (SDValue V = CanZExtLowHalf()) {
7898     V = DAG.getBitcast(MVT::v2i64, V);
7899     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7900     return DAG.getBitcast(VT, V);
7901   }
7902
7903   // No viable ext lowering found.
7904   return SDValue();
7905 }
7906
7907 /// \brief Try to get a scalar value for a specific element of a vector.
7908 ///
7909 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7910 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7911                                               SelectionDAG &DAG) {
7912   MVT VT = V.getSimpleValueType();
7913   MVT EltVT = VT.getVectorElementType();
7914   while (V.getOpcode() == ISD::BITCAST)
7915     V = V.getOperand(0);
7916   // If the bitcasts shift the element size, we can't extract an equivalent
7917   // element from it.
7918   MVT NewVT = V.getSimpleValueType();
7919   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7920     return SDValue();
7921
7922   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7923       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7924     // Ensure the scalar operand is the same size as the destination.
7925     // FIXME: Add support for scalar truncation where possible.
7926     SDValue S = V.getOperand(Idx);
7927     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7928       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7929   }
7930
7931   return SDValue();
7932 }
7933
7934 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7935 ///
7936 /// This is particularly important because the set of instructions varies
7937 /// significantly based on whether the operand is a load or not.
7938 static bool isShuffleFoldableLoad(SDValue V) {
7939   while (V.getOpcode() == ISD::BITCAST)
7940     V = V.getOperand(0);
7941
7942   return ISD::isNON_EXTLoad(V.getNode());
7943 }
7944
7945 /// \brief Try to lower insertion of a single element into a zero vector.
7946 ///
7947 /// This is a common pattern that we have especially efficient patterns to lower
7948 /// across all subtarget feature sets.
7949 static SDValue lowerVectorShuffleAsElementInsertion(
7950     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7951     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7952   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7953   MVT ExtVT = VT;
7954   MVT EltVT = VT.getVectorElementType();
7955
7956   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7957                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7958                 Mask.begin();
7959   bool IsV1Zeroable = true;
7960   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7961     if (i != V2Index && !Zeroable[i]) {
7962       IsV1Zeroable = false;
7963       break;
7964     }
7965
7966   // Check for a single input from a SCALAR_TO_VECTOR node.
7967   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7968   // all the smarts here sunk into that routine. However, the current
7969   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7970   // vector shuffle lowering is dead.
7971   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7972                                                DAG);
7973   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7974     // We need to zext the scalar if it is smaller than an i32.
7975     V2S = DAG.getBitcast(EltVT, V2S);
7976     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7977       // Using zext to expand a narrow element won't work for non-zero
7978       // insertions.
7979       if (!IsV1Zeroable)
7980         return SDValue();
7981
7982       // Zero-extend directly to i32.
7983       ExtVT = MVT::v4i32;
7984       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7985     }
7986     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7987   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7988              EltVT == MVT::i16) {
7989     // Either not inserting from the low element of the input or the input
7990     // element size is too small to use VZEXT_MOVL to clear the high bits.
7991     return SDValue();
7992   }
7993
7994   if (!IsV1Zeroable) {
7995     // If V1 can't be treated as a zero vector we have fewer options to lower
7996     // this. We can't support integer vectors or non-zero targets cheaply, and
7997     // the V1 elements can't be permuted in any way.
7998     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7999     if (!VT.isFloatingPoint() || V2Index != 0)
8000       return SDValue();
8001     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8002     V1Mask[V2Index] = -1;
8003     if (!isNoopShuffleMask(V1Mask))
8004       return SDValue();
8005     // This is essentially a special case blend operation, but if we have
8006     // general purpose blend operations, they are always faster. Bail and let
8007     // the rest of the lowering handle these as blends.
8008     if (Subtarget->hasSSE41())
8009       return SDValue();
8010
8011     // Otherwise, use MOVSD or MOVSS.
8012     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8013            "Only two types of floating point element types to handle!");
8014     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8015                        ExtVT, V1, V2);
8016   }
8017
8018   // This lowering only works for the low element with floating point vectors.
8019   if (VT.isFloatingPoint() && V2Index != 0)
8020     return SDValue();
8021
8022   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8023   if (ExtVT != VT)
8024     V2 = DAG.getBitcast(VT, V2);
8025
8026   if (V2Index != 0) {
8027     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8028     // the desired position. Otherwise it is more efficient to do a vector
8029     // shift left. We know that we can do a vector shift left because all
8030     // the inputs are zero.
8031     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8032       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8033       V2Shuffle[V2Index] = 0;
8034       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8035     } else {
8036       V2 = DAG.getBitcast(MVT::v2i64, V2);
8037       V2 = DAG.getNode(
8038           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8039           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8040                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8041                               DAG.getDataLayout(), VT)));
8042       V2 = DAG.getBitcast(VT, V2);
8043     }
8044   }
8045   return V2;
8046 }
8047
8048 /// \brief Try to lower broadcast of a single - truncated - integer element,
8049 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8050 ///
8051 /// This assumes we have AVX2.
8052 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8053                                                   int BroadcastIdx,
8054                                                   const X86Subtarget *Subtarget,
8055                                                   SelectionDAG &DAG) {
8056   assert(Subtarget->hasAVX2() &&
8057          "We can only lower integer broadcasts with AVX2!");
8058
8059   EVT EltVT = VT.getVectorElementType();
8060   EVT V0VT = V0.getValueType();
8061
8062   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8063   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8064
8065   EVT V0EltVT = V0VT.getVectorElementType();
8066   if (!V0EltVT.isInteger())
8067     return SDValue();
8068
8069   const unsigned EltSize = EltVT.getSizeInBits();
8070   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8071
8072   // This is only a truncation if the original element type is larger.
8073   if (V0EltSize <= EltSize)
8074     return SDValue();
8075
8076   assert(((V0EltSize % EltSize) == 0) &&
8077          "Scalar type sizes must all be powers of 2 on x86!");
8078
8079   const unsigned V0Opc = V0.getOpcode();
8080   const unsigned Scale = V0EltSize / EltSize;
8081   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8082
8083   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8084       V0Opc != ISD::BUILD_VECTOR)
8085     return SDValue();
8086
8087   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8088
8089   // If we're extracting non-least-significant bits, shift so we can truncate.
8090   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8091   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8092   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8093   if (const int OffsetIdx = BroadcastIdx % Scale)
8094     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8095             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8096
8097   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8098                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8099 }
8100
8101 /// \brief Try to lower broadcast of a single element.
8102 ///
8103 /// For convenience, this code also bundles all of the subtarget feature set
8104 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8105 /// a convenient way to factor it out.
8106 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8107 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8108                                              ArrayRef<int> Mask,
8109                                              const X86Subtarget *Subtarget,
8110                                              SelectionDAG &DAG) {
8111   if (!Subtarget->hasAVX())
8112     return SDValue();
8113   if (VT.isInteger() && !Subtarget->hasAVX2())
8114     return SDValue();
8115
8116   // Check that the mask is a broadcast.
8117   int BroadcastIdx = -1;
8118   for (int M : Mask)
8119     if (M >= 0 && BroadcastIdx == -1)
8120       BroadcastIdx = M;
8121     else if (M >= 0 && M != BroadcastIdx)
8122       return SDValue();
8123
8124   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8125                                             "a sorted mask where the broadcast "
8126                                             "comes from V1.");
8127
8128   // Go up the chain of (vector) values to find a scalar load that we can
8129   // combine with the broadcast.
8130   for (;;) {
8131     switch (V.getOpcode()) {
8132     case ISD::CONCAT_VECTORS: {
8133       int OperandSize = Mask.size() / V.getNumOperands();
8134       V = V.getOperand(BroadcastIdx / OperandSize);
8135       BroadcastIdx %= OperandSize;
8136       continue;
8137     }
8138
8139     case ISD::INSERT_SUBVECTOR: {
8140       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8141       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8142       if (!ConstantIdx)
8143         break;
8144
8145       int BeginIdx = (int)ConstantIdx->getZExtValue();
8146       int EndIdx =
8147           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8148       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8149         BroadcastIdx -= BeginIdx;
8150         V = VInner;
8151       } else {
8152         V = VOuter;
8153       }
8154       continue;
8155     }
8156     }
8157     break;
8158   }
8159
8160   // Check if this is a broadcast of a scalar. We special case lowering
8161   // for scalars so that we can more effectively fold with loads.
8162   // First, look through bitcast: if the original value has a larger element
8163   // type than the shuffle, the broadcast element is in essence truncated.
8164   // Make that explicit to ease folding.
8165   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8166     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8167             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8168       return TruncBroadcast;
8169
8170   // Also check the simpler case, where we can directly reuse the scalar.
8171   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8172       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8173     V = V.getOperand(BroadcastIdx);
8174
8175     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8176     // Only AVX2 has register broadcasts.
8177     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8178       return SDValue();
8179   } else if (MayFoldLoad(V) && !cast<LoadSDNode>(V)->isVolatile()) {
8180     // If we are broadcasting a load that is only used by the shuffle
8181     // then we can reduce the vector load to the broadcasted scalar load.
8182     LoadSDNode *Ld = cast<LoadSDNode>(V);
8183     SDValue BaseAddr = Ld->getOperand(1);
8184     EVT AddrVT = BaseAddr.getValueType();
8185     EVT SVT = VT.getScalarType();
8186     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8187     SDValue NewAddr = DAG.getNode(
8188         ISD::ADD, DL, AddrVT, BaseAddr,
8189         DAG.getConstant(Offset, DL, AddrVT));
8190     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8191                     DAG.getMachineFunction().getMachineMemOperand(
8192                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8193   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8194     // We can't broadcast from a vector register without AVX2, and we can only
8195     // broadcast from the zero-element of a vector register.
8196     return SDValue();
8197   }
8198
8199   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8200 }
8201
8202 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8203 // INSERTPS when the V1 elements are already in the correct locations
8204 // because otherwise we can just always use two SHUFPS instructions which
8205 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8206 // perform INSERTPS if a single V1 element is out of place and all V2
8207 // elements are zeroable.
8208 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8209                                             ArrayRef<int> Mask,
8210                                             SelectionDAG &DAG) {
8211   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8212   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8213   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8214   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8215
8216   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8217
8218   unsigned ZMask = 0;
8219   int V1DstIndex = -1;
8220   int V2DstIndex = -1;
8221   bool V1UsedInPlace = false;
8222
8223   for (int i = 0; i < 4; ++i) {
8224     // Synthesize a zero mask from the zeroable elements (includes undefs).
8225     if (Zeroable[i]) {
8226       ZMask |= 1 << i;
8227       continue;
8228     }
8229
8230     // Flag if we use any V1 inputs in place.
8231     if (i == Mask[i]) {
8232       V1UsedInPlace = true;
8233       continue;
8234     }
8235
8236     // We can only insert a single non-zeroable element.
8237     if (V1DstIndex != -1 || V2DstIndex != -1)
8238       return SDValue();
8239
8240     if (Mask[i] < 4) {
8241       // V1 input out of place for insertion.
8242       V1DstIndex = i;
8243     } else {
8244       // V2 input for insertion.
8245       V2DstIndex = i;
8246     }
8247   }
8248
8249   // Don't bother if we have no (non-zeroable) element for insertion.
8250   if (V1DstIndex == -1 && V2DstIndex == -1)
8251     return SDValue();
8252
8253   // Determine element insertion src/dst indices. The src index is from the
8254   // start of the inserted vector, not the start of the concatenated vector.
8255   unsigned V2SrcIndex = 0;
8256   if (V1DstIndex != -1) {
8257     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8258     // and don't use the original V2 at all.
8259     V2SrcIndex = Mask[V1DstIndex];
8260     V2DstIndex = V1DstIndex;
8261     V2 = V1;
8262   } else {
8263     V2SrcIndex = Mask[V2DstIndex] - 4;
8264   }
8265
8266   // If no V1 inputs are used in place, then the result is created only from
8267   // the zero mask and the V2 insertion - so remove V1 dependency.
8268   if (!V1UsedInPlace)
8269     V1 = DAG.getUNDEF(MVT::v4f32);
8270
8271   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8272   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8273
8274   // Insert the V2 element into the desired position.
8275   SDLoc DL(Op);
8276   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8277                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8278 }
8279
8280 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8281 /// UNPCK instruction.
8282 ///
8283 /// This specifically targets cases where we end up with alternating between
8284 /// the two inputs, and so can permute them into something that feeds a single
8285 /// UNPCK instruction. Note that this routine only targets integer vectors
8286 /// because for floating point vectors we have a generalized SHUFPS lowering
8287 /// strategy that handles everything that doesn't *exactly* match an unpack,
8288 /// making this clever lowering unnecessary.
8289 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8290                                                     SDValue V1, SDValue V2,
8291                                                     ArrayRef<int> Mask,
8292                                                     SelectionDAG &DAG) {
8293   assert(!VT.isFloatingPoint() &&
8294          "This routine only supports integer vectors.");
8295   assert(!isSingleInputShuffleMask(Mask) &&
8296          "This routine should only be used when blending two inputs.");
8297   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8298
8299   int Size = Mask.size();
8300
8301   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8302     return M >= 0 && M % Size < Size / 2;
8303   });
8304   int NumHiInputs = std::count_if(
8305       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8306
8307   bool UnpackLo = NumLoInputs >= NumHiInputs;
8308
8309   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8310     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8311     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8312
8313     for (int i = 0; i < Size; ++i) {
8314       if (Mask[i] < 0)
8315         continue;
8316
8317       // Each element of the unpack contains Scale elements from this mask.
8318       int UnpackIdx = i / Scale;
8319
8320       // We only handle the case where V1 feeds the first slots of the unpack.
8321       // We rely on canonicalization to ensure this is the case.
8322       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8323         return SDValue();
8324
8325       // Setup the mask for this input. The indexing is tricky as we have to
8326       // handle the unpack stride.
8327       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8328       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8329           Mask[i] % Size;
8330     }
8331
8332     // If we will have to shuffle both inputs to use the unpack, check whether
8333     // we can just unpack first and shuffle the result. If so, skip this unpack.
8334     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8335         !isNoopShuffleMask(V2Mask))
8336       return SDValue();
8337
8338     // Shuffle the inputs into place.
8339     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8340     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8341
8342     // Cast the inputs to the type we will use to unpack them.
8343     V1 = DAG.getBitcast(UnpackVT, V1);
8344     V2 = DAG.getBitcast(UnpackVT, V2);
8345
8346     // Unpack the inputs and cast the result back to the desired type.
8347     return DAG.getBitcast(
8348         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8349                         UnpackVT, V1, V2));
8350   };
8351
8352   // We try each unpack from the largest to the smallest to try and find one
8353   // that fits this mask.
8354   int OrigNumElements = VT.getVectorNumElements();
8355   int OrigScalarSize = VT.getScalarSizeInBits();
8356   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8357     int Scale = ScalarSize / OrigScalarSize;
8358     int NumElements = OrigNumElements / Scale;
8359     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8360     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8361       return Unpack;
8362   }
8363
8364   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8365   // initial unpack.
8366   if (NumLoInputs == 0 || NumHiInputs == 0) {
8367     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8368            "We have to have *some* inputs!");
8369     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8370
8371     // FIXME: We could consider the total complexity of the permute of each
8372     // possible unpacking. Or at the least we should consider how many
8373     // half-crossings are created.
8374     // FIXME: We could consider commuting the unpacks.
8375
8376     SmallVector<int, 32> PermMask;
8377     PermMask.assign(Size, -1);
8378     for (int i = 0; i < Size; ++i) {
8379       if (Mask[i] < 0)
8380         continue;
8381
8382       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8383
8384       PermMask[i] =
8385           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8386     }
8387     return DAG.getVectorShuffle(
8388         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8389                             DL, VT, V1, V2),
8390         DAG.getUNDEF(VT), PermMask);
8391   }
8392
8393   return SDValue();
8394 }
8395
8396 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8397 ///
8398 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8399 /// support for floating point shuffles but not integer shuffles. These
8400 /// instructions will incur a domain crossing penalty on some chips though so
8401 /// it is better to avoid lowering through this for integer vectors where
8402 /// possible.
8403 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8404                                        const X86Subtarget *Subtarget,
8405                                        SelectionDAG &DAG) {
8406   SDLoc DL(Op);
8407   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8408   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8409   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8410   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8411   ArrayRef<int> Mask = SVOp->getMask();
8412   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8413
8414   if (isSingleInputShuffleMask(Mask)) {
8415     // Use low duplicate instructions for masks that match their pattern.
8416     if (Subtarget->hasSSE3())
8417       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8418         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8419
8420     // Straight shuffle of a single input vector. Simulate this by using the
8421     // single input as both of the "inputs" to this instruction..
8422     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8423
8424     if (Subtarget->hasAVX()) {
8425       // If we have AVX, we can use VPERMILPS which will allow folding a load
8426       // into the shuffle.
8427       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8428                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8429     }
8430
8431     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8432                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8433   }
8434   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8435   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8436
8437   // If we have a single input, insert that into V1 if we can do so cheaply.
8438   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8439     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8440             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8441       return Insertion;
8442     // Try inverting the insertion since for v2 masks it is easy to do and we
8443     // can't reliably sort the mask one way or the other.
8444     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8445                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8446     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8447             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8448       return Insertion;
8449   }
8450
8451   // Try to use one of the special instruction patterns to handle two common
8452   // blend patterns if a zero-blend above didn't work.
8453   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8454       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8455     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8456       // We can either use a special instruction to load over the low double or
8457       // to move just the low double.
8458       return DAG.getNode(
8459           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8460           DL, MVT::v2f64, V2,
8461           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8462
8463   if (Subtarget->hasSSE41())
8464     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8465                                                   Subtarget, DAG))
8466       return Blend;
8467
8468   // Use dedicated unpack instructions for masks that match their pattern.
8469   if (SDValue V =
8470           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8471     return V;
8472
8473   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8474   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8475                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8476 }
8477
8478 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8479 ///
8480 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8481 /// the integer unit to minimize domain crossing penalties. However, for blends
8482 /// it falls back to the floating point shuffle operation with appropriate bit
8483 /// casting.
8484 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8485                                        const X86Subtarget *Subtarget,
8486                                        SelectionDAG &DAG) {
8487   SDLoc DL(Op);
8488   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8489   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8490   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8491   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8492   ArrayRef<int> Mask = SVOp->getMask();
8493   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8494
8495   if (isSingleInputShuffleMask(Mask)) {
8496     // Check for being able to broadcast a single element.
8497     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8498                                                           Mask, Subtarget, DAG))
8499       return Broadcast;
8500
8501     // Straight shuffle of a single input vector. For everything from SSE2
8502     // onward this has a single fast instruction with no scary immediates.
8503     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8504     V1 = DAG.getBitcast(MVT::v4i32, V1);
8505     int WidenedMask[4] = {
8506         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8507         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8508     return DAG.getBitcast(
8509         MVT::v2i64,
8510         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8511                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8512   }
8513   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8514   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8515   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8516   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8517
8518   // If we have a blend of two PACKUS operations an the blend aligns with the
8519   // low and half halves, we can just merge the PACKUS operations. This is
8520   // particularly important as it lets us merge shuffles that this routine itself
8521   // creates.
8522   auto GetPackNode = [](SDValue V) {
8523     while (V.getOpcode() == ISD::BITCAST)
8524       V = V.getOperand(0);
8525
8526     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8527   };
8528   if (SDValue V1Pack = GetPackNode(V1))
8529     if (SDValue V2Pack = GetPackNode(V2))
8530       return DAG.getBitcast(MVT::v2i64,
8531                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8532                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8533                                                      : V1Pack.getOperand(1),
8534                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8535                                                      : V2Pack.getOperand(1)));
8536
8537   // Try to use shift instructions.
8538   if (SDValue Shift =
8539           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8540     return Shift;
8541
8542   // When loading a scalar and then shuffling it into a vector we can often do
8543   // the insertion cheaply.
8544   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8545           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8546     return Insertion;
8547   // Try inverting the insertion since for v2 masks it is easy to do and we
8548   // can't reliably sort the mask one way or the other.
8549   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8550   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8551           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8552     return Insertion;
8553
8554   // We have different paths for blend lowering, but they all must use the
8555   // *exact* same predicate.
8556   bool IsBlendSupported = Subtarget->hasSSE41();
8557   if (IsBlendSupported)
8558     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8559                                                   Subtarget, DAG))
8560       return Blend;
8561
8562   // Use dedicated unpack instructions for masks that match their pattern.
8563   if (SDValue V =
8564           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8565     return V;
8566
8567   // Try to use byte rotation instructions.
8568   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8569   if (Subtarget->hasSSSE3())
8570     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8571             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8572       return Rotate;
8573
8574   // If we have direct support for blends, we should lower by decomposing into
8575   // a permute. That will be faster than the domain cross.
8576   if (IsBlendSupported)
8577     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8578                                                       Mask, DAG);
8579
8580   // We implement this with SHUFPD which is pretty lame because it will likely
8581   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8582   // However, all the alternatives are still more cycles and newer chips don't
8583   // have this problem. It would be really nice if x86 had better shuffles here.
8584   V1 = DAG.getBitcast(MVT::v2f64, V1);
8585   V2 = DAG.getBitcast(MVT::v2f64, V2);
8586   return DAG.getBitcast(MVT::v2i64,
8587                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8588 }
8589
8590 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8591 ///
8592 /// This is used to disable more specialized lowerings when the shufps lowering
8593 /// will happen to be efficient.
8594 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8595   // This routine only handles 128-bit shufps.
8596   assert(Mask.size() == 4 && "Unsupported mask size!");
8597
8598   // To lower with a single SHUFPS we need to have the low half and high half
8599   // each requiring a single input.
8600   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8601     return false;
8602   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8603     return false;
8604
8605   return true;
8606 }
8607
8608 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8609 ///
8610 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8611 /// It makes no assumptions about whether this is the *best* lowering, it simply
8612 /// uses it.
8613 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8614                                             ArrayRef<int> Mask, SDValue V1,
8615                                             SDValue V2, SelectionDAG &DAG) {
8616   SDValue LowV = V1, HighV = V2;
8617   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8618
8619   int NumV2Elements =
8620       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8621
8622   if (NumV2Elements == 1) {
8623     int V2Index =
8624         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8625         Mask.begin();
8626
8627     // Compute the index adjacent to V2Index and in the same half by toggling
8628     // the low bit.
8629     int V2AdjIndex = V2Index ^ 1;
8630
8631     if (Mask[V2AdjIndex] == -1) {
8632       // Handles all the cases where we have a single V2 element and an undef.
8633       // This will only ever happen in the high lanes because we commute the
8634       // vector otherwise.
8635       if (V2Index < 2)
8636         std::swap(LowV, HighV);
8637       NewMask[V2Index] -= 4;
8638     } else {
8639       // Handle the case where the V2 element ends up adjacent to a V1 element.
8640       // To make this work, blend them together as the first step.
8641       int V1Index = V2AdjIndex;
8642       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8643       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8644                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8645
8646       // Now proceed to reconstruct the final blend as we have the necessary
8647       // high or low half formed.
8648       if (V2Index < 2) {
8649         LowV = V2;
8650         HighV = V1;
8651       } else {
8652         HighV = V2;
8653       }
8654       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8655       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8656     }
8657   } else if (NumV2Elements == 2) {
8658     if (Mask[0] < 4 && Mask[1] < 4) {
8659       // Handle the easy case where we have V1 in the low lanes and V2 in the
8660       // high lanes.
8661       NewMask[2] -= 4;
8662       NewMask[3] -= 4;
8663     } else if (Mask[2] < 4 && Mask[3] < 4) {
8664       // We also handle the reversed case because this utility may get called
8665       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8666       // arrange things in the right direction.
8667       NewMask[0] -= 4;
8668       NewMask[1] -= 4;
8669       HighV = V1;
8670       LowV = V2;
8671     } else {
8672       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8673       // trying to place elements directly, just blend them and set up the final
8674       // shuffle to place them.
8675
8676       // The first two blend mask elements are for V1, the second two are for
8677       // V2.
8678       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8679                           Mask[2] < 4 ? Mask[2] : Mask[3],
8680                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8681                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8682       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8683                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8684
8685       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8686       // a blend.
8687       LowV = HighV = V1;
8688       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8689       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8690       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8691       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8692     }
8693   }
8694   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8695                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8696 }
8697
8698 /// \brief Lower 4-lane 32-bit floating point shuffles.
8699 ///
8700 /// Uses instructions exclusively from the floating point unit to minimize
8701 /// domain crossing penalties, as these are sufficient to implement all v4f32
8702 /// shuffles.
8703 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8704                                        const X86Subtarget *Subtarget,
8705                                        SelectionDAG &DAG) {
8706   SDLoc DL(Op);
8707   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8708   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8709   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8710   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8711   ArrayRef<int> Mask = SVOp->getMask();
8712   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8713
8714   int NumV2Elements =
8715       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8716
8717   if (NumV2Elements == 0) {
8718     // Check for being able to broadcast a single element.
8719     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8720                                                           Mask, Subtarget, DAG))
8721       return Broadcast;
8722
8723     // Use even/odd duplicate instructions for masks that match their pattern.
8724     if (Subtarget->hasSSE3()) {
8725       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8726         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8727       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8728         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8729     }
8730
8731     if (Subtarget->hasAVX()) {
8732       // If we have AVX, we can use VPERMILPS which will allow folding a load
8733       // into the shuffle.
8734       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8735                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8736     }
8737
8738     // Otherwise, use a straight shuffle of a single input vector. We pass the
8739     // input vector to both operands to simulate this with a SHUFPS.
8740     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8741                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8742   }
8743
8744   // There are special ways we can lower some single-element blends. However, we
8745   // have custom ways we can lower more complex single-element blends below that
8746   // we defer to if both this and BLENDPS fail to match, so restrict this to
8747   // when the V2 input is targeting element 0 of the mask -- that is the fast
8748   // case here.
8749   if (NumV2Elements == 1 && Mask[0] >= 4)
8750     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8751                                                          Mask, Subtarget, DAG))
8752       return V;
8753
8754   if (Subtarget->hasSSE41()) {
8755     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8756                                                   Subtarget, DAG))
8757       return Blend;
8758
8759     // Use INSERTPS if we can complete the shuffle efficiently.
8760     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8761       return V;
8762
8763     if (!isSingleSHUFPSMask(Mask))
8764       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8765               DL, MVT::v4f32, V1, V2, Mask, DAG))
8766         return BlendPerm;
8767   }
8768
8769   // Use dedicated unpack instructions for masks that match their pattern.
8770   if (SDValue V =
8771           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8772     return V;
8773
8774   // Otherwise fall back to a SHUFPS lowering strategy.
8775   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8776 }
8777
8778 /// \brief Lower 4-lane i32 vector shuffles.
8779 ///
8780 /// We try to handle these with integer-domain shuffles where we can, but for
8781 /// blends we use the floating point domain blend instructions.
8782 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8783                                        const X86Subtarget *Subtarget,
8784                                        SelectionDAG &DAG) {
8785   SDLoc DL(Op);
8786   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8787   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8788   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8789   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8790   ArrayRef<int> Mask = SVOp->getMask();
8791   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8792
8793   // Whenever we can lower this as a zext, that instruction is strictly faster
8794   // than any alternative. It also allows us to fold memory operands into the
8795   // shuffle in many cases.
8796   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8797                                                          Mask, Subtarget, DAG))
8798     return ZExt;
8799
8800   int NumV2Elements =
8801       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8802
8803   if (NumV2Elements == 0) {
8804     // Check for being able to broadcast a single element.
8805     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8806                                                           Mask, Subtarget, DAG))
8807       return Broadcast;
8808
8809     // Straight shuffle of a single input vector. For everything from SSE2
8810     // onward this has a single fast instruction with no scary immediates.
8811     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8812     // but we aren't actually going to use the UNPCK instruction because doing
8813     // so prevents folding a load into this instruction or making a copy.
8814     const int UnpackLoMask[] = {0, 0, 1, 1};
8815     const int UnpackHiMask[] = {2, 2, 3, 3};
8816     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8817       Mask = UnpackLoMask;
8818     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8819       Mask = UnpackHiMask;
8820
8821     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8822                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8823   }
8824
8825   // Try to use shift instructions.
8826   if (SDValue Shift =
8827           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8828     return Shift;
8829
8830   // There are special ways we can lower some single-element blends.
8831   if (NumV2Elements == 1)
8832     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8833                                                          Mask, Subtarget, DAG))
8834       return V;
8835
8836   // We have different paths for blend lowering, but they all must use the
8837   // *exact* same predicate.
8838   bool IsBlendSupported = Subtarget->hasSSE41();
8839   if (IsBlendSupported)
8840     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8841                                                   Subtarget, DAG))
8842       return Blend;
8843
8844   if (SDValue Masked =
8845           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8846     return Masked;
8847
8848   // Use dedicated unpack instructions for masks that match their pattern.
8849   if (SDValue V =
8850           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8851     return V;
8852
8853   // Try to use byte rotation instructions.
8854   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8855   if (Subtarget->hasSSSE3())
8856     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8857             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8858       return Rotate;
8859
8860   // If we have direct support for blends, we should lower by decomposing into
8861   // a permute. That will be faster than the domain cross.
8862   if (IsBlendSupported)
8863     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8864                                                       Mask, DAG);
8865
8866   // Try to lower by permuting the inputs into an unpack instruction.
8867   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8868                                                             V2, Mask, DAG))
8869     return Unpack;
8870
8871   // We implement this with SHUFPS because it can blend from two vectors.
8872   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8873   // up the inputs, bypassing domain shift penalties that we would encur if we
8874   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8875   // relevant.
8876   return DAG.getBitcast(
8877       MVT::v4i32,
8878       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8879                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8880 }
8881
8882 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8883 /// shuffle lowering, and the most complex part.
8884 ///
8885 /// The lowering strategy is to try to form pairs of input lanes which are
8886 /// targeted at the same half of the final vector, and then use a dword shuffle
8887 /// to place them onto the right half, and finally unpack the paired lanes into
8888 /// their final position.
8889 ///
8890 /// The exact breakdown of how to form these dword pairs and align them on the
8891 /// correct sides is really tricky. See the comments within the function for
8892 /// more of the details.
8893 ///
8894 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8895 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8896 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8897 /// vector, form the analogous 128-bit 8-element Mask.
8898 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8899     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8900     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8901   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8902   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8903
8904   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8905   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8906   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8907
8908   SmallVector<int, 4> LoInputs;
8909   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8910                [](int M) { return M >= 0; });
8911   std::sort(LoInputs.begin(), LoInputs.end());
8912   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8913   SmallVector<int, 4> HiInputs;
8914   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8915                [](int M) { return M >= 0; });
8916   std::sort(HiInputs.begin(), HiInputs.end());
8917   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8918   int NumLToL =
8919       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8920   int NumHToL = LoInputs.size() - NumLToL;
8921   int NumLToH =
8922       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8923   int NumHToH = HiInputs.size() - NumLToH;
8924   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8925   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8926   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8927   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8928
8929   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8930   // such inputs we can swap two of the dwords across the half mark and end up
8931   // with <=2 inputs to each half in each half. Once there, we can fall through
8932   // to the generic code below. For example:
8933   //
8934   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8935   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8936   //
8937   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8938   // and an existing 2-into-2 on the other half. In this case we may have to
8939   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8940   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8941   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8942   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8943   // half than the one we target for fixing) will be fixed when we re-enter this
8944   // path. We will also combine away any sequence of PSHUFD instructions that
8945   // result into a single instruction. Here is an example of the tricky case:
8946   //
8947   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8948   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8949   //
8950   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8951   //
8952   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8953   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8954   //
8955   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8956   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8957   //
8958   // The result is fine to be handled by the generic logic.
8959   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8960                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8961                           int AOffset, int BOffset) {
8962     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8963            "Must call this with A having 3 or 1 inputs from the A half.");
8964     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8965            "Must call this with B having 1 or 3 inputs from the B half.");
8966     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8967            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8968
8969     bool ThreeAInputs = AToAInputs.size() == 3;
8970
8971     // Compute the index of dword with only one word among the three inputs in
8972     // a half by taking the sum of the half with three inputs and subtracting
8973     // the sum of the actual three inputs. The difference is the remaining
8974     // slot.
8975     int ADWord, BDWord;
8976     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8977     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8978     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8979     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8980     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8981     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8982     int TripleNonInputIdx =
8983         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8984     TripleDWord = TripleNonInputIdx / 2;
8985
8986     // We use xor with one to compute the adjacent DWord to whichever one the
8987     // OneInput is in.
8988     OneInputDWord = (OneInput / 2) ^ 1;
8989
8990     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8991     // and BToA inputs. If there is also such a problem with the BToB and AToB
8992     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8993     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8994     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8995     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8996       // Compute how many inputs will be flipped by swapping these DWords. We
8997       // need
8998       // to balance this to ensure we don't form a 3-1 shuffle in the other
8999       // half.
9000       int NumFlippedAToBInputs =
9001           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9002           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9003       int NumFlippedBToBInputs =
9004           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9005           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9006       if ((NumFlippedAToBInputs == 1 &&
9007            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9008           (NumFlippedBToBInputs == 1 &&
9009            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9010         // We choose whether to fix the A half or B half based on whether that
9011         // half has zero flipped inputs. At zero, we may not be able to fix it
9012         // with that half. We also bias towards fixing the B half because that
9013         // will more commonly be the high half, and we have to bias one way.
9014         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9015                                                        ArrayRef<int> Inputs) {
9016           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9017           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9018                                          PinnedIdx ^ 1) != Inputs.end();
9019           // Determine whether the free index is in the flipped dword or the
9020           // unflipped dword based on where the pinned index is. We use this bit
9021           // in an xor to conditionally select the adjacent dword.
9022           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9023           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9024                                              FixFreeIdx) != Inputs.end();
9025           if (IsFixIdxInput == IsFixFreeIdxInput)
9026             FixFreeIdx += 1;
9027           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9028                                         FixFreeIdx) != Inputs.end();
9029           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9030                  "We need to be changing the number of flipped inputs!");
9031           int PSHUFHalfMask[] = {0, 1, 2, 3};
9032           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9033           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9034                           MVT::v8i16, V,
9035                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9036
9037           for (int &M : Mask)
9038             if (M != -1 && M == FixIdx)
9039               M = FixFreeIdx;
9040             else if (M != -1 && M == FixFreeIdx)
9041               M = FixIdx;
9042         };
9043         if (NumFlippedBToBInputs != 0) {
9044           int BPinnedIdx =
9045               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9046           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9047         } else {
9048           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9049           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9050           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9051         }
9052       }
9053     }
9054
9055     int PSHUFDMask[] = {0, 1, 2, 3};
9056     PSHUFDMask[ADWord] = BDWord;
9057     PSHUFDMask[BDWord] = ADWord;
9058     V = DAG.getBitcast(
9059         VT,
9060         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9061                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9062
9063     // Adjust the mask to match the new locations of A and B.
9064     for (int &M : Mask)
9065       if (M != -1 && M/2 == ADWord)
9066         M = 2 * BDWord + M % 2;
9067       else if (M != -1 && M/2 == BDWord)
9068         M = 2 * ADWord + M % 2;
9069
9070     // Recurse back into this routine to re-compute state now that this isn't
9071     // a 3 and 1 problem.
9072     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9073                                                      DAG);
9074   };
9075   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9076     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9077   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9078     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9079
9080   // At this point there are at most two inputs to the low and high halves from
9081   // each half. That means the inputs can always be grouped into dwords and
9082   // those dwords can then be moved to the correct half with a dword shuffle.
9083   // We use at most one low and one high word shuffle to collect these paired
9084   // inputs into dwords, and finally a dword shuffle to place them.
9085   int PSHUFLMask[4] = {-1, -1, -1, -1};
9086   int PSHUFHMask[4] = {-1, -1, -1, -1};
9087   int PSHUFDMask[4] = {-1, -1, -1, -1};
9088
9089   // First fix the masks for all the inputs that are staying in their
9090   // original halves. This will then dictate the targets of the cross-half
9091   // shuffles.
9092   auto fixInPlaceInputs =
9093       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9094                     MutableArrayRef<int> SourceHalfMask,
9095                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9096     if (InPlaceInputs.empty())
9097       return;
9098     if (InPlaceInputs.size() == 1) {
9099       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9100           InPlaceInputs[0] - HalfOffset;
9101       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9102       return;
9103     }
9104     if (IncomingInputs.empty()) {
9105       // Just fix all of the in place inputs.
9106       for (int Input : InPlaceInputs) {
9107         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9108         PSHUFDMask[Input / 2] = Input / 2;
9109       }
9110       return;
9111     }
9112
9113     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9114     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9115         InPlaceInputs[0] - HalfOffset;
9116     // Put the second input next to the first so that they are packed into
9117     // a dword. We find the adjacent index by toggling the low bit.
9118     int AdjIndex = InPlaceInputs[0] ^ 1;
9119     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9120     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9121     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9122   };
9123   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9124   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9125
9126   // Now gather the cross-half inputs and place them into a free dword of
9127   // their target half.
9128   // FIXME: This operation could almost certainly be simplified dramatically to
9129   // look more like the 3-1 fixing operation.
9130   auto moveInputsToRightHalf = [&PSHUFDMask](
9131       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9132       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9133       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9134       int DestOffset) {
9135     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9136       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9137     };
9138     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9139                                                int Word) {
9140       int LowWord = Word & ~1;
9141       int HighWord = Word | 1;
9142       return isWordClobbered(SourceHalfMask, LowWord) ||
9143              isWordClobbered(SourceHalfMask, HighWord);
9144     };
9145
9146     if (IncomingInputs.empty())
9147       return;
9148
9149     if (ExistingInputs.empty()) {
9150       // Map any dwords with inputs from them into the right half.
9151       for (int Input : IncomingInputs) {
9152         // If the source half mask maps over the inputs, turn those into
9153         // swaps and use the swapped lane.
9154         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9155           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9156             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9157                 Input - SourceOffset;
9158             // We have to swap the uses in our half mask in one sweep.
9159             for (int &M : HalfMask)
9160               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9161                 M = Input;
9162               else if (M == Input)
9163                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9164           } else {
9165             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9166                        Input - SourceOffset &&
9167                    "Previous placement doesn't match!");
9168           }
9169           // Note that this correctly re-maps both when we do a swap and when
9170           // we observe the other side of the swap above. We rely on that to
9171           // avoid swapping the members of the input list directly.
9172           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9173         }
9174
9175         // Map the input's dword into the correct half.
9176         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9177           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9178         else
9179           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9180                      Input / 2 &&
9181                  "Previous placement doesn't match!");
9182       }
9183
9184       // And just directly shift any other-half mask elements to be same-half
9185       // as we will have mirrored the dword containing the element into the
9186       // same position within that half.
9187       for (int &M : HalfMask)
9188         if (M >= SourceOffset && M < SourceOffset + 4) {
9189           M = M - SourceOffset + DestOffset;
9190           assert(M >= 0 && "This should never wrap below zero!");
9191         }
9192       return;
9193     }
9194
9195     // Ensure we have the input in a viable dword of its current half. This
9196     // is particularly tricky because the original position may be clobbered
9197     // by inputs being moved and *staying* in that half.
9198     if (IncomingInputs.size() == 1) {
9199       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9200         int InputFixed = std::find(std::begin(SourceHalfMask),
9201                                    std::end(SourceHalfMask), -1) -
9202                          std::begin(SourceHalfMask) + SourceOffset;
9203         SourceHalfMask[InputFixed - SourceOffset] =
9204             IncomingInputs[0] - SourceOffset;
9205         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9206                      InputFixed);
9207         IncomingInputs[0] = InputFixed;
9208       }
9209     } else if (IncomingInputs.size() == 2) {
9210       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9211           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9212         // We have two non-adjacent or clobbered inputs we need to extract from
9213         // the source half. To do this, we need to map them into some adjacent
9214         // dword slot in the source mask.
9215         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9216                               IncomingInputs[1] - SourceOffset};
9217
9218         // If there is a free slot in the source half mask adjacent to one of
9219         // the inputs, place the other input in it. We use (Index XOR 1) to
9220         // compute an adjacent index.
9221         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9222             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9223           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9224           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9225           InputsFixed[1] = InputsFixed[0] ^ 1;
9226         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9227                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9228           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9229           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9230           InputsFixed[0] = InputsFixed[1] ^ 1;
9231         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9232                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9233           // The two inputs are in the same DWord but it is clobbered and the
9234           // adjacent DWord isn't used at all. Move both inputs to the free
9235           // slot.
9236           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9237           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9238           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9239           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9240         } else {
9241           // The only way we hit this point is if there is no clobbering
9242           // (because there are no off-half inputs to this half) and there is no
9243           // free slot adjacent to one of the inputs. In this case, we have to
9244           // swap an input with a non-input.
9245           for (int i = 0; i < 4; ++i)
9246             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9247                    "We can't handle any clobbers here!");
9248           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9249                  "Cannot have adjacent inputs here!");
9250
9251           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9252           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9253
9254           // We also have to update the final source mask in this case because
9255           // it may need to undo the above swap.
9256           for (int &M : FinalSourceHalfMask)
9257             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9258               M = InputsFixed[1] + SourceOffset;
9259             else if (M == InputsFixed[1] + SourceOffset)
9260               M = (InputsFixed[0] ^ 1) + SourceOffset;
9261
9262           InputsFixed[1] = InputsFixed[0] ^ 1;
9263         }
9264
9265         // Point everything at the fixed inputs.
9266         for (int &M : HalfMask)
9267           if (M == IncomingInputs[0])
9268             M = InputsFixed[0] + SourceOffset;
9269           else if (M == IncomingInputs[1])
9270             M = InputsFixed[1] + SourceOffset;
9271
9272         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9273         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9274       }
9275     } else {
9276       llvm_unreachable("Unhandled input size!");
9277     }
9278
9279     // Now hoist the DWord down to the right half.
9280     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9281     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9282     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9283     for (int &M : HalfMask)
9284       for (int Input : IncomingInputs)
9285         if (M == Input)
9286           M = FreeDWord * 2 + Input % 2;
9287   };
9288   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9289                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9290   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9291                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9292
9293   // Now enact all the shuffles we've computed to move the inputs into their
9294   // target half.
9295   if (!isNoopShuffleMask(PSHUFLMask))
9296     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9297                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9298   if (!isNoopShuffleMask(PSHUFHMask))
9299     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9300                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9301   if (!isNoopShuffleMask(PSHUFDMask))
9302     V = DAG.getBitcast(
9303         VT,
9304         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9305                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9306
9307   // At this point, each half should contain all its inputs, and we can then
9308   // just shuffle them into their final position.
9309   assert(std::count_if(LoMask.begin(), LoMask.end(),
9310                        [](int M) { return M >= 4; }) == 0 &&
9311          "Failed to lift all the high half inputs to the low mask!");
9312   assert(std::count_if(HiMask.begin(), HiMask.end(),
9313                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9314          "Failed to lift all the low half inputs to the high mask!");
9315
9316   // Do a half shuffle for the low mask.
9317   if (!isNoopShuffleMask(LoMask))
9318     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9319                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9320
9321   // Do a half shuffle with the high mask after shifting its values down.
9322   for (int &M : HiMask)
9323     if (M >= 0)
9324       M -= 4;
9325   if (!isNoopShuffleMask(HiMask))
9326     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9327                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9328
9329   return V;
9330 }
9331
9332 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9333 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9334                                           SDValue V2, ArrayRef<int> Mask,
9335                                           SelectionDAG &DAG, bool &V1InUse,
9336                                           bool &V2InUse) {
9337   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9338   SDValue V1Mask[16];
9339   SDValue V2Mask[16];
9340   V1InUse = false;
9341   V2InUse = false;
9342
9343   int Size = Mask.size();
9344   int Scale = 16 / Size;
9345   for (int i = 0; i < 16; ++i) {
9346     if (Mask[i / Scale] == -1) {
9347       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9348     } else {
9349       const int ZeroMask = 0x80;
9350       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9351                                           : ZeroMask;
9352       int V2Idx = Mask[i / Scale] < Size
9353                       ? ZeroMask
9354                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9355       if (Zeroable[i / Scale])
9356         V1Idx = V2Idx = ZeroMask;
9357       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9358       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9359       V1InUse |= (ZeroMask != V1Idx);
9360       V2InUse |= (ZeroMask != V2Idx);
9361     }
9362   }
9363
9364   if (V1InUse)
9365     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9366                      DAG.getBitcast(MVT::v16i8, V1),
9367                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9368   if (V2InUse)
9369     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9370                      DAG.getBitcast(MVT::v16i8, V2),
9371                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9372
9373   // If we need shuffled inputs from both, blend the two.
9374   SDValue V;
9375   if (V1InUse && V2InUse)
9376     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9377   else
9378     V = V1InUse ? V1 : V2;
9379
9380   // Cast the result back to the correct type.
9381   return DAG.getBitcast(VT, V);
9382 }
9383
9384 /// \brief Generic lowering of 8-lane i16 shuffles.
9385 ///
9386 /// This handles both single-input shuffles and combined shuffle/blends with
9387 /// two inputs. The single input shuffles are immediately delegated to
9388 /// a dedicated lowering routine.
9389 ///
9390 /// The blends are lowered in one of three fundamental ways. If there are few
9391 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9392 /// of the input is significantly cheaper when lowered as an interleaving of
9393 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9394 /// halves of the inputs separately (making them have relatively few inputs)
9395 /// and then concatenate them.
9396 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9397                                        const X86Subtarget *Subtarget,
9398                                        SelectionDAG &DAG) {
9399   SDLoc DL(Op);
9400   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9401   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9402   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9403   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9404   ArrayRef<int> OrigMask = SVOp->getMask();
9405   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9406                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9407   MutableArrayRef<int> Mask(MaskStorage);
9408
9409   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9410
9411   // Whenever we can lower this as a zext, that instruction is strictly faster
9412   // than any alternative.
9413   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9414           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9415     return ZExt;
9416
9417   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9418   (void)isV1;
9419   auto isV2 = [](int M) { return M >= 8; };
9420
9421   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9422
9423   if (NumV2Inputs == 0) {
9424     // Check for being able to broadcast a single element.
9425     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9426                                                           Mask, Subtarget, DAG))
9427       return Broadcast;
9428
9429     // Try to use shift instructions.
9430     if (SDValue Shift =
9431             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9432       return Shift;
9433
9434     // Use dedicated unpack instructions for masks that match their pattern.
9435     if (SDValue V =
9436             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9437       return V;
9438
9439     // Try to use byte rotation instructions.
9440     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9441                                                         Mask, Subtarget, DAG))
9442       return Rotate;
9443
9444     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9445                                                      Subtarget, DAG);
9446   }
9447
9448   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9449          "All single-input shuffles should be canonicalized to be V1-input "
9450          "shuffles.");
9451
9452   // Try to use shift instructions.
9453   if (SDValue Shift =
9454           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9455     return Shift;
9456
9457   // See if we can use SSE4A Extraction / Insertion.
9458   if (Subtarget->hasSSE4A())
9459     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9460       return V;
9461
9462   // There are special ways we can lower some single-element blends.
9463   if (NumV2Inputs == 1)
9464     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9465                                                          Mask, Subtarget, DAG))
9466       return V;
9467
9468   // We have different paths for blend lowering, but they all must use the
9469   // *exact* same predicate.
9470   bool IsBlendSupported = Subtarget->hasSSE41();
9471   if (IsBlendSupported)
9472     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9473                                                   Subtarget, DAG))
9474       return Blend;
9475
9476   if (SDValue Masked =
9477           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9478     return Masked;
9479
9480   // Use dedicated unpack instructions for masks that match their pattern.
9481   if (SDValue V =
9482           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9483     return V;
9484
9485   // Try to use byte rotation instructions.
9486   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9487           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9488     return Rotate;
9489
9490   if (SDValue BitBlend =
9491           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9492     return BitBlend;
9493
9494   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9495                                                             V2, Mask, DAG))
9496     return Unpack;
9497
9498   // If we can't directly blend but can use PSHUFB, that will be better as it
9499   // can both shuffle and set up the inefficient blend.
9500   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9501     bool V1InUse, V2InUse;
9502     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9503                                       V1InUse, V2InUse);
9504   }
9505
9506   // We can always bit-blend if we have to so the fallback strategy is to
9507   // decompose into single-input permutes and blends.
9508   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9509                                                       Mask, DAG);
9510 }
9511
9512 /// \brief Check whether a compaction lowering can be done by dropping even
9513 /// elements and compute how many times even elements must be dropped.
9514 ///
9515 /// This handles shuffles which take every Nth element where N is a power of
9516 /// two. Example shuffle masks:
9517 ///
9518 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9519 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9520 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9521 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9522 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9523 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9524 ///
9525 /// Any of these lanes can of course be undef.
9526 ///
9527 /// This routine only supports N <= 3.
9528 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9529 /// for larger N.
9530 ///
9531 /// \returns N above, or the number of times even elements must be dropped if
9532 /// there is such a number. Otherwise returns zero.
9533 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9534   // Figure out whether we're looping over two inputs or just one.
9535   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9536
9537   // The modulus for the shuffle vector entries is based on whether this is
9538   // a single input or not.
9539   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9540   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9541          "We should only be called with masks with a power-of-2 size!");
9542
9543   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9544
9545   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9546   // and 2^3 simultaneously. This is because we may have ambiguity with
9547   // partially undef inputs.
9548   bool ViableForN[3] = {true, true, true};
9549
9550   for (int i = 0, e = Mask.size(); i < e; ++i) {
9551     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9552     // want.
9553     if (Mask[i] == -1)
9554       continue;
9555
9556     bool IsAnyViable = false;
9557     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9558       if (ViableForN[j]) {
9559         uint64_t N = j + 1;
9560
9561         // The shuffle mask must be equal to (i * 2^N) % M.
9562         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9563           IsAnyViable = true;
9564         else
9565           ViableForN[j] = false;
9566       }
9567     // Early exit if we exhaust the possible powers of two.
9568     if (!IsAnyViable)
9569       break;
9570   }
9571
9572   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9573     if (ViableForN[j])
9574       return j + 1;
9575
9576   // Return 0 as there is no viable power of two.
9577   return 0;
9578 }
9579
9580 /// \brief Generic lowering of v16i8 shuffles.
9581 ///
9582 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9583 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9584 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9585 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9586 /// back together.
9587 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9588                                        const X86Subtarget *Subtarget,
9589                                        SelectionDAG &DAG) {
9590   SDLoc DL(Op);
9591   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9592   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9593   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9594   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9595   ArrayRef<int> Mask = SVOp->getMask();
9596   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9597
9598   // Try to use shift instructions.
9599   if (SDValue Shift =
9600           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9601     return Shift;
9602
9603   // Try to use byte rotation instructions.
9604   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9605           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9606     return Rotate;
9607
9608   // Try to use a zext lowering.
9609   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9610           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9611     return ZExt;
9612
9613   // See if we can use SSE4A Extraction / Insertion.
9614   if (Subtarget->hasSSE4A())
9615     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9616       return V;
9617
9618   int NumV2Elements =
9619       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9620
9621   // For single-input shuffles, there are some nicer lowering tricks we can use.
9622   if (NumV2Elements == 0) {
9623     // Check for being able to broadcast a single element.
9624     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9625                                                           Mask, Subtarget, DAG))
9626       return Broadcast;
9627
9628     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9629     // Notably, this handles splat and partial-splat shuffles more efficiently.
9630     // However, it only makes sense if the pre-duplication shuffle simplifies
9631     // things significantly. Currently, this means we need to be able to
9632     // express the pre-duplication shuffle as an i16 shuffle.
9633     //
9634     // FIXME: We should check for other patterns which can be widened into an
9635     // i16 shuffle as well.
9636     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9637       for (int i = 0; i < 16; i += 2)
9638         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9639           return false;
9640
9641       return true;
9642     };
9643     auto tryToWidenViaDuplication = [&]() -> SDValue {
9644       if (!canWidenViaDuplication(Mask))
9645         return SDValue();
9646       SmallVector<int, 4> LoInputs;
9647       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9648                    [](int M) { return M >= 0 && M < 8; });
9649       std::sort(LoInputs.begin(), LoInputs.end());
9650       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9651                      LoInputs.end());
9652       SmallVector<int, 4> HiInputs;
9653       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9654                    [](int M) { return M >= 8; });
9655       std::sort(HiInputs.begin(), HiInputs.end());
9656       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9657                      HiInputs.end());
9658
9659       bool TargetLo = LoInputs.size() >= HiInputs.size();
9660       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9661       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9662
9663       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9664       SmallDenseMap<int, int, 8> LaneMap;
9665       for (int I : InPlaceInputs) {
9666         PreDupI16Shuffle[I/2] = I/2;
9667         LaneMap[I] = I;
9668       }
9669       int j = TargetLo ? 0 : 4, je = j + 4;
9670       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9671         // Check if j is already a shuffle of this input. This happens when
9672         // there are two adjacent bytes after we move the low one.
9673         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9674           // If we haven't yet mapped the input, search for a slot into which
9675           // we can map it.
9676           while (j < je && PreDupI16Shuffle[j] != -1)
9677             ++j;
9678
9679           if (j == je)
9680             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9681             return SDValue();
9682
9683           // Map this input with the i16 shuffle.
9684           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9685         }
9686
9687         // Update the lane map based on the mapping we ended up with.
9688         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9689       }
9690       V1 = DAG.getBitcast(
9691           MVT::v16i8,
9692           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9693                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9694
9695       // Unpack the bytes to form the i16s that will be shuffled into place.
9696       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9697                        MVT::v16i8, V1, V1);
9698
9699       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9700       for (int i = 0; i < 16; ++i)
9701         if (Mask[i] != -1) {
9702           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9703           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9704           if (PostDupI16Shuffle[i / 2] == -1)
9705             PostDupI16Shuffle[i / 2] = MappedMask;
9706           else
9707             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9708                    "Conflicting entrties in the original shuffle!");
9709         }
9710       return DAG.getBitcast(
9711           MVT::v16i8,
9712           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9713                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9714     };
9715     if (SDValue V = tryToWidenViaDuplication())
9716       return V;
9717   }
9718
9719   if (SDValue Masked =
9720           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9721     return Masked;
9722
9723   // Use dedicated unpack instructions for masks that match their pattern.
9724   if (SDValue V =
9725           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9726     return V;
9727
9728   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9729   // with PSHUFB. It is important to do this before we attempt to generate any
9730   // blends but after all of the single-input lowerings. If the single input
9731   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9732   // want to preserve that and we can DAG combine any longer sequences into
9733   // a PSHUFB in the end. But once we start blending from multiple inputs,
9734   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9735   // and there are *very* few patterns that would actually be faster than the
9736   // PSHUFB approach because of its ability to zero lanes.
9737   //
9738   // FIXME: The only exceptions to the above are blends which are exact
9739   // interleavings with direct instructions supporting them. We currently don't
9740   // handle those well here.
9741   if (Subtarget->hasSSSE3()) {
9742     bool V1InUse = false;
9743     bool V2InUse = false;
9744
9745     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9746                                                 DAG, V1InUse, V2InUse);
9747
9748     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9749     // do so. This avoids using them to handle blends-with-zero which is
9750     // important as a single pshufb is significantly faster for that.
9751     if (V1InUse && V2InUse) {
9752       if (Subtarget->hasSSE41())
9753         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9754                                                       Mask, Subtarget, DAG))
9755           return Blend;
9756
9757       // We can use an unpack to do the blending rather than an or in some
9758       // cases. Even though the or may be (very minorly) more efficient, we
9759       // preference this lowering because there are common cases where part of
9760       // the complexity of the shuffles goes away when we do the final blend as
9761       // an unpack.
9762       // FIXME: It might be worth trying to detect if the unpack-feeding
9763       // shuffles will both be pshufb, in which case we shouldn't bother with
9764       // this.
9765       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9766               DL, MVT::v16i8, V1, V2, Mask, DAG))
9767         return Unpack;
9768     }
9769
9770     return PSHUFB;
9771   }
9772
9773   // There are special ways we can lower some single-element blends.
9774   if (NumV2Elements == 1)
9775     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9776                                                          Mask, Subtarget, DAG))
9777       return V;
9778
9779   if (SDValue BitBlend =
9780           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9781     return BitBlend;
9782
9783   // Check whether a compaction lowering can be done. This handles shuffles
9784   // which take every Nth element for some even N. See the helper function for
9785   // details.
9786   //
9787   // We special case these as they can be particularly efficiently handled with
9788   // the PACKUSB instruction on x86 and they show up in common patterns of
9789   // rearranging bytes to truncate wide elements.
9790   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9791     // NumEvenDrops is the power of two stride of the elements. Another way of
9792     // thinking about it is that we need to drop the even elements this many
9793     // times to get the original input.
9794     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9795
9796     // First we need to zero all the dropped bytes.
9797     assert(NumEvenDrops <= 3 &&
9798            "No support for dropping even elements more than 3 times.");
9799     // We use the mask type to pick which bytes are preserved based on how many
9800     // elements are dropped.
9801     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9802     SDValue ByteClearMask = DAG.getBitcast(
9803         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9804     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9805     if (!IsSingleInput)
9806       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9807
9808     // Now pack things back together.
9809     V1 = DAG.getBitcast(MVT::v8i16, V1);
9810     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9811     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9812     for (int i = 1; i < NumEvenDrops; ++i) {
9813       Result = DAG.getBitcast(MVT::v8i16, Result);
9814       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9815     }
9816
9817     return Result;
9818   }
9819
9820   // Handle multi-input cases by blending single-input shuffles.
9821   if (NumV2Elements > 0)
9822     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9823                                                       Mask, DAG);
9824
9825   // The fallback path for single-input shuffles widens this into two v8i16
9826   // vectors with unpacks, shuffles those, and then pulls them back together
9827   // with a pack.
9828   SDValue V = V1;
9829
9830   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9831   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9832   for (int i = 0; i < 16; ++i)
9833     if (Mask[i] >= 0)
9834       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9835
9836   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9837
9838   SDValue VLoHalf, VHiHalf;
9839   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9840   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9841   // i16s.
9842   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9843                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9844       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9845                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9846     // Use a mask to drop the high bytes.
9847     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9848     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9849                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9850
9851     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9852     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9853
9854     // Squash the masks to point directly into VLoHalf.
9855     for (int &M : LoBlendMask)
9856       if (M >= 0)
9857         M /= 2;
9858     for (int &M : HiBlendMask)
9859       if (M >= 0)
9860         M /= 2;
9861   } else {
9862     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9863     // VHiHalf so that we can blend them as i16s.
9864     VLoHalf = DAG.getBitcast(
9865         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9866     VHiHalf = DAG.getBitcast(
9867         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9868   }
9869
9870   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9871   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9872
9873   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9874 }
9875
9876 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9877 ///
9878 /// This routine breaks down the specific type of 128-bit shuffle and
9879 /// dispatches to the lowering routines accordingly.
9880 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9881                                         MVT VT, const X86Subtarget *Subtarget,
9882                                         SelectionDAG &DAG) {
9883   switch (VT.SimpleTy) {
9884   case MVT::v2i64:
9885     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9886   case MVT::v2f64:
9887     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9888   case MVT::v4i32:
9889     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9890   case MVT::v4f32:
9891     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9892   case MVT::v8i16:
9893     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9894   case MVT::v16i8:
9895     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9896
9897   default:
9898     llvm_unreachable("Unimplemented!");
9899   }
9900 }
9901
9902 /// \brief Helper function to test whether a shuffle mask could be
9903 /// simplified by widening the elements being shuffled.
9904 ///
9905 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9906 /// leaves it in an unspecified state.
9907 ///
9908 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9909 /// shuffle masks. The latter have the special property of a '-2' representing
9910 /// a zero-ed lane of a vector.
9911 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9912                                     SmallVectorImpl<int> &WidenedMask) {
9913   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9914     // If both elements are undef, its trivial.
9915     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9916       WidenedMask.push_back(SM_SentinelUndef);
9917       continue;
9918     }
9919
9920     // Check for an undef mask and a mask value properly aligned to fit with
9921     // a pair of values. If we find such a case, use the non-undef mask's value.
9922     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9923       WidenedMask.push_back(Mask[i + 1] / 2);
9924       continue;
9925     }
9926     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9927       WidenedMask.push_back(Mask[i] / 2);
9928       continue;
9929     }
9930
9931     // When zeroing, we need to spread the zeroing across both lanes to widen.
9932     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9933       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9934           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9935         WidenedMask.push_back(SM_SentinelZero);
9936         continue;
9937       }
9938       return false;
9939     }
9940
9941     // Finally check if the two mask values are adjacent and aligned with
9942     // a pair.
9943     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9944       WidenedMask.push_back(Mask[i] / 2);
9945       continue;
9946     }
9947
9948     // Otherwise we can't safely widen the elements used in this shuffle.
9949     return false;
9950   }
9951   assert(WidenedMask.size() == Mask.size() / 2 &&
9952          "Incorrect size of mask after widening the elements!");
9953
9954   return true;
9955 }
9956
9957 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9958 ///
9959 /// This routine just extracts two subvectors, shuffles them independently, and
9960 /// then concatenates them back together. This should work effectively with all
9961 /// AVX vector shuffle types.
9962 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9963                                           SDValue V2, ArrayRef<int> Mask,
9964                                           SelectionDAG &DAG) {
9965   assert(VT.getSizeInBits() >= 256 &&
9966          "Only for 256-bit or wider vector shuffles!");
9967   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9968   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9969
9970   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9971   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9972
9973   int NumElements = VT.getVectorNumElements();
9974   int SplitNumElements = NumElements / 2;
9975   MVT ScalarVT = VT.getVectorElementType();
9976   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9977
9978   // Rather than splitting build-vectors, just build two narrower build
9979   // vectors. This helps shuffling with splats and zeros.
9980   auto SplitVector = [&](SDValue V) {
9981     while (V.getOpcode() == ISD::BITCAST)
9982       V = V->getOperand(0);
9983
9984     MVT OrigVT = V.getSimpleValueType();
9985     int OrigNumElements = OrigVT.getVectorNumElements();
9986     int OrigSplitNumElements = OrigNumElements / 2;
9987     MVT OrigScalarVT = OrigVT.getVectorElementType();
9988     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9989
9990     SDValue LoV, HiV;
9991
9992     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9993     if (!BV) {
9994       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9995                         DAG.getIntPtrConstant(0, DL));
9996       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9997                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9998     } else {
9999
10000       SmallVector<SDValue, 16> LoOps, HiOps;
10001       for (int i = 0; i < OrigSplitNumElements; ++i) {
10002         LoOps.push_back(BV->getOperand(i));
10003         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10004       }
10005       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10006       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10007     }
10008     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10009                           DAG.getBitcast(SplitVT, HiV));
10010   };
10011
10012   SDValue LoV1, HiV1, LoV2, HiV2;
10013   std::tie(LoV1, HiV1) = SplitVector(V1);
10014   std::tie(LoV2, HiV2) = SplitVector(V2);
10015
10016   // Now create two 4-way blends of these half-width vectors.
10017   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10018     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10019     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10020     for (int i = 0; i < SplitNumElements; ++i) {
10021       int M = HalfMask[i];
10022       if (M >= NumElements) {
10023         if (M >= NumElements + SplitNumElements)
10024           UseHiV2 = true;
10025         else
10026           UseLoV2 = true;
10027         V2BlendMask.push_back(M - NumElements);
10028         V1BlendMask.push_back(-1);
10029         BlendMask.push_back(SplitNumElements + i);
10030       } else if (M >= 0) {
10031         if (M >= SplitNumElements)
10032           UseHiV1 = true;
10033         else
10034           UseLoV1 = true;
10035         V2BlendMask.push_back(-1);
10036         V1BlendMask.push_back(M);
10037         BlendMask.push_back(i);
10038       } else {
10039         V2BlendMask.push_back(-1);
10040         V1BlendMask.push_back(-1);
10041         BlendMask.push_back(-1);
10042       }
10043     }
10044
10045     // Because the lowering happens after all combining takes place, we need to
10046     // manually combine these blend masks as much as possible so that we create
10047     // a minimal number of high-level vector shuffle nodes.
10048
10049     // First try just blending the halves of V1 or V2.
10050     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10051       return DAG.getUNDEF(SplitVT);
10052     if (!UseLoV2 && !UseHiV2)
10053       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10054     if (!UseLoV1 && !UseHiV1)
10055       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10056
10057     SDValue V1Blend, V2Blend;
10058     if (UseLoV1 && UseHiV1) {
10059       V1Blend =
10060         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10061     } else {
10062       // We only use half of V1 so map the usage down into the final blend mask.
10063       V1Blend = UseLoV1 ? LoV1 : HiV1;
10064       for (int i = 0; i < SplitNumElements; ++i)
10065         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10066           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10067     }
10068     if (UseLoV2 && UseHiV2) {
10069       V2Blend =
10070         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10071     } else {
10072       // We only use half of V2 so map the usage down into the final blend mask.
10073       V2Blend = UseLoV2 ? LoV2 : HiV2;
10074       for (int i = 0; i < SplitNumElements; ++i)
10075         if (BlendMask[i] >= SplitNumElements)
10076           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10077     }
10078     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10079   };
10080   SDValue Lo = HalfBlend(LoMask);
10081   SDValue Hi = HalfBlend(HiMask);
10082   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10083 }
10084
10085 /// \brief Either split a vector in halves or decompose the shuffles and the
10086 /// blend.
10087 ///
10088 /// This is provided as a good fallback for many lowerings of non-single-input
10089 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10090 /// between splitting the shuffle into 128-bit components and stitching those
10091 /// back together vs. extracting the single-input shuffles and blending those
10092 /// results.
10093 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10094                                                 SDValue V2, ArrayRef<int> Mask,
10095                                                 SelectionDAG &DAG) {
10096   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10097                                             "lower single-input shuffles as it "
10098                                             "could then recurse on itself.");
10099   int Size = Mask.size();
10100
10101   // If this can be modeled as a broadcast of two elements followed by a blend,
10102   // prefer that lowering. This is especially important because broadcasts can
10103   // often fold with memory operands.
10104   auto DoBothBroadcast = [&] {
10105     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10106     for (int M : Mask)
10107       if (M >= Size) {
10108         if (V2BroadcastIdx == -1)
10109           V2BroadcastIdx = M - Size;
10110         else if (M - Size != V2BroadcastIdx)
10111           return false;
10112       } else if (M >= 0) {
10113         if (V1BroadcastIdx == -1)
10114           V1BroadcastIdx = M;
10115         else if (M != V1BroadcastIdx)
10116           return false;
10117       }
10118     return true;
10119   };
10120   if (DoBothBroadcast())
10121     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10122                                                       DAG);
10123
10124   // If the inputs all stem from a single 128-bit lane of each input, then we
10125   // split them rather than blending because the split will decompose to
10126   // unusually few instructions.
10127   int LaneCount = VT.getSizeInBits() / 128;
10128   int LaneSize = Size / LaneCount;
10129   SmallBitVector LaneInputs[2];
10130   LaneInputs[0].resize(LaneCount, false);
10131   LaneInputs[1].resize(LaneCount, false);
10132   for (int i = 0; i < Size; ++i)
10133     if (Mask[i] >= 0)
10134       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10135   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10136     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10137
10138   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10139   // that the decomposed single-input shuffles don't end up here.
10140   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10141 }
10142
10143 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10144 /// a permutation and blend of those lanes.
10145 ///
10146 /// This essentially blends the out-of-lane inputs to each lane into the lane
10147 /// from a permuted copy of the vector. This lowering strategy results in four
10148 /// instructions in the worst case for a single-input cross lane shuffle which
10149 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10150 /// of. Special cases for each particular shuffle pattern should be handled
10151 /// prior to trying this lowering.
10152 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10153                                                        SDValue V1, SDValue V2,
10154                                                        ArrayRef<int> Mask,
10155                                                        SelectionDAG &DAG) {
10156   // FIXME: This should probably be generalized for 512-bit vectors as well.
10157   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10158   int LaneSize = Mask.size() / 2;
10159
10160   // If there are only inputs from one 128-bit lane, splitting will in fact be
10161   // less expensive. The flags track whether the given lane contains an element
10162   // that crosses to another lane.
10163   bool LaneCrossing[2] = {false, false};
10164   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10165     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10166       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10167   if (!LaneCrossing[0] || !LaneCrossing[1])
10168     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10169
10170   if (isSingleInputShuffleMask(Mask)) {
10171     SmallVector<int, 32> FlippedBlendMask;
10172     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10173       FlippedBlendMask.push_back(
10174           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10175                                   ? Mask[i]
10176                                   : Mask[i] % LaneSize +
10177                                         (i / LaneSize) * LaneSize + Size));
10178
10179     // Flip the vector, and blend the results which should now be in-lane. The
10180     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10181     // 5 for the high source. The value 3 selects the high half of source 2 and
10182     // the value 2 selects the low half of source 2. We only use source 2 to
10183     // allow folding it into a memory operand.
10184     unsigned PERMMask = 3 | 2 << 4;
10185     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10186                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10187     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10188   }
10189
10190   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10191   // will be handled by the above logic and a blend of the results, much like
10192   // other patterns in AVX.
10193   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10194 }
10195
10196 /// \brief Handle lowering 2-lane 128-bit shuffles.
10197 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10198                                         SDValue V2, ArrayRef<int> Mask,
10199                                         const X86Subtarget *Subtarget,
10200                                         SelectionDAG &DAG) {
10201   // TODO: If minimizing size and one of the inputs is a zero vector and the
10202   // the zero vector has only one use, we could use a VPERM2X128 to save the
10203   // instruction bytes needed to explicitly generate the zero vector.
10204
10205   // Blends are faster and handle all the non-lane-crossing cases.
10206   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10207                                                 Subtarget, DAG))
10208     return Blend;
10209
10210   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10211   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10212
10213   // If either input operand is a zero vector, use VPERM2X128 because its mask
10214   // allows us to replace the zero input with an implicit zero.
10215   if (!IsV1Zero && !IsV2Zero) {
10216     // Check for patterns which can be matched with a single insert of a 128-bit
10217     // subvector.
10218     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10219     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10220       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10221                                    VT.getVectorNumElements() / 2);
10222       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10223                                 DAG.getIntPtrConstant(0, DL));
10224       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10225                                 OnlyUsesV1 ? V1 : V2,
10226                                 DAG.getIntPtrConstant(0, DL));
10227       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10228     }
10229   }
10230
10231   // Otherwise form a 128-bit permutation. After accounting for undefs,
10232   // convert the 64-bit shuffle mask selection values into 128-bit
10233   // selection bits by dividing the indexes by 2 and shifting into positions
10234   // defined by a vperm2*128 instruction's immediate control byte.
10235
10236   // The immediate permute control byte looks like this:
10237   //    [1:0] - select 128 bits from sources for low half of destination
10238   //    [2]   - ignore
10239   //    [3]   - zero low half of destination
10240   //    [5:4] - select 128 bits from sources for high half of destination
10241   //    [6]   - ignore
10242   //    [7]   - zero high half of destination
10243
10244   int MaskLO = Mask[0];
10245   if (MaskLO == SM_SentinelUndef)
10246     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10247
10248   int MaskHI = Mask[2];
10249   if (MaskHI == SM_SentinelUndef)
10250     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10251
10252   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10253
10254   // If either input is a zero vector, replace it with an undef input.
10255   // Shuffle mask values <  4 are selecting elements of V1.
10256   // Shuffle mask values >= 4 are selecting elements of V2.
10257   // Adjust each half of the permute mask by clearing the half that was
10258   // selecting the zero vector and setting the zero mask bit.
10259   if (IsV1Zero) {
10260     V1 = DAG.getUNDEF(VT);
10261     if (MaskLO < 4)
10262       PermMask = (PermMask & 0xf0) | 0x08;
10263     if (MaskHI < 4)
10264       PermMask = (PermMask & 0x0f) | 0x80;
10265   }
10266   if (IsV2Zero) {
10267     V2 = DAG.getUNDEF(VT);
10268     if (MaskLO >= 4)
10269       PermMask = (PermMask & 0xf0) | 0x08;
10270     if (MaskHI >= 4)
10271       PermMask = (PermMask & 0x0f) | 0x80;
10272   }
10273
10274   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10275                      DAG.getConstant(PermMask, DL, MVT::i8));
10276 }
10277
10278 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10279 /// shuffling each lane.
10280 ///
10281 /// This will only succeed when the result of fixing the 128-bit lanes results
10282 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10283 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10284 /// the lane crosses early and then use simpler shuffles within each lane.
10285 ///
10286 /// FIXME: It might be worthwhile at some point to support this without
10287 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10288 /// in x86 only floating point has interesting non-repeating shuffles, and even
10289 /// those are still *marginally* more expensive.
10290 static SDValue lowerVectorShuffleByMerging128BitLanes(
10291     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10292     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10293   assert(!isSingleInputShuffleMask(Mask) &&
10294          "This is only useful with multiple inputs.");
10295
10296   int Size = Mask.size();
10297   int LaneSize = 128 / VT.getScalarSizeInBits();
10298   int NumLanes = Size / LaneSize;
10299   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10300
10301   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10302   // check whether the in-128-bit lane shuffles share a repeating pattern.
10303   SmallVector<int, 4> Lanes;
10304   Lanes.resize(NumLanes, -1);
10305   SmallVector<int, 4> InLaneMask;
10306   InLaneMask.resize(LaneSize, -1);
10307   for (int i = 0; i < Size; ++i) {
10308     if (Mask[i] < 0)
10309       continue;
10310
10311     int j = i / LaneSize;
10312
10313     if (Lanes[j] < 0) {
10314       // First entry we've seen for this lane.
10315       Lanes[j] = Mask[i] / LaneSize;
10316     } else if (Lanes[j] != Mask[i] / LaneSize) {
10317       // This doesn't match the lane selected previously!
10318       return SDValue();
10319     }
10320
10321     // Check that within each lane we have a consistent shuffle mask.
10322     int k = i % LaneSize;
10323     if (InLaneMask[k] < 0) {
10324       InLaneMask[k] = Mask[i] % LaneSize;
10325     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10326       // This doesn't fit a repeating in-lane mask.
10327       return SDValue();
10328     }
10329   }
10330
10331   // First shuffle the lanes into place.
10332   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10333                                 VT.getSizeInBits() / 64);
10334   SmallVector<int, 8> LaneMask;
10335   LaneMask.resize(NumLanes * 2, -1);
10336   for (int i = 0; i < NumLanes; ++i)
10337     if (Lanes[i] >= 0) {
10338       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10339       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10340     }
10341
10342   V1 = DAG.getBitcast(LaneVT, V1);
10343   V2 = DAG.getBitcast(LaneVT, V2);
10344   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10345
10346   // Cast it back to the type we actually want.
10347   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10348
10349   // Now do a simple shuffle that isn't lane crossing.
10350   SmallVector<int, 8> NewMask;
10351   NewMask.resize(Size, -1);
10352   for (int i = 0; i < Size; ++i)
10353     if (Mask[i] >= 0)
10354       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10355   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10356          "Must not introduce lane crosses at this point!");
10357
10358   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10359 }
10360
10361 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10362 /// This allows for fast cases such as subvector extraction/insertion
10363 /// or shuffling smaller vector types which can lower more efficiently.
10364 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10365                                                SDValue V2, ArrayRef<int> Mask,
10366                                                const X86Subtarget *Subtarget,
10367                                                SelectionDAG &DAG) {
10368   assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10369
10370   unsigned NumElts = VT.getVectorNumElements();
10371   unsigned HalfNumElts = NumElts / 2;
10372   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10373
10374   bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10375   bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10376   if (!UndefLower && !UndefUpper)
10377     return SDValue();
10378
10379   // Upper half is undef and lower half is whole upper subvector.
10380   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10381   if (UndefUpper &&
10382       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10383     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10384                              DAG.getIntPtrConstant(HalfNumElts, DL));
10385     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10386                        DAG.getIntPtrConstant(0, DL));
10387   }
10388
10389   // Lower half is undef and upper half is whole lower subvector.
10390   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10391   if (UndefLower &&
10392       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10393     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10394                              DAG.getIntPtrConstant(0, DL));
10395     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10396                        DAG.getIntPtrConstant(HalfNumElts, DL));
10397   }
10398
10399   // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10400   if (UndefLower && Subtarget->hasAVX2() &&
10401       (VT == MVT::v4f64 || VT == MVT::v4i64))
10402     return SDValue();
10403
10404   // If the shuffle only uses the lower halves of the input operands,
10405   // then extract them and perform the 'half' shuffle at half width.
10406   // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10407   int HalfIdx1 = -1, HalfIdx2 = -1;
10408   SmallVector<int, 8> HalfMask;
10409   unsigned Offset = UndefLower ? HalfNumElts : 0;
10410   for (unsigned i = 0; i != HalfNumElts; ++i) {
10411     int M = Mask[i + Offset];
10412     if (M < 0) {
10413       HalfMask.push_back(M);
10414       continue;
10415     }
10416
10417     // Determine which of the 4 half vectors this element is from.
10418     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10419     int HalfIdx = M / HalfNumElts;
10420
10421     // Only shuffle using the lower halves of the inputs.
10422     // TODO: Investigate usefulness of shuffling with upper halves.
10423     if (HalfIdx != 0 && HalfIdx != 2)
10424       return SDValue();
10425
10426     // Determine the element index into its half vector source.
10427     int HalfElt = M % HalfNumElts;
10428
10429     // We can shuffle with up to 2 half vectors, set the new 'half'
10430     // shuffle mask accordingly.
10431     if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10432       HalfMask.push_back(HalfElt);
10433       HalfIdx1 = HalfIdx;
10434       continue;
10435     }
10436     if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10437       HalfMask.push_back(HalfElt + HalfNumElts);
10438       HalfIdx2 = HalfIdx;
10439       continue;
10440     }
10441
10442     // Too many half vectors referenced.
10443     return SDValue();
10444   }
10445   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10446
10447   auto GetHalfVector = [&](int HalfIdx) {
10448     if (HalfIdx < 0)
10449       return DAG.getUNDEF(HalfVT);
10450     SDValue V = (HalfIdx < 2 ? V1 : V2);
10451     HalfIdx = (HalfIdx % 2) * HalfNumElts;
10452     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10453                        DAG.getIntPtrConstant(HalfIdx, DL));
10454   };
10455
10456   SDValue Half1 = GetHalfVector(HalfIdx1);
10457   SDValue Half2 = GetHalfVector(HalfIdx2);
10458   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10459   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10460                      DAG.getIntPtrConstant(Offset, DL));
10461 }
10462
10463 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10464 /// given mask.
10465 ///
10466 /// This returns true if the elements from a particular input are already in the
10467 /// slot required by the given mask and require no permutation.
10468 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10469   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10470   int Size = Mask.size();
10471   for (int i = 0; i < Size; ++i)
10472     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10473       return false;
10474
10475   return true;
10476 }
10477
10478 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10479                                             ArrayRef<int> Mask, SDValue V1,
10480                                             SDValue V2, SelectionDAG &DAG) {
10481
10482   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10483   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10484   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10485   int NumElts = VT.getVectorNumElements();
10486   bool ShufpdMask = true;
10487   bool CommutableMask = true;
10488   unsigned Immediate = 0;
10489   for (int i = 0; i < NumElts; ++i) {
10490     if (Mask[i] < 0)
10491       continue;
10492     int Val = (i & 6) + NumElts * (i & 1);
10493     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10494     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10495       ShufpdMask = false;
10496     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10497       CommutableMask = false;
10498     Immediate |= (Mask[i] % 2) << i;
10499   }
10500   if (ShufpdMask)
10501     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10502                        DAG.getConstant(Immediate, DL, MVT::i8));
10503   if (CommutableMask)
10504     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10505                        DAG.getConstant(Immediate, DL, MVT::i8));
10506   return SDValue();
10507 }
10508
10509 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10510 ///
10511 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10512 /// isn't available.
10513 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10514                                        const X86Subtarget *Subtarget,
10515                                        SelectionDAG &DAG) {
10516   SDLoc DL(Op);
10517   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10518   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10519   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10520   ArrayRef<int> Mask = SVOp->getMask();
10521   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10522
10523   SmallVector<int, 4> WidenedMask;
10524   if (canWidenShuffleElements(Mask, WidenedMask))
10525     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10526                                     DAG);
10527
10528   if (isSingleInputShuffleMask(Mask)) {
10529     // Check for being able to broadcast a single element.
10530     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10531                                                           Mask, Subtarget, DAG))
10532       return Broadcast;
10533
10534     // Use low duplicate instructions for masks that match their pattern.
10535     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10536       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10537
10538     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10539       // Non-half-crossing single input shuffles can be lowerid with an
10540       // interleaved permutation.
10541       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10542                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10543       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10544                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10545     }
10546
10547     // With AVX2 we have direct support for this permutation.
10548     if (Subtarget->hasAVX2())
10549       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10550                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10551
10552     // Otherwise, fall back.
10553     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10554                                                    DAG);
10555   }
10556
10557   // Use dedicated unpack instructions for masks that match their pattern.
10558   if (SDValue V =
10559           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10560     return V;
10561
10562   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10563                                                 Subtarget, DAG))
10564     return Blend;
10565
10566   // Check if the blend happens to exactly fit that of SHUFPD.
10567   if (SDValue Op =
10568       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10569     return Op;
10570
10571   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10572   // shuffle. However, if we have AVX2 and either inputs are already in place,
10573   // we will be able to shuffle even across lanes the other input in a single
10574   // instruction so skip this pattern.
10575   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10576                                  isShuffleMaskInputInPlace(1, Mask))))
10577     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10578             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10579       return Result;
10580
10581   // If we have AVX2 then we always want to lower with a blend because an v4 we
10582   // can fully permute the elements.
10583   if (Subtarget->hasAVX2())
10584     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10585                                                       Mask, DAG);
10586
10587   // Otherwise fall back on generic lowering.
10588   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10589 }
10590
10591 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10592 ///
10593 /// This routine is only called when we have AVX2 and thus a reasonable
10594 /// instruction set for v4i64 shuffling..
10595 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10596                                        const X86Subtarget *Subtarget,
10597                                        SelectionDAG &DAG) {
10598   SDLoc DL(Op);
10599   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10600   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10601   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10602   ArrayRef<int> Mask = SVOp->getMask();
10603   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10604   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10605
10606   SmallVector<int, 4> WidenedMask;
10607   if (canWidenShuffleElements(Mask, WidenedMask))
10608     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10609                                     DAG);
10610
10611   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10612                                                 Subtarget, DAG))
10613     return Blend;
10614
10615   // Check for being able to broadcast a single element.
10616   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10617                                                         Mask, Subtarget, DAG))
10618     return Broadcast;
10619
10620   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10621   // use lower latency instructions that will operate on both 128-bit lanes.
10622   SmallVector<int, 2> RepeatedMask;
10623   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10624     if (isSingleInputShuffleMask(Mask)) {
10625       int PSHUFDMask[] = {-1, -1, -1, -1};
10626       for (int i = 0; i < 2; ++i)
10627         if (RepeatedMask[i] >= 0) {
10628           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10629           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10630         }
10631       return DAG.getBitcast(
10632           MVT::v4i64,
10633           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10634                       DAG.getBitcast(MVT::v8i32, V1),
10635                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10636     }
10637   }
10638
10639   // AVX2 provides a direct instruction for permuting a single input across
10640   // lanes.
10641   if (isSingleInputShuffleMask(Mask))
10642     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10643                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10644
10645   // Try to use shift instructions.
10646   if (SDValue Shift =
10647           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10648     return Shift;
10649
10650   // Use dedicated unpack instructions for masks that match their pattern.
10651   if (SDValue V =
10652           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10653     return V;
10654
10655   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10656   // shuffle. However, if we have AVX2 and either inputs are already in place,
10657   // we will be able to shuffle even across lanes the other input in a single
10658   // instruction so skip this pattern.
10659   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10660                                  isShuffleMaskInputInPlace(1, Mask))))
10661     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10662             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10663       return Result;
10664
10665   // Otherwise fall back on generic blend lowering.
10666   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10667                                                     Mask, DAG);
10668 }
10669
10670 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10671 ///
10672 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10673 /// isn't available.
10674 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10675                                        const X86Subtarget *Subtarget,
10676                                        SelectionDAG &DAG) {
10677   SDLoc DL(Op);
10678   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10679   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10680   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10681   ArrayRef<int> Mask = SVOp->getMask();
10682   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10683
10684   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10685                                                 Subtarget, DAG))
10686     return Blend;
10687
10688   // Check for being able to broadcast a single element.
10689   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10690                                                         Mask, Subtarget, DAG))
10691     return Broadcast;
10692
10693   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10694   // options to efficiently lower the shuffle.
10695   SmallVector<int, 4> RepeatedMask;
10696   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10697     assert(RepeatedMask.size() == 4 &&
10698            "Repeated masks must be half the mask width!");
10699
10700     // Use even/odd duplicate instructions for masks that match their pattern.
10701     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10702       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10703     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10704       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10705
10706     if (isSingleInputShuffleMask(Mask))
10707       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10708                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10709
10710     // Use dedicated unpack instructions for masks that match their pattern.
10711     if (SDValue V =
10712             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10713       return V;
10714
10715     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10716     // have already handled any direct blends. We also need to squash the
10717     // repeated mask into a simulated v4f32 mask.
10718     for (int i = 0; i < 4; ++i)
10719       if (RepeatedMask[i] >= 8)
10720         RepeatedMask[i] -= 4;
10721     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10722   }
10723
10724   // If we have a single input shuffle with different shuffle patterns in the
10725   // two 128-bit lanes use the variable mask to VPERMILPS.
10726   if (isSingleInputShuffleMask(Mask)) {
10727     SDValue VPermMask[8];
10728     for (int i = 0; i < 8; ++i)
10729       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10730                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10731     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10732       return DAG.getNode(
10733           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10734           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10735
10736     if (Subtarget->hasAVX2())
10737       return DAG.getNode(
10738           X86ISD::VPERMV, DL, MVT::v8f32,
10739           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10740
10741     // Otherwise, fall back.
10742     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10743                                                    DAG);
10744   }
10745
10746   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10747   // shuffle.
10748   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10749           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10750     return Result;
10751
10752   // If we have AVX2 then we always want to lower with a blend because at v8 we
10753   // can fully permute the elements.
10754   if (Subtarget->hasAVX2())
10755     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10756                                                       Mask, DAG);
10757
10758   // Otherwise fall back on generic lowering.
10759   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10760 }
10761
10762 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10763 ///
10764 /// This routine is only called when we have AVX2 and thus a reasonable
10765 /// instruction set for v8i32 shuffling..
10766 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10767                                        const X86Subtarget *Subtarget,
10768                                        SelectionDAG &DAG) {
10769   SDLoc DL(Op);
10770   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10771   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10772   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10773   ArrayRef<int> Mask = SVOp->getMask();
10774   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10775   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10776
10777   // Whenever we can lower this as a zext, that instruction is strictly faster
10778   // than any alternative. It also allows us to fold memory operands into the
10779   // shuffle in many cases.
10780   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10781                                                          Mask, Subtarget, DAG))
10782     return ZExt;
10783
10784   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10785                                                 Subtarget, DAG))
10786     return Blend;
10787
10788   // Check for being able to broadcast a single element.
10789   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10790                                                         Mask, Subtarget, DAG))
10791     return Broadcast;
10792
10793   // If the shuffle mask is repeated in each 128-bit lane we can use more
10794   // efficient instructions that mirror the shuffles across the two 128-bit
10795   // lanes.
10796   SmallVector<int, 4> RepeatedMask;
10797   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10798     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10799     if (isSingleInputShuffleMask(Mask))
10800       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10801                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10802
10803     // Use dedicated unpack instructions for masks that match their pattern.
10804     if (SDValue V =
10805             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10806       return V;
10807   }
10808
10809   // Try to use shift instructions.
10810   if (SDValue Shift =
10811           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10812     return Shift;
10813
10814   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10815           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10816     return Rotate;
10817
10818   // If the shuffle patterns aren't repeated but it is a single input, directly
10819   // generate a cross-lane VPERMD instruction.
10820   if (isSingleInputShuffleMask(Mask)) {
10821     SDValue VPermMask[8];
10822     for (int i = 0; i < 8; ++i)
10823       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10824                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10825     return DAG.getNode(
10826         X86ISD::VPERMV, DL, MVT::v8i32,
10827         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10828   }
10829
10830   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10831   // shuffle.
10832   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10833           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10834     return Result;
10835
10836   // Otherwise fall back on generic blend lowering.
10837   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10838                                                     Mask, DAG);
10839 }
10840
10841 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10842 ///
10843 /// This routine is only called when we have AVX2 and thus a reasonable
10844 /// instruction set for v16i16 shuffling..
10845 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10846                                         const X86Subtarget *Subtarget,
10847                                         SelectionDAG &DAG) {
10848   SDLoc DL(Op);
10849   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10850   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10851   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10852   ArrayRef<int> Mask = SVOp->getMask();
10853   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10854   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10855
10856   // Whenever we can lower this as a zext, that instruction is strictly faster
10857   // than any alternative. It also allows us to fold memory operands into the
10858   // shuffle in many cases.
10859   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10860                                                          Mask, Subtarget, DAG))
10861     return ZExt;
10862
10863   // Check for being able to broadcast a single element.
10864   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10865                                                         Mask, Subtarget, DAG))
10866     return Broadcast;
10867
10868   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10869                                                 Subtarget, DAG))
10870     return Blend;
10871
10872   // Use dedicated unpack instructions for masks that match their pattern.
10873   if (SDValue V =
10874           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10875     return V;
10876
10877   // Try to use shift instructions.
10878   if (SDValue Shift =
10879           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10880     return Shift;
10881
10882   // Try to use byte rotation instructions.
10883   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10884           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10885     return Rotate;
10886
10887   if (isSingleInputShuffleMask(Mask)) {
10888     // There are no generalized cross-lane shuffle operations available on i16
10889     // element types.
10890     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10891       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10892                                                      Mask, DAG);
10893
10894     SmallVector<int, 8> RepeatedMask;
10895     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10896       // As this is a single-input shuffle, the repeated mask should be
10897       // a strictly valid v8i16 mask that we can pass through to the v8i16
10898       // lowering to handle even the v16 case.
10899       return lowerV8I16GeneralSingleInputVectorShuffle(
10900           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10901     }
10902
10903     SDValue PSHUFBMask[32];
10904     for (int i = 0; i < 16; ++i) {
10905       if (Mask[i] == -1) {
10906         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10907         continue;
10908       }
10909
10910       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10911       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10912       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10913       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10914     }
10915     return DAG.getBitcast(MVT::v16i16,
10916                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10917                                       DAG.getBitcast(MVT::v32i8, V1),
10918                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10919                                                   MVT::v32i8, PSHUFBMask)));
10920   }
10921
10922   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10923   // shuffle.
10924   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10925           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10926     return Result;
10927
10928   // Otherwise fall back on generic lowering.
10929   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10930 }
10931
10932 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10933 ///
10934 /// This routine is only called when we have AVX2 and thus a reasonable
10935 /// instruction set for v32i8 shuffling..
10936 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10937                                        const X86Subtarget *Subtarget,
10938                                        SelectionDAG &DAG) {
10939   SDLoc DL(Op);
10940   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10941   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10942   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10943   ArrayRef<int> Mask = SVOp->getMask();
10944   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10945   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10946
10947   // Whenever we can lower this as a zext, that instruction is strictly faster
10948   // than any alternative. It also allows us to fold memory operands into the
10949   // shuffle in many cases.
10950   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10951                                                          Mask, Subtarget, DAG))
10952     return ZExt;
10953
10954   // Check for being able to broadcast a single element.
10955   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10956                                                         Mask, Subtarget, DAG))
10957     return Broadcast;
10958
10959   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10960                                                 Subtarget, DAG))
10961     return Blend;
10962
10963   // Use dedicated unpack instructions for masks that match their pattern.
10964   if (SDValue V =
10965           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10966     return V;
10967
10968   // Try to use shift instructions.
10969   if (SDValue Shift =
10970           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10971     return Shift;
10972
10973   // Try to use byte rotation instructions.
10974   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10975           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10976     return Rotate;
10977
10978   if (isSingleInputShuffleMask(Mask)) {
10979     // There are no generalized cross-lane shuffle operations available on i8
10980     // element types.
10981     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10982       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10983                                                      Mask, DAG);
10984
10985     SDValue PSHUFBMask[32];
10986     for (int i = 0; i < 32; ++i)
10987       PSHUFBMask[i] =
10988           Mask[i] < 0
10989               ? DAG.getUNDEF(MVT::i8)
10990               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10991                                 MVT::i8);
10992
10993     return DAG.getNode(
10994         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10995         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10996   }
10997
10998   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10999   // shuffle.
11000   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11001           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11002     return Result;
11003
11004   // Otherwise fall back on generic lowering.
11005   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11006 }
11007
11008 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11009 ///
11010 /// This routine either breaks down the specific type of a 256-bit x86 vector
11011 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11012 /// together based on the available instructions.
11013 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11014                                         MVT VT, const X86Subtarget *Subtarget,
11015                                         SelectionDAG &DAG) {
11016   SDLoc DL(Op);
11017   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11018   ArrayRef<int> Mask = SVOp->getMask();
11019
11020   // If we have a single input to the zero element, insert that into V1 if we
11021   // can do so cheaply.
11022   int NumElts = VT.getVectorNumElements();
11023   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11024     return M >= NumElts;
11025   });
11026
11027   if (NumV2Elements == 1 && Mask[0] >= NumElts)
11028     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11029                               DL, VT, V1, V2, Mask, Subtarget, DAG))
11030       return Insertion;
11031
11032   // Handle special cases where the lower or upper half is UNDEF.
11033   if (SDValue V =
11034           lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11035     return V;
11036
11037   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11038   // can check for those subtargets here and avoid much of the subtarget
11039   // querying in the per-vector-type lowering routines. With AVX1 we have
11040   // essentially *zero* ability to manipulate a 256-bit vector with integer
11041   // types. Since we'll use floating point types there eventually, just
11042   // immediately cast everything to a float and operate entirely in that domain.
11043   if (VT.isInteger() && !Subtarget->hasAVX2()) {
11044     int ElementBits = VT.getScalarSizeInBits();
11045     if (ElementBits < 32)
11046       // No floating point type available, decompose into 128-bit vectors.
11047       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11048
11049     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11050                                 VT.getVectorNumElements());
11051     V1 = DAG.getBitcast(FpVT, V1);
11052     V2 = DAG.getBitcast(FpVT, V2);
11053     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11054   }
11055
11056   switch (VT.SimpleTy) {
11057   case MVT::v4f64:
11058     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11059   case MVT::v4i64:
11060     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11061   case MVT::v8f32:
11062     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11063   case MVT::v8i32:
11064     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11065   case MVT::v16i16:
11066     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11067   case MVT::v32i8:
11068     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11069
11070   default:
11071     llvm_unreachable("Not a valid 256-bit x86 vector type!");
11072   }
11073 }
11074
11075 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11076 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11077                                         ArrayRef<int> Mask,
11078                                         SDValue V1, SDValue V2,
11079                                         SelectionDAG &DAG) {
11080   assert(VT.getScalarSizeInBits() == 64 &&
11081          "Unexpected element type size for 128bit shuffle.");
11082
11083   // To handle 256 bit vector requires VLX and most probably
11084   // function lowerV2X128VectorShuffle() is better solution.
11085   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11086
11087   SmallVector<int, 4> WidenedMask;
11088   if (!canWidenShuffleElements(Mask, WidenedMask))
11089     return SDValue();
11090
11091   // Form a 128-bit permutation.
11092   // Convert the 64-bit shuffle mask selection values into 128-bit selection
11093   // bits defined by a vshuf64x2 instruction's immediate control byte.
11094   unsigned PermMask = 0, Imm = 0;
11095   unsigned ControlBitsNum = WidenedMask.size() / 2;
11096
11097   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11098     if (WidenedMask[i] == SM_SentinelZero)
11099       return SDValue();
11100
11101     // Use first element in place of undef mask.
11102     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11103     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11104   }
11105
11106   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11107                      DAG.getConstant(PermMask, DL, MVT::i8));
11108 }
11109
11110 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11111                                            ArrayRef<int> Mask, SDValue V1,
11112                                            SDValue V2, SelectionDAG &DAG) {
11113
11114   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11115
11116   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11117   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11118
11119   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11120   if (isSingleInputShuffleMask(Mask))
11121     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11122
11123   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11124 }
11125
11126 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11127 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11128                                        const X86Subtarget *Subtarget,
11129                                        SelectionDAG &DAG) {
11130   SDLoc DL(Op);
11131   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11132   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11133   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11134   ArrayRef<int> Mask = SVOp->getMask();
11135   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11136
11137   if (SDValue Shuf128 =
11138           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11139     return Shuf128;
11140
11141   if (SDValue Unpck =
11142           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11143     return Unpck;
11144
11145   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11146 }
11147
11148 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11149 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11150                                         const X86Subtarget *Subtarget,
11151                                         SelectionDAG &DAG) {
11152   SDLoc DL(Op);
11153   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11154   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11155   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11156   ArrayRef<int> Mask = SVOp->getMask();
11157   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11158
11159   if (SDValue Unpck =
11160           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11161     return Unpck;
11162
11163   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11164 }
11165
11166 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11167 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11168                                        const X86Subtarget *Subtarget,
11169                                        SelectionDAG &DAG) {
11170   SDLoc DL(Op);
11171   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11172   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11173   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11174   ArrayRef<int> Mask = SVOp->getMask();
11175   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11176
11177   if (SDValue Shuf128 =
11178           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11179     return Shuf128;
11180
11181   if (SDValue Unpck =
11182           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11183     return Unpck;
11184
11185   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11186 }
11187
11188 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11189 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11190                                         const X86Subtarget *Subtarget,
11191                                         SelectionDAG &DAG) {
11192   SDLoc DL(Op);
11193   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11194   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11195   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11196   ArrayRef<int> Mask = SVOp->getMask();
11197   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11198
11199   if (SDValue Unpck =
11200           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11201     return Unpck;
11202
11203   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11204 }
11205
11206 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11207 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11208                                         const X86Subtarget *Subtarget,
11209                                         SelectionDAG &DAG) {
11210   SDLoc DL(Op);
11211   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11212   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11213   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11214   ArrayRef<int> Mask = SVOp->getMask();
11215   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11216   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11217
11218   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11219 }
11220
11221 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11222 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11223                                        const X86Subtarget *Subtarget,
11224                                        SelectionDAG &DAG) {
11225   SDLoc DL(Op);
11226   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11227   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11228   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11229   ArrayRef<int> Mask = SVOp->getMask();
11230   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11231   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11232
11233   // FIXME: Implement direct support for this type!
11234   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11235 }
11236
11237 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11238 ///
11239 /// This routine either breaks down the specific type of a 512-bit x86 vector
11240 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11241 /// together based on the available instructions.
11242 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11243                                         MVT VT, const X86Subtarget *Subtarget,
11244                                         SelectionDAG &DAG) {
11245   SDLoc DL(Op);
11246   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11247   ArrayRef<int> Mask = SVOp->getMask();
11248   assert(Subtarget->hasAVX512() &&
11249          "Cannot lower 512-bit vectors w/ basic ISA!");
11250
11251   // Check for being able to broadcast a single element.
11252   if (SDValue Broadcast =
11253           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11254     return Broadcast;
11255
11256   // Dispatch to each element type for lowering. If we don't have supprot for
11257   // specific element type shuffles at 512 bits, immediately split them and
11258   // lower them. Each lowering routine of a given type is allowed to assume that
11259   // the requisite ISA extensions for that element type are available.
11260   switch (VT.SimpleTy) {
11261   case MVT::v8f64:
11262     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11263   case MVT::v16f32:
11264     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11265   case MVT::v8i64:
11266     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11267   case MVT::v16i32:
11268     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11269   case MVT::v32i16:
11270     if (Subtarget->hasBWI())
11271       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11272     break;
11273   case MVT::v64i8:
11274     if (Subtarget->hasBWI())
11275       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11276     break;
11277
11278   default:
11279     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11280   }
11281
11282   // Otherwise fall back on splitting.
11283   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11284 }
11285
11286 // Lower vXi1 vector shuffles.
11287 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11288 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11289 // vector, shuffle and then truncate it back.
11290 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11291                                       MVT VT, const X86Subtarget *Subtarget,
11292                                       SelectionDAG &DAG) {
11293   SDLoc DL(Op);
11294   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11295   ArrayRef<int> Mask = SVOp->getMask();
11296   assert(Subtarget->hasAVX512() &&
11297          "Cannot lower 512-bit vectors w/o basic ISA!");
11298   MVT ExtVT;
11299   switch (VT.SimpleTy) {
11300   default:
11301     llvm_unreachable("Expected a vector of i1 elements");
11302   case MVT::v2i1:
11303     ExtVT = MVT::v2i64;
11304     break;
11305   case MVT::v4i1:
11306     ExtVT = MVT::v4i32;
11307     break;
11308   case MVT::v8i1:
11309     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11310     break;
11311   case MVT::v16i1:
11312     ExtVT = MVT::v16i32;
11313     break;
11314   case MVT::v32i1:
11315     ExtVT = MVT::v32i16;
11316     break;
11317   case MVT::v64i1:
11318     ExtVT = MVT::v64i8;
11319     break;
11320   }
11321
11322   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11323     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11324   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11325     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11326   else
11327     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11328
11329   if (V2.isUndef())
11330     V2 = DAG.getUNDEF(ExtVT);
11331   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11332     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11333   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11334     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11335   else
11336     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11337   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11338                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11339 }
11340 /// \brief Top-level lowering for x86 vector shuffles.
11341 ///
11342 /// This handles decomposition, canonicalization, and lowering of all x86
11343 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11344 /// above in helper routines. The canonicalization attempts to widen shuffles
11345 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11346 /// s.t. only one of the two inputs needs to be tested, etc.
11347 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11348                                   SelectionDAG &DAG) {
11349   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11350   ArrayRef<int> Mask = SVOp->getMask();
11351   SDValue V1 = Op.getOperand(0);
11352   SDValue V2 = Op.getOperand(1);
11353   MVT VT = Op.getSimpleValueType();
11354   int NumElements = VT.getVectorNumElements();
11355   SDLoc dl(Op);
11356   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11357
11358   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11359          "Can't lower MMX shuffles");
11360
11361   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11362   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11363   if (V1IsUndef && V2IsUndef)
11364     return DAG.getUNDEF(VT);
11365
11366   // When we create a shuffle node we put the UNDEF node to second operand,
11367   // but in some cases the first operand may be transformed to UNDEF.
11368   // In this case we should just commute the node.
11369   if (V1IsUndef)
11370     return DAG.getCommutedVectorShuffle(*SVOp);
11371
11372   // Check for non-undef masks pointing at an undef vector and make the masks
11373   // undef as well. This makes it easier to match the shuffle based solely on
11374   // the mask.
11375   if (V2IsUndef)
11376     for (int M : Mask)
11377       if (M >= NumElements) {
11378         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11379         for (int &M : NewMask)
11380           if (M >= NumElements)
11381             M = -1;
11382         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11383       }
11384
11385   // We actually see shuffles that are entirely re-arrangements of a set of
11386   // zero inputs. This mostly happens while decomposing complex shuffles into
11387   // simple ones. Directly lower these as a buildvector of zeros.
11388   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11389   if (Zeroable.all())
11390     return getZeroVector(VT, Subtarget, DAG, dl);
11391
11392   // Try to collapse shuffles into using a vector type with fewer elements but
11393   // wider element types. We cap this to not form integers or floating point
11394   // elements wider than 64 bits, but it might be interesting to form i128
11395   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11396   SmallVector<int, 16> WidenedMask;
11397   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11398       canWidenShuffleElements(Mask, WidenedMask)) {
11399     MVT NewEltVT = VT.isFloatingPoint()
11400                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11401                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11402     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11403     // Make sure that the new vector type is legal. For example, v2f64 isn't
11404     // legal on SSE1.
11405     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11406       V1 = DAG.getBitcast(NewVT, V1);
11407       V2 = DAG.getBitcast(NewVT, V2);
11408       return DAG.getBitcast(
11409           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11410     }
11411   }
11412
11413   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11414   for (int M : SVOp->getMask())
11415     if (M < 0)
11416       ++NumUndefElements;
11417     else if (M < NumElements)
11418       ++NumV1Elements;
11419     else
11420       ++NumV2Elements;
11421
11422   // Commute the shuffle as needed such that more elements come from V1 than
11423   // V2. This allows us to match the shuffle pattern strictly on how many
11424   // elements come from V1 without handling the symmetric cases.
11425   if (NumV2Elements > NumV1Elements)
11426     return DAG.getCommutedVectorShuffle(*SVOp);
11427
11428   // When the number of V1 and V2 elements are the same, try to minimize the
11429   // number of uses of V2 in the low half of the vector. When that is tied,
11430   // ensure that the sum of indices for V1 is equal to or lower than the sum
11431   // indices for V2. When those are equal, try to ensure that the number of odd
11432   // indices for V1 is lower than the number of odd indices for V2.
11433   if (NumV1Elements == NumV2Elements) {
11434     int LowV1Elements = 0, LowV2Elements = 0;
11435     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11436       if (M >= NumElements)
11437         ++LowV2Elements;
11438       else if (M >= 0)
11439         ++LowV1Elements;
11440     if (LowV2Elements > LowV1Elements) {
11441       return DAG.getCommutedVectorShuffle(*SVOp);
11442     } else if (LowV2Elements == LowV1Elements) {
11443       int SumV1Indices = 0, SumV2Indices = 0;
11444       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11445         if (SVOp->getMask()[i] >= NumElements)
11446           SumV2Indices += i;
11447         else if (SVOp->getMask()[i] >= 0)
11448           SumV1Indices += i;
11449       if (SumV2Indices < SumV1Indices) {
11450         return DAG.getCommutedVectorShuffle(*SVOp);
11451       } else if (SumV2Indices == SumV1Indices) {
11452         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11453         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11454           if (SVOp->getMask()[i] >= NumElements)
11455             NumV2OddIndices += i % 2;
11456           else if (SVOp->getMask()[i] >= 0)
11457             NumV1OddIndices += i % 2;
11458         if (NumV2OddIndices < NumV1OddIndices)
11459           return DAG.getCommutedVectorShuffle(*SVOp);
11460       }
11461     }
11462   }
11463
11464   // For each vector width, delegate to a specialized lowering routine.
11465   if (VT.is128BitVector())
11466     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11467
11468   if (VT.is256BitVector())
11469     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11470
11471   if (VT.is512BitVector())
11472     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11473
11474   if (Is1BitVector)
11475     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11476   llvm_unreachable("Unimplemented!");
11477 }
11478
11479 // This function assumes its argument is a BUILD_VECTOR of constants or
11480 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11481 // true.
11482 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11483                                     unsigned &MaskValue) {
11484   MaskValue = 0;
11485   unsigned NumElems = BuildVector->getNumOperands();
11486
11487   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11488   // We don't handle the >2 lanes case right now.
11489   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11490   if (NumLanes > 2)
11491     return false;
11492
11493   unsigned NumElemsInLane = NumElems / NumLanes;
11494
11495   // Blend for v16i16 should be symmetric for the both lanes.
11496   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11497     SDValue EltCond = BuildVector->getOperand(i);
11498     SDValue SndLaneEltCond =
11499         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11500
11501     int Lane1Cond = -1, Lane2Cond = -1;
11502     if (isa<ConstantSDNode>(EltCond))
11503       Lane1Cond = !isNullConstant(EltCond);
11504     if (isa<ConstantSDNode>(SndLaneEltCond))
11505       Lane2Cond = !isNullConstant(SndLaneEltCond);
11506
11507     unsigned LaneMask = 0;
11508     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11509       // Lane1Cond != 0, means we want the first argument.
11510       // Lane1Cond == 0, means we want the second argument.
11511       // The encoding of this argument is 0 for the first argument, 1
11512       // for the second. Therefore, invert the condition.
11513       LaneMask = !Lane1Cond << i;
11514     else if (Lane1Cond < 0)
11515       LaneMask = !Lane2Cond << i;
11516     else
11517       return false;
11518
11519     MaskValue |= LaneMask;
11520     if (NumLanes == 2)
11521       MaskValue |= LaneMask << NumElemsInLane;
11522   }
11523   return true;
11524 }
11525
11526 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11527 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11528                                            const X86Subtarget *Subtarget,
11529                                            SelectionDAG &DAG) {
11530   SDValue Cond = Op.getOperand(0);
11531   SDValue LHS = Op.getOperand(1);
11532   SDValue RHS = Op.getOperand(2);
11533   SDLoc dl(Op);
11534   MVT VT = Op.getSimpleValueType();
11535
11536   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11537     return SDValue();
11538   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11539
11540   // Only non-legal VSELECTs reach this lowering, convert those into generic
11541   // shuffles and re-use the shuffle lowering path for blends.
11542   SmallVector<int, 32> Mask;
11543   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11544     SDValue CondElt = CondBV->getOperand(i);
11545     Mask.push_back(
11546         isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11547                                      : -1);
11548   }
11549   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11550 }
11551
11552 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11553   // A vselect where all conditions and data are constants can be optimized into
11554   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11555   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11556       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11557       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11558     return SDValue();
11559
11560   // Try to lower this to a blend-style vector shuffle. This can handle all
11561   // constant condition cases.
11562   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11563     return BlendOp;
11564
11565   // Variable blends are only legal from SSE4.1 onward.
11566   if (!Subtarget->hasSSE41())
11567     return SDValue();
11568
11569   // Only some types will be legal on some subtargets. If we can emit a legal
11570   // VSELECT-matching blend, return Op, and but if we need to expand, return
11571   // a null value.
11572   switch (Op.getSimpleValueType().SimpleTy) {
11573   default:
11574     // Most of the vector types have blends past SSE4.1.
11575     return Op;
11576
11577   case MVT::v32i8:
11578     // The byte blends for AVX vectors were introduced only in AVX2.
11579     if (Subtarget->hasAVX2())
11580       return Op;
11581
11582     return SDValue();
11583
11584   case MVT::v8i16:
11585   case MVT::v16i16:
11586     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11587     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11588       return Op;
11589
11590     // FIXME: We should custom lower this by fixing the condition and using i8
11591     // blends.
11592     return SDValue();
11593   }
11594 }
11595
11596 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11597   MVT VT = Op.getSimpleValueType();
11598   SDLoc dl(Op);
11599
11600   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11601     return SDValue();
11602
11603   if (VT.getSizeInBits() == 8) {
11604     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11605                                   Op.getOperand(0), Op.getOperand(1));
11606     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11607                                   DAG.getValueType(VT));
11608     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11609   }
11610
11611   if (VT.getSizeInBits() == 16) {
11612     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11613     if (isNullConstant(Op.getOperand(1)))
11614       return DAG.getNode(
11615           ISD::TRUNCATE, dl, MVT::i16,
11616           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11617                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11618                       Op.getOperand(1)));
11619     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11620                                   Op.getOperand(0), Op.getOperand(1));
11621     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11622                                   DAG.getValueType(VT));
11623     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11624   }
11625
11626   if (VT == MVT::f32) {
11627     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11628     // the result back to FR32 register. It's only worth matching if the
11629     // result has a single use which is a store or a bitcast to i32.  And in
11630     // the case of a store, it's not worth it if the index is a constant 0,
11631     // because a MOVSSmr can be used instead, which is smaller and faster.
11632     if (!Op.hasOneUse())
11633       return SDValue();
11634     SDNode *User = *Op.getNode()->use_begin();
11635     if ((User->getOpcode() != ISD::STORE ||
11636          isNullConstant(Op.getOperand(1))) &&
11637         (User->getOpcode() != ISD::BITCAST ||
11638          User->getValueType(0) != MVT::i32))
11639       return SDValue();
11640     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11641                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11642                                   Op.getOperand(1));
11643     return DAG.getBitcast(MVT::f32, Extract);
11644   }
11645
11646   if (VT == MVT::i32 || VT == MVT::i64) {
11647     // ExtractPS/pextrq works with constant index.
11648     if (isa<ConstantSDNode>(Op.getOperand(1)))
11649       return Op;
11650   }
11651   return SDValue();
11652 }
11653
11654 /// Extract one bit from mask vector, like v16i1 or v8i1.
11655 /// AVX-512 feature.
11656 SDValue
11657 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11658   SDValue Vec = Op.getOperand(0);
11659   SDLoc dl(Vec);
11660   MVT VecVT = Vec.getSimpleValueType();
11661   SDValue Idx = Op.getOperand(1);
11662   MVT EltVT = Op.getSimpleValueType();
11663
11664   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11665   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11666          "Unexpected vector type in ExtractBitFromMaskVector");
11667
11668   // variable index can't be handled in mask registers,
11669   // extend vector to VR512
11670   if (!isa<ConstantSDNode>(Idx)) {
11671     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11672     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11673     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11674                               ExtVT.getVectorElementType(), Ext, Idx);
11675     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11676   }
11677
11678   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11679   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11680   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11681     rc = getRegClassFor(MVT::v16i1);
11682   unsigned MaxSift = rc->getSize()*8 - 1;
11683   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11684                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11685   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11686                     DAG.getConstant(MaxSift, dl, MVT::i8));
11687   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11688                        DAG.getIntPtrConstant(0, dl));
11689 }
11690
11691 SDValue
11692 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11693                                            SelectionDAG &DAG) const {
11694   SDLoc dl(Op);
11695   SDValue Vec = Op.getOperand(0);
11696   MVT VecVT = Vec.getSimpleValueType();
11697   SDValue Idx = Op.getOperand(1);
11698
11699   if (Op.getSimpleValueType() == MVT::i1)
11700     return ExtractBitFromMaskVector(Op, DAG);
11701
11702   if (!isa<ConstantSDNode>(Idx)) {
11703     if (VecVT.is512BitVector() ||
11704         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11705          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11706
11707       MVT MaskEltVT =
11708         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11709       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11710                                     MaskEltVT.getSizeInBits());
11711
11712       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11713       auto PtrVT = getPointerTy(DAG.getDataLayout());
11714       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11715                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11716                                  DAG.getConstant(0, dl, PtrVT));
11717       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11718       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11719                          DAG.getConstant(0, dl, PtrVT));
11720     }
11721     return SDValue();
11722   }
11723
11724   // If this is a 256-bit vector result, first extract the 128-bit vector and
11725   // then extract the element from the 128-bit vector.
11726   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11727
11728     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11729     // Get the 128-bit vector.
11730     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11731     MVT EltVT = VecVT.getVectorElementType();
11732
11733     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11734     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11735
11736     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11737     // this can be done with a mask.
11738     IdxVal &= ElemsPerChunk - 1;
11739     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11740                        DAG.getConstant(IdxVal, dl, MVT::i32));
11741   }
11742
11743   assert(VecVT.is128BitVector() && "Unexpected vector length");
11744
11745   if (Subtarget->hasSSE41())
11746     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11747       return Res;
11748
11749   MVT VT = Op.getSimpleValueType();
11750   // TODO: handle v16i8.
11751   if (VT.getSizeInBits() == 16) {
11752     SDValue Vec = Op.getOperand(0);
11753     if (isNullConstant(Op.getOperand(1)))
11754       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11755                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11756                                      DAG.getBitcast(MVT::v4i32, Vec),
11757                                      Op.getOperand(1)));
11758     // Transform it so it match pextrw which produces a 32-bit result.
11759     MVT EltVT = MVT::i32;
11760     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11761                                   Op.getOperand(0), Op.getOperand(1));
11762     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11763                                   DAG.getValueType(VT));
11764     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11765   }
11766
11767   if (VT.getSizeInBits() == 32) {
11768     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11769     if (Idx == 0)
11770       return Op;
11771
11772     // SHUFPS the element to the lowest double word, then movss.
11773     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11774     MVT VVT = Op.getOperand(0).getSimpleValueType();
11775     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11776                                        DAG.getUNDEF(VVT), Mask);
11777     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11778                        DAG.getIntPtrConstant(0, dl));
11779   }
11780
11781   if (VT.getSizeInBits() == 64) {
11782     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11783     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11784     //        to match extract_elt for f64.
11785     if (isNullConstant(Op.getOperand(1)))
11786       return Op;
11787
11788     // UNPCKHPD the element to the lowest double word, then movsd.
11789     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11790     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11791     int Mask[2] = { 1, -1 };
11792     MVT VVT = Op.getOperand(0).getSimpleValueType();
11793     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11794                                        DAG.getUNDEF(VVT), Mask);
11795     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11796                        DAG.getIntPtrConstant(0, dl));
11797   }
11798
11799   return SDValue();
11800 }
11801
11802 /// Insert one bit to mask vector, like v16i1 or v8i1.
11803 /// AVX-512 feature.
11804 SDValue
11805 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11806   SDLoc dl(Op);
11807   SDValue Vec = Op.getOperand(0);
11808   SDValue Elt = Op.getOperand(1);
11809   SDValue Idx = Op.getOperand(2);
11810   MVT VecVT = Vec.getSimpleValueType();
11811
11812   if (!isa<ConstantSDNode>(Idx)) {
11813     // Non constant index. Extend source and destination,
11814     // insert element and then truncate the result.
11815     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11816     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11817     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11818       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11819       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11820     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11821   }
11822
11823   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11824   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11825   if (IdxVal)
11826     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11827                            DAG.getConstant(IdxVal, dl, MVT::i8));
11828   if (Vec.getOpcode() == ISD::UNDEF)
11829     return EltInVec;
11830   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11831 }
11832
11833 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11834                                                   SelectionDAG &DAG) const {
11835   MVT VT = Op.getSimpleValueType();
11836   MVT EltVT = VT.getVectorElementType();
11837
11838   if (EltVT == MVT::i1)
11839     return InsertBitToMaskVector(Op, DAG);
11840
11841   SDLoc dl(Op);
11842   SDValue N0 = Op.getOperand(0);
11843   SDValue N1 = Op.getOperand(1);
11844   SDValue N2 = Op.getOperand(2);
11845   if (!isa<ConstantSDNode>(N2))
11846     return SDValue();
11847   auto *N2C = cast<ConstantSDNode>(N2);
11848   unsigned IdxVal = N2C->getZExtValue();
11849
11850   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11851   // into that, and then insert the subvector back into the result.
11852   if (VT.is256BitVector() || VT.is512BitVector()) {
11853     // With a 256-bit vector, we can insert into the zero element efficiently
11854     // using a blend if we have AVX or AVX2 and the right data type.
11855     if (VT.is256BitVector() && IdxVal == 0) {
11856       // TODO: It is worthwhile to cast integer to floating point and back
11857       // and incur a domain crossing penalty if that's what we'll end up
11858       // doing anyway after extracting to a 128-bit vector.
11859       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11860           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11861         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11862         N2 = DAG.getIntPtrConstant(1, dl);
11863         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11864       }
11865     }
11866
11867     // Get the desired 128-bit vector chunk.
11868     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11869
11870     // Insert the element into the desired chunk.
11871     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11872     assert(isPowerOf2_32(NumEltsIn128));
11873     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11874     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11875
11876     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11877                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11878
11879     // Insert the changed part back into the bigger vector
11880     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11881   }
11882   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11883
11884   if (Subtarget->hasSSE41()) {
11885     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11886       unsigned Opc;
11887       if (VT == MVT::v8i16) {
11888         Opc = X86ISD::PINSRW;
11889       } else {
11890         assert(VT == MVT::v16i8);
11891         Opc = X86ISD::PINSRB;
11892       }
11893
11894       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11895       // argument.
11896       if (N1.getValueType() != MVT::i32)
11897         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11898       if (N2.getValueType() != MVT::i32)
11899         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11900       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11901     }
11902
11903     if (EltVT == MVT::f32) {
11904       // Bits [7:6] of the constant are the source select. This will always be
11905       //   zero here. The DAG Combiner may combine an extract_elt index into
11906       //   these bits. For example (insert (extract, 3), 2) could be matched by
11907       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11908       // Bits [5:4] of the constant are the destination select. This is the
11909       //   value of the incoming immediate.
11910       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11911       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11912
11913       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11914       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11915         // If this is an insertion of 32-bits into the low 32-bits of
11916         // a vector, we prefer to generate a blend with immediate rather
11917         // than an insertps. Blends are simpler operations in hardware and so
11918         // will always have equal or better performance than insertps.
11919         // But if optimizing for size and there's a load folding opportunity,
11920         // generate insertps because blendps does not have a 32-bit memory
11921         // operand form.
11922         N2 = DAG.getIntPtrConstant(1, dl);
11923         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11924         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11925       }
11926       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11927       // Create this as a scalar to vector..
11928       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11929       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11930     }
11931
11932     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11933       // PINSR* works with constant index.
11934       return Op;
11935     }
11936   }
11937
11938   if (EltVT == MVT::i8)
11939     return SDValue();
11940
11941   if (EltVT.getSizeInBits() == 16) {
11942     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11943     // as its second argument.
11944     if (N1.getValueType() != MVT::i32)
11945       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11946     if (N2.getValueType() != MVT::i32)
11947       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11948     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11949   }
11950   return SDValue();
11951 }
11952
11953 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11954   SDLoc dl(Op);
11955   MVT OpVT = Op.getSimpleValueType();
11956
11957   // If this is a 256-bit vector result, first insert into a 128-bit
11958   // vector and then insert into the 256-bit vector.
11959   if (!OpVT.is128BitVector()) {
11960     // Insert into a 128-bit vector.
11961     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11962     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11963                                  OpVT.getVectorNumElements() / SizeFactor);
11964
11965     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11966
11967     // Insert the 128-bit vector.
11968     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11969   }
11970
11971   if (OpVT == MVT::v1i64 &&
11972       Op.getOperand(0).getValueType() == MVT::i64)
11973     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11974
11975   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11976   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11977   return DAG.getBitcast(
11978       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11979 }
11980
11981 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11982 // a simple subregister reference or explicit instructions to grab
11983 // upper bits of a vector.
11984 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11985                                       SelectionDAG &DAG) {
11986   SDLoc dl(Op);
11987   SDValue In =  Op.getOperand(0);
11988   SDValue Idx = Op.getOperand(1);
11989   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11990   MVT ResVT   = Op.getSimpleValueType();
11991   MVT InVT    = In.getSimpleValueType();
11992
11993   if (Subtarget->hasFp256()) {
11994     if (ResVT.is128BitVector() &&
11995         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11996         isa<ConstantSDNode>(Idx)) {
11997       return Extract128BitVector(In, IdxVal, DAG, dl);
11998     }
11999     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12000         isa<ConstantSDNode>(Idx)) {
12001       return Extract256BitVector(In, IdxVal, DAG, dl);
12002     }
12003   }
12004   return SDValue();
12005 }
12006
12007 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12008 // simple superregister reference or explicit instructions to insert
12009 // the upper bits of a vector.
12010 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12011                                      SelectionDAG &DAG) {
12012   if (!Subtarget->hasAVX())
12013     return SDValue();
12014
12015   SDLoc dl(Op);
12016   SDValue Vec = Op.getOperand(0);
12017   SDValue SubVec = Op.getOperand(1);
12018   SDValue Idx = Op.getOperand(2);
12019
12020   if (!isa<ConstantSDNode>(Idx))
12021     return SDValue();
12022
12023   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12024   MVT OpVT = Op.getSimpleValueType();
12025   MVT SubVecVT = SubVec.getSimpleValueType();
12026
12027   // Fold two 16-byte subvector loads into one 32-byte load:
12028   // (insert_subvector (insert_subvector undef, (load addr), 0),
12029   //                   (load addr + 16), Elts/2)
12030   // --> load32 addr
12031   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12032       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12033       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12034     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12035     if (Idx2 && Idx2->getZExtValue() == 0) {
12036       SDValue SubVec2 = Vec.getOperand(1);
12037       // If needed, look through a bitcast to get to the load.
12038       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12039         SubVec2 = SubVec2.getOperand(0);
12040
12041       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12042         bool Fast;
12043         unsigned Alignment = FirstLd->getAlignment();
12044         unsigned AS = FirstLd->getAddressSpace();
12045         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12046         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12047                                     OpVT, AS, Alignment, &Fast) && Fast) {
12048           SDValue Ops[] = { SubVec2, SubVec };
12049           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12050             return Ld;
12051         }
12052       }
12053     }
12054   }
12055
12056   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12057       SubVecVT.is128BitVector())
12058     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12059
12060   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12061     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12062
12063   if (OpVT.getVectorElementType() == MVT::i1)
12064     return Insert1BitVector(Op, DAG);
12065
12066   return SDValue();
12067 }
12068
12069 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12070 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12071 // one of the above mentioned nodes. It has to be wrapped because otherwise
12072 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12073 // be used to form addressing mode. These wrapped nodes will be selected
12074 // into MOV32ri.
12075 SDValue
12076 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12077   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12078
12079   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12080   // global base reg.
12081   unsigned char OpFlag = 0;
12082   unsigned WrapperKind = X86ISD::Wrapper;
12083   CodeModel::Model M = DAG.getTarget().getCodeModel();
12084
12085   if (Subtarget->isPICStyleRIPRel() &&
12086       (M == CodeModel::Small || M == CodeModel::Kernel))
12087     WrapperKind = X86ISD::WrapperRIP;
12088   else if (Subtarget->isPICStyleGOT())
12089     OpFlag = X86II::MO_GOTOFF;
12090   else if (Subtarget->isPICStyleStubPIC())
12091     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12092
12093   auto PtrVT = getPointerTy(DAG.getDataLayout());
12094   SDValue Result = DAG.getTargetConstantPool(
12095       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12096   SDLoc DL(CP);
12097   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12098   // With PIC, the address is actually $g + Offset.
12099   if (OpFlag) {
12100     Result =
12101         DAG.getNode(ISD::ADD, DL, PtrVT,
12102                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12103   }
12104
12105   return Result;
12106 }
12107
12108 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12109   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12110
12111   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12112   // global base reg.
12113   unsigned char OpFlag = 0;
12114   unsigned WrapperKind = X86ISD::Wrapper;
12115   CodeModel::Model M = DAG.getTarget().getCodeModel();
12116
12117   if (Subtarget->isPICStyleRIPRel() &&
12118       (M == CodeModel::Small || M == CodeModel::Kernel))
12119     WrapperKind = X86ISD::WrapperRIP;
12120   else if (Subtarget->isPICStyleGOT())
12121     OpFlag = X86II::MO_GOTOFF;
12122   else if (Subtarget->isPICStyleStubPIC())
12123     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12124
12125   auto PtrVT = getPointerTy(DAG.getDataLayout());
12126   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12127   SDLoc DL(JT);
12128   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12129
12130   // With PIC, the address is actually $g + Offset.
12131   if (OpFlag)
12132     Result =
12133         DAG.getNode(ISD::ADD, DL, PtrVT,
12134                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12135
12136   return Result;
12137 }
12138
12139 SDValue
12140 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12141   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12142
12143   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12144   // global base reg.
12145   unsigned char OpFlag = 0;
12146   unsigned WrapperKind = X86ISD::Wrapper;
12147   CodeModel::Model M = DAG.getTarget().getCodeModel();
12148
12149   if (Subtarget->isPICStyleRIPRel() &&
12150       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12151     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12152       OpFlag = X86II::MO_GOTPCREL;
12153     WrapperKind = X86ISD::WrapperRIP;
12154   } else if (Subtarget->isPICStyleGOT()) {
12155     OpFlag = X86II::MO_GOT;
12156   } else if (Subtarget->isPICStyleStubPIC()) {
12157     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12158   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12159     OpFlag = X86II::MO_DARWIN_NONLAZY;
12160   }
12161
12162   auto PtrVT = getPointerTy(DAG.getDataLayout());
12163   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12164
12165   SDLoc DL(Op);
12166   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12167
12168   // With PIC, the address is actually $g + Offset.
12169   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12170       !Subtarget->is64Bit()) {
12171     Result =
12172         DAG.getNode(ISD::ADD, DL, PtrVT,
12173                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12174   }
12175
12176   // For symbols that require a load from a stub to get the address, emit the
12177   // load.
12178   if (isGlobalStubReference(OpFlag))
12179     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12180                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12181                          false, false, false, 0);
12182
12183   return Result;
12184 }
12185
12186 SDValue
12187 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12188   // Create the TargetBlockAddressAddress node.
12189   unsigned char OpFlags =
12190     Subtarget->ClassifyBlockAddressReference();
12191   CodeModel::Model M = DAG.getTarget().getCodeModel();
12192   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12193   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12194   SDLoc dl(Op);
12195   auto PtrVT = getPointerTy(DAG.getDataLayout());
12196   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12197
12198   if (Subtarget->isPICStyleRIPRel() &&
12199       (M == CodeModel::Small || M == CodeModel::Kernel))
12200     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12201   else
12202     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12203
12204   // With PIC, the address is actually $g + Offset.
12205   if (isGlobalRelativeToPICBase(OpFlags)) {
12206     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12207                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12208   }
12209
12210   return Result;
12211 }
12212
12213 SDValue
12214 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12215                                       int64_t Offset, SelectionDAG &DAG) const {
12216   // Create the TargetGlobalAddress node, folding in the constant
12217   // offset if it is legal.
12218   unsigned char OpFlags =
12219       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12220   CodeModel::Model M = DAG.getTarget().getCodeModel();
12221   auto PtrVT = getPointerTy(DAG.getDataLayout());
12222   SDValue Result;
12223   if (OpFlags == X86II::MO_NO_FLAG &&
12224       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12225     // A direct static reference to a global.
12226     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12227     Offset = 0;
12228   } else {
12229     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12230   }
12231
12232   if (Subtarget->isPICStyleRIPRel() &&
12233       (M == CodeModel::Small || M == CodeModel::Kernel))
12234     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12235   else
12236     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12237
12238   // With PIC, the address is actually $g + Offset.
12239   if (isGlobalRelativeToPICBase(OpFlags)) {
12240     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12241                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12242   }
12243
12244   // For globals that require a load from a stub to get the address, emit the
12245   // load.
12246   if (isGlobalStubReference(OpFlags))
12247     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12248                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12249                          false, false, false, 0);
12250
12251   // If there was a non-zero offset that we didn't fold, create an explicit
12252   // addition for it.
12253   if (Offset != 0)
12254     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12255                          DAG.getConstant(Offset, dl, PtrVT));
12256
12257   return Result;
12258 }
12259
12260 SDValue
12261 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12262   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12263   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12264   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12265 }
12266
12267 static SDValue
12268 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12269            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12270            unsigned char OperandFlags, bool LocalDynamic = false) {
12271   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12272   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12273   SDLoc dl(GA);
12274   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12275                                            GA->getValueType(0),
12276                                            GA->getOffset(),
12277                                            OperandFlags);
12278
12279   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12280                                            : X86ISD::TLSADDR;
12281
12282   if (InFlag) {
12283     SDValue Ops[] = { Chain,  TGA, *InFlag };
12284     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12285   } else {
12286     SDValue Ops[]  = { Chain, TGA };
12287     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12288   }
12289
12290   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12291   MFI->setAdjustsStack(true);
12292   MFI->setHasCalls(true);
12293
12294   SDValue Flag = Chain.getValue(1);
12295   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12296 }
12297
12298 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12299 static SDValue
12300 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12301                                 const EVT PtrVT) {
12302   SDValue InFlag;
12303   SDLoc dl(GA);  // ? function entry point might be better
12304   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12305                                    DAG.getNode(X86ISD::GlobalBaseReg,
12306                                                SDLoc(), PtrVT), InFlag);
12307   InFlag = Chain.getValue(1);
12308
12309   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12310 }
12311
12312 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12313 static SDValue
12314 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12315                                 const EVT PtrVT) {
12316   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12317                     X86::RAX, X86II::MO_TLSGD);
12318 }
12319
12320 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12321                                            SelectionDAG &DAG,
12322                                            const EVT PtrVT,
12323                                            bool is64Bit) {
12324   SDLoc dl(GA);
12325
12326   // Get the start address of the TLS block for this module.
12327   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12328       .getInfo<X86MachineFunctionInfo>();
12329   MFI->incNumLocalDynamicTLSAccesses();
12330
12331   SDValue Base;
12332   if (is64Bit) {
12333     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12334                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12335   } else {
12336     SDValue InFlag;
12337     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12338         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12339     InFlag = Chain.getValue(1);
12340     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12341                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12342   }
12343
12344   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12345   // of Base.
12346
12347   // Build x@dtpoff.
12348   unsigned char OperandFlags = X86II::MO_DTPOFF;
12349   unsigned WrapperKind = X86ISD::Wrapper;
12350   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12351                                            GA->getValueType(0),
12352                                            GA->getOffset(), OperandFlags);
12353   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12354
12355   // Add x@dtpoff with the base.
12356   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12357 }
12358
12359 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12360 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12361                                    const EVT PtrVT, TLSModel::Model model,
12362                                    bool is64Bit, bool isPIC) {
12363   SDLoc dl(GA);
12364
12365   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12366   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12367                                                          is64Bit ? 257 : 256));
12368
12369   SDValue ThreadPointer =
12370       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12371                   MachinePointerInfo(Ptr), false, false, false, 0);
12372
12373   unsigned char OperandFlags = 0;
12374   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12375   // initialexec.
12376   unsigned WrapperKind = X86ISD::Wrapper;
12377   if (model == TLSModel::LocalExec) {
12378     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12379   } else if (model == TLSModel::InitialExec) {
12380     if (is64Bit) {
12381       OperandFlags = X86II::MO_GOTTPOFF;
12382       WrapperKind = X86ISD::WrapperRIP;
12383     } else {
12384       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12385     }
12386   } else {
12387     llvm_unreachable("Unexpected model");
12388   }
12389
12390   // emit "addl x@ntpoff,%eax" (local exec)
12391   // or "addl x@indntpoff,%eax" (initial exec)
12392   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12393   SDValue TGA =
12394       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12395                                  GA->getOffset(), OperandFlags);
12396   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12397
12398   if (model == TLSModel::InitialExec) {
12399     if (isPIC && !is64Bit) {
12400       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12401                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12402                            Offset);
12403     }
12404
12405     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12406                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12407                          false, false, false, 0);
12408   }
12409
12410   // The address of the thread local variable is the add of the thread
12411   // pointer with the offset of the variable.
12412   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12413 }
12414
12415 SDValue
12416 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12417
12418   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12419
12420   // Cygwin uses emutls.
12421   // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12422   if (Subtarget->isTargetWindowsCygwin())
12423     return LowerToTLSEmulatedModel(GA, DAG);
12424
12425   const GlobalValue *GV = GA->getGlobal();
12426   auto PtrVT = getPointerTy(DAG.getDataLayout());
12427
12428   if (Subtarget->isTargetELF()) {
12429     if (DAG.getTarget().Options.EmulatedTLS)
12430       return LowerToTLSEmulatedModel(GA, DAG);
12431     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12432     switch (model) {
12433       case TLSModel::GeneralDynamic:
12434         if (Subtarget->is64Bit())
12435           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12436         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12437       case TLSModel::LocalDynamic:
12438         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12439                                            Subtarget->is64Bit());
12440       case TLSModel::InitialExec:
12441       case TLSModel::LocalExec:
12442         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12443                                    DAG.getTarget().getRelocationModel() ==
12444                                        Reloc::PIC_);
12445     }
12446     llvm_unreachable("Unknown TLS model.");
12447   }
12448
12449   if (Subtarget->isTargetDarwin()) {
12450     // Darwin only has one model of TLS.  Lower to that.
12451     unsigned char OpFlag = 0;
12452     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12453                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12454
12455     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12456     // global base reg.
12457     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12458                  !Subtarget->is64Bit();
12459     if (PIC32)
12460       OpFlag = X86II::MO_TLVP_PIC_BASE;
12461     else
12462       OpFlag = X86II::MO_TLVP;
12463     SDLoc DL(Op);
12464     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12465                                                 GA->getValueType(0),
12466                                                 GA->getOffset(), OpFlag);
12467     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12468
12469     // With PIC32, the address is actually $g + Offset.
12470     if (PIC32)
12471       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12472                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12473                            Offset);
12474
12475     // Lowering the machine isd will make sure everything is in the right
12476     // location.
12477     SDValue Chain = DAG.getEntryNode();
12478     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12479     SDValue Args[] = { Chain, Offset };
12480     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12481
12482     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12483     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12484     MFI->setAdjustsStack(true);
12485
12486     // And our return value (tls address) is in the standard call return value
12487     // location.
12488     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12489     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12490   }
12491
12492   if (Subtarget->isTargetKnownWindowsMSVC() ||
12493       Subtarget->isTargetWindowsGNU()) {
12494     // Just use the implicit TLS architecture
12495     // Need to generate someting similar to:
12496     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12497     //                                  ; from TEB
12498     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12499     //   mov     rcx, qword [rdx+rcx*8]
12500     //   mov     eax, .tls$:tlsvar
12501     //   [rax+rcx] contains the address
12502     // Windows 64bit: gs:0x58
12503     // Windows 32bit: fs:__tls_array
12504
12505     SDLoc dl(GA);
12506     SDValue Chain = DAG.getEntryNode();
12507
12508     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12509     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12510     // use its literal value of 0x2C.
12511     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12512                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12513                                                              256)
12514                                         : Type::getInt32PtrTy(*DAG.getContext(),
12515                                                               257));
12516
12517     SDValue TlsArray = Subtarget->is64Bit()
12518                            ? DAG.getIntPtrConstant(0x58, dl)
12519                            : (Subtarget->isTargetWindowsGNU()
12520                                   ? DAG.getIntPtrConstant(0x2C, dl)
12521                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12522
12523     SDValue ThreadPointer =
12524         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12525                     false, false, 0);
12526
12527     SDValue res;
12528     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12529       res = ThreadPointer;
12530     } else {
12531       // Load the _tls_index variable
12532       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12533       if (Subtarget->is64Bit())
12534         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12535                              MachinePointerInfo(), MVT::i32, false, false,
12536                              false, 0);
12537       else
12538         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12539                           false, false, 0);
12540
12541       auto &DL = DAG.getDataLayout();
12542       SDValue Scale =
12543           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12544       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12545
12546       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12547     }
12548
12549     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12550                       false, 0);
12551
12552     // Get the offset of start of .tls section
12553     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12554                                              GA->getValueType(0),
12555                                              GA->getOffset(), X86II::MO_SECREL);
12556     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12557
12558     // The address of the thread local variable is the add of the thread
12559     // pointer with the offset of the variable.
12560     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12561   }
12562
12563   llvm_unreachable("TLS not implemented for this target.");
12564 }
12565
12566 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12567 /// and take a 2 x i32 value to shift plus a shift amount.
12568 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12569   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12570   MVT VT = Op.getSimpleValueType();
12571   unsigned VTBits = VT.getSizeInBits();
12572   SDLoc dl(Op);
12573   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12574   SDValue ShOpLo = Op.getOperand(0);
12575   SDValue ShOpHi = Op.getOperand(1);
12576   SDValue ShAmt  = Op.getOperand(2);
12577   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12578   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12579   // during isel.
12580   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12581                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12582   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12583                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12584                        : DAG.getConstant(0, dl, VT);
12585
12586   SDValue Tmp2, Tmp3;
12587   if (Op.getOpcode() == ISD::SHL_PARTS) {
12588     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12589     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12590   } else {
12591     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12592     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12593   }
12594
12595   // If the shift amount is larger or equal than the width of a part we can't
12596   // rely on the results of shld/shrd. Insert a test and select the appropriate
12597   // values for large shift amounts.
12598   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12599                                 DAG.getConstant(VTBits, dl, MVT::i8));
12600   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12601                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12602
12603   SDValue Hi, Lo;
12604   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12605   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12606   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12607
12608   if (Op.getOpcode() == ISD::SHL_PARTS) {
12609     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12610     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12611   } else {
12612     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12613     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12614   }
12615
12616   SDValue Ops[2] = { Lo, Hi };
12617   return DAG.getMergeValues(Ops, dl);
12618 }
12619
12620 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12621                                            SelectionDAG &DAG) const {
12622   SDValue Src = Op.getOperand(0);
12623   MVT SrcVT = Src.getSimpleValueType();
12624   MVT VT = Op.getSimpleValueType();
12625   SDLoc dl(Op);
12626
12627   if (SrcVT.isVector()) {
12628     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12629       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12630                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12631                          DAG.getUNDEF(SrcVT)));
12632     }
12633     if (SrcVT.getVectorElementType() == MVT::i1) {
12634       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12635       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12636                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12637     }
12638     return SDValue();
12639   }
12640
12641   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12642          "Unknown SINT_TO_FP to lower!");
12643
12644   // These are really Legal; return the operand so the caller accepts it as
12645   // Legal.
12646   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12647     return Op;
12648   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12649       Subtarget->is64Bit()) {
12650     return Op;
12651   }
12652
12653   unsigned Size = SrcVT.getSizeInBits()/8;
12654   MachineFunction &MF = DAG.getMachineFunction();
12655   auto PtrVT = getPointerTy(MF.getDataLayout());
12656   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12657   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12658   SDValue Chain = DAG.getStore(
12659       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12660       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12661       false, 0);
12662   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12663 }
12664
12665 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12666                                      SDValue StackSlot,
12667                                      SelectionDAG &DAG) const {
12668   // Build the FILD
12669   SDLoc DL(Op);
12670   SDVTList Tys;
12671   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12672   if (useSSE)
12673     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12674   else
12675     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12676
12677   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12678
12679   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12680   MachineMemOperand *MMO;
12681   if (FI) {
12682     int SSFI = FI->getIndex();
12683     MMO = DAG.getMachineFunction().getMachineMemOperand(
12684         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12685         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12686   } else {
12687     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12688     StackSlot = StackSlot.getOperand(1);
12689   }
12690   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12691   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12692                                            X86ISD::FILD, DL,
12693                                            Tys, Ops, SrcVT, MMO);
12694
12695   if (useSSE) {
12696     Chain = Result.getValue(1);
12697     SDValue InFlag = Result.getValue(2);
12698
12699     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12700     // shouldn't be necessary except that RFP cannot be live across
12701     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12702     MachineFunction &MF = DAG.getMachineFunction();
12703     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12704     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12705     auto PtrVT = getPointerTy(MF.getDataLayout());
12706     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12707     Tys = DAG.getVTList(MVT::Other);
12708     SDValue Ops[] = {
12709       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12710     };
12711     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12712         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12713         MachineMemOperand::MOStore, SSFISize, SSFISize);
12714
12715     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12716                                     Ops, Op.getValueType(), MMO);
12717     Result = DAG.getLoad(
12718         Op.getValueType(), DL, Chain, StackSlot,
12719         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12720         false, false, false, 0);
12721   }
12722
12723   return Result;
12724 }
12725
12726 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12727 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12728                                                SelectionDAG &DAG) const {
12729   // This algorithm is not obvious. Here it is what we're trying to output:
12730   /*
12731      movq       %rax,  %xmm0
12732      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12733      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12734      #ifdef __SSE3__
12735        haddpd   %xmm0, %xmm0
12736      #else
12737        pshufd   $0x4e, %xmm0, %xmm1
12738        addpd    %xmm1, %xmm0
12739      #endif
12740   */
12741
12742   SDLoc dl(Op);
12743   LLVMContext *Context = DAG.getContext();
12744
12745   // Build some magic constants.
12746   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12747   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12748   auto PtrVT = getPointerTy(DAG.getDataLayout());
12749   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12750
12751   SmallVector<Constant*,2> CV1;
12752   CV1.push_back(
12753     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12754                                       APInt(64, 0x4330000000000000ULL))));
12755   CV1.push_back(
12756     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12757                                       APInt(64, 0x4530000000000000ULL))));
12758   Constant *C1 = ConstantVector::get(CV1);
12759   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12760
12761   // Load the 64-bit value into an XMM register.
12762   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12763                             Op.getOperand(0));
12764   SDValue CLod0 =
12765       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12766                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12767                   false, false, false, 16);
12768   SDValue Unpck1 =
12769       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12770
12771   SDValue CLod1 =
12772       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12773                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12774                   false, false, false, 16);
12775   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12776   // TODO: Are there any fast-math-flags to propagate here?
12777   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12778   SDValue Result;
12779
12780   if (Subtarget->hasSSE3()) {
12781     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12782     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12783   } else {
12784     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12785     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12786                                            S2F, 0x4E, DAG);
12787     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12788                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12789   }
12790
12791   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12792                      DAG.getIntPtrConstant(0, dl));
12793 }
12794
12795 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12796 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12797                                                SelectionDAG &DAG) const {
12798   SDLoc dl(Op);
12799   // FP constant to bias correct the final result.
12800   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12801                                    MVT::f64);
12802
12803   // Load the 32-bit value into an XMM register.
12804   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12805                              Op.getOperand(0));
12806
12807   // Zero out the upper parts of the register.
12808   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12809
12810   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12811                      DAG.getBitcast(MVT::v2f64, Load),
12812                      DAG.getIntPtrConstant(0, dl));
12813
12814   // Or the load with the bias.
12815   SDValue Or = DAG.getNode(
12816       ISD::OR, dl, MVT::v2i64,
12817       DAG.getBitcast(MVT::v2i64,
12818                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12819       DAG.getBitcast(MVT::v2i64,
12820                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12821   Or =
12822       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12823                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12824
12825   // Subtract the bias.
12826   // TODO: Are there any fast-math-flags to propagate here?
12827   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12828
12829   // Handle final rounding.
12830   MVT DestVT = Op.getSimpleValueType();
12831
12832   if (DestVT.bitsLT(MVT::f64))
12833     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12834                        DAG.getIntPtrConstant(0, dl));
12835   if (DestVT.bitsGT(MVT::f64))
12836     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12837
12838   // Handle final rounding.
12839   return Sub;
12840 }
12841
12842 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12843                                      const X86Subtarget &Subtarget) {
12844   // The algorithm is the following:
12845   // #ifdef __SSE4_1__
12846   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12847   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12848   //                                 (uint4) 0x53000000, 0xaa);
12849   // #else
12850   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12851   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12852   // #endif
12853   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12854   //     return (float4) lo + fhi;
12855
12856   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12857   // reassociate the two FADDs, and if we do that, the algorithm fails
12858   // spectacularly (PR24512).
12859   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12860   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12861   // there's also the MachineCombiner reassociations happening on Machine IR.
12862   if (DAG.getTarget().Options.UnsafeFPMath)
12863     return SDValue();
12864
12865   SDLoc DL(Op);
12866   SDValue V = Op->getOperand(0);
12867   MVT VecIntVT = V.getSimpleValueType();
12868   bool Is128 = VecIntVT == MVT::v4i32;
12869   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12870   // If we convert to something else than the supported type, e.g., to v4f64,
12871   // abort early.
12872   if (VecFloatVT != Op->getSimpleValueType(0))
12873     return SDValue();
12874
12875   unsigned NumElts = VecIntVT.getVectorNumElements();
12876   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12877          "Unsupported custom type");
12878   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12879
12880   // In the #idef/#else code, we have in common:
12881   // - The vector of constants:
12882   // -- 0x4b000000
12883   // -- 0x53000000
12884   // - A shift:
12885   // -- v >> 16
12886
12887   // Create the splat vector for 0x4b000000.
12888   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12889   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12890                            CstLow, CstLow, CstLow, CstLow};
12891   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12892                                   makeArrayRef(&CstLowArray[0], NumElts));
12893   // Create the splat vector for 0x53000000.
12894   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12895   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12896                             CstHigh, CstHigh, CstHigh, CstHigh};
12897   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12898                                    makeArrayRef(&CstHighArray[0], NumElts));
12899
12900   // Create the right shift.
12901   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12902   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12903                              CstShift, CstShift, CstShift, CstShift};
12904   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12905                                     makeArrayRef(&CstShiftArray[0], NumElts));
12906   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12907
12908   SDValue Low, High;
12909   if (Subtarget.hasSSE41()) {
12910     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12911     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12912     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12913     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12914     // Low will be bitcasted right away, so do not bother bitcasting back to its
12915     // original type.
12916     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12917                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12918     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12919     //                                 (uint4) 0x53000000, 0xaa);
12920     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12921     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12922     // High will be bitcasted right away, so do not bother bitcasting back to
12923     // its original type.
12924     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12925                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12926   } else {
12927     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12928     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12929                                      CstMask, CstMask, CstMask);
12930     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12931     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12932     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12933
12934     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12935     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12936   }
12937
12938   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12939   SDValue CstFAdd = DAG.getConstantFP(
12940       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12941   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12942                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12943   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12944                                    makeArrayRef(&CstFAddArray[0], NumElts));
12945
12946   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12947   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12948   // TODO: Are there any fast-math-flags to propagate here?
12949   SDValue FHigh =
12950       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12951   //     return (float4) lo + fhi;
12952   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12953   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12954 }
12955
12956 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12957                                                SelectionDAG &DAG) const {
12958   SDValue N0 = Op.getOperand(0);
12959   MVT SVT = N0.getSimpleValueType();
12960   SDLoc dl(Op);
12961
12962   switch (SVT.SimpleTy) {
12963   default:
12964     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12965   case MVT::v4i8:
12966   case MVT::v4i16:
12967   case MVT::v8i8:
12968   case MVT::v8i16: {
12969     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12970     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12971                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12972   }
12973   case MVT::v4i32:
12974   case MVT::v8i32:
12975     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12976   case MVT::v16i8:
12977   case MVT::v16i16:
12978     assert(Subtarget->hasAVX512());
12979     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12980                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12981   }
12982 }
12983
12984 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12985                                            SelectionDAG &DAG) const {
12986   SDValue N0 = Op.getOperand(0);
12987   SDLoc dl(Op);
12988   auto PtrVT = getPointerTy(DAG.getDataLayout());
12989
12990   if (Op.getSimpleValueType().isVector())
12991     return lowerUINT_TO_FP_vec(Op, DAG);
12992
12993   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12994   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12995   // the optimization here.
12996   if (DAG.SignBitIsZero(N0))
12997     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12998
12999   MVT SrcVT = N0.getSimpleValueType();
13000   MVT DstVT = Op.getSimpleValueType();
13001
13002   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13003       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13004     // Conversions from unsigned i32 to f32/f64 are legal,
13005     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
13006     return Op;
13007   }
13008
13009   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13010     return LowerUINT_TO_FP_i64(Op, DAG);
13011   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13012     return LowerUINT_TO_FP_i32(Op, DAG);
13013   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13014     return SDValue();
13015
13016   // Make a 64-bit buffer, and use it to build an FILD.
13017   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13018   if (SrcVT == MVT::i32) {
13019     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13020     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13021     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13022                                   StackSlot, MachinePointerInfo(),
13023                                   false, false, 0);
13024     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13025                                   OffsetSlot, MachinePointerInfo(),
13026                                   false, false, 0);
13027     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13028     return Fild;
13029   }
13030
13031   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13032   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13033                                StackSlot, MachinePointerInfo(),
13034                                false, false, 0);
13035   // For i64 source, we need to add the appropriate power of 2 if the input
13036   // was negative.  This is the same as the optimization in
13037   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13038   // we must be careful to do the computation in x87 extended precision, not
13039   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13040   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13041   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13042       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13043       MachineMemOperand::MOLoad, 8, 8);
13044
13045   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13046   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13047   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13048                                          MVT::i64, MMO);
13049
13050   APInt FF(32, 0x5F800000ULL);
13051
13052   // Check whether the sign bit is set.
13053   SDValue SignSet = DAG.getSetCC(
13054       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13055       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13056
13057   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13058   SDValue FudgePtr = DAG.getConstantPool(
13059       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13060
13061   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13062   SDValue Zero = DAG.getIntPtrConstant(0, dl);
13063   SDValue Four = DAG.getIntPtrConstant(4, dl);
13064   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13065                                Zero, Four);
13066   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13067
13068   // Load the value out, extending it from f32 to f80.
13069   // FIXME: Avoid the extend by constructing the right constant pool?
13070   SDValue Fudge = DAG.getExtLoad(
13071       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13072       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13073       false, false, false, 4);
13074   // Extend everything to 80 bits to force it to be done on x87.
13075   // TODO: Are there any fast-math-flags to propagate here?
13076   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13077   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13078                      DAG.getIntPtrConstant(0, dl));
13079 }
13080
13081 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13082 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13083 // just return an <SDValue(), SDValue()> pair.
13084 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13085 // to i16, i32 or i64, and we lower it to a legal sequence.
13086 // If lowered to the final integer result we return a <result, SDValue()> pair.
13087 // Otherwise we lower it to a sequence ending with a FIST, return a
13088 // <FIST, StackSlot> pair, and the caller is responsible for loading
13089 // the final integer result from StackSlot.
13090 std::pair<SDValue,SDValue>
13091 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13092                                    bool IsSigned, bool IsReplace) const {
13093   SDLoc DL(Op);
13094
13095   EVT DstTy = Op.getValueType();
13096   EVT TheVT = Op.getOperand(0).getValueType();
13097   auto PtrVT = getPointerTy(DAG.getDataLayout());
13098
13099   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13100     // f16 must be promoted before using the lowering in this routine.
13101     // fp128 does not use this lowering.
13102     return std::make_pair(SDValue(), SDValue());
13103   }
13104
13105   // If using FIST to compute an unsigned i64, we'll need some fixup
13106   // to handle values above the maximum signed i64.  A FIST is always
13107   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13108   bool UnsignedFixup = !IsSigned &&
13109                        DstTy == MVT::i64 &&
13110                        (!Subtarget->is64Bit() ||
13111                         !isScalarFPTypeInSSEReg(TheVT));
13112
13113   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13114     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13115     // The low 32 bits of the fist result will have the correct uint32 result.
13116     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13117     DstTy = MVT::i64;
13118   }
13119
13120   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13121          DstTy.getSimpleVT() >= MVT::i16 &&
13122          "Unknown FP_TO_INT to lower!");
13123
13124   // These are really Legal.
13125   if (DstTy == MVT::i32 &&
13126       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13127     return std::make_pair(SDValue(), SDValue());
13128   if (Subtarget->is64Bit() &&
13129       DstTy == MVT::i64 &&
13130       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13131     return std::make_pair(SDValue(), SDValue());
13132
13133   // We lower FP->int64 into FISTP64 followed by a load from a temporary
13134   // stack slot.
13135   MachineFunction &MF = DAG.getMachineFunction();
13136   unsigned MemSize = DstTy.getSizeInBits()/8;
13137   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13138   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13139
13140   unsigned Opc;
13141   switch (DstTy.getSimpleVT().SimpleTy) {
13142   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13143   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13144   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13145   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13146   }
13147
13148   SDValue Chain = DAG.getEntryNode();
13149   SDValue Value = Op.getOperand(0);
13150   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13151
13152   if (UnsignedFixup) {
13153     //
13154     // Conversion to unsigned i64 is implemented with a select,
13155     // depending on whether the source value fits in the range
13156     // of a signed i64.  Let Thresh be the FP equivalent of
13157     // 0x8000000000000000ULL.
13158     //
13159     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13160     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
13161     //  Fist-to-mem64 FistSrc
13162     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13163     //  to XOR'ing the high 32 bits with Adjust.
13164     //
13165     // Being a power of 2, Thresh is exactly representable in all FP formats.
13166     // For X87 we'd like to use the smallest FP type for this constant, but
13167     // for DAG type consistency we have to match the FP operand type.
13168
13169     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13170     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13171     bool LosesInfo = false;
13172     if (TheVT == MVT::f64)
13173       // The rounding mode is irrelevant as the conversion should be exact.
13174       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13175                               &LosesInfo);
13176     else if (TheVT == MVT::f80)
13177       Status = Thresh.convert(APFloat::x87DoubleExtended,
13178                               APFloat::rmNearestTiesToEven, &LosesInfo);
13179
13180     assert(Status == APFloat::opOK && !LosesInfo &&
13181            "FP conversion should have been exact");
13182
13183     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13184
13185     SDValue Cmp = DAG.getSetCC(DL,
13186                                getSetCCResultType(DAG.getDataLayout(),
13187                                                   *DAG.getContext(), TheVT),
13188                                Value, ThreshVal, ISD::SETLT);
13189     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13190                            DAG.getConstant(0, DL, MVT::i32),
13191                            DAG.getConstant(0x80000000, DL, MVT::i32));
13192     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13193     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13194                                               *DAG.getContext(), TheVT),
13195                        Value, ThreshVal, ISD::SETLT);
13196     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13197   }
13198
13199   // FIXME This causes a redundant load/store if the SSE-class value is already
13200   // in memory, such as if it is on the callstack.
13201   if (isScalarFPTypeInSSEReg(TheVT)) {
13202     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13203     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13204                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13205                          false, 0);
13206     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13207     SDValue Ops[] = {
13208       Chain, StackSlot, DAG.getValueType(TheVT)
13209     };
13210
13211     MachineMemOperand *MMO =
13212         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13213                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13214     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13215     Chain = Value.getValue(1);
13216     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13217     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13218   }
13219
13220   MachineMemOperand *MMO =
13221       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13222                               MachineMemOperand::MOStore, MemSize, MemSize);
13223
13224   if (UnsignedFixup) {
13225
13226     // Insert the FIST, load its result as two i32's,
13227     // and XOR the high i32 with Adjust.
13228
13229     SDValue FistOps[] = { Chain, Value, StackSlot };
13230     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13231                                            FistOps, DstTy, MMO);
13232
13233     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13234                                 MachinePointerInfo(),
13235                                 false, false, false, 0);
13236     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13237                                    DAG.getConstant(4, DL, PtrVT));
13238
13239     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13240                                  MachinePointerInfo(),
13241                                  false, false, false, 0);
13242     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13243
13244     if (Subtarget->is64Bit()) {
13245       // Join High32 and Low32 into a 64-bit result.
13246       // (High32 << 32) | Low32
13247       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13248       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13249       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13250                            DAG.getConstant(32, DL, MVT::i8));
13251       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13252       return std::make_pair(Result, SDValue());
13253     }
13254
13255     SDValue ResultOps[] = { Low32, High32 };
13256
13257     SDValue pair = IsReplace
13258       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13259       : DAG.getMergeValues(ResultOps, DL);
13260     return std::make_pair(pair, SDValue());
13261   } else {
13262     // Build the FP_TO_INT*_IN_MEM
13263     SDValue Ops[] = { Chain, Value, StackSlot };
13264     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13265                                            Ops, DstTy, MMO);
13266     return std::make_pair(FIST, StackSlot);
13267   }
13268 }
13269
13270 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13271                               const X86Subtarget *Subtarget) {
13272   MVT VT = Op->getSimpleValueType(0);
13273   SDValue In = Op->getOperand(0);
13274   MVT InVT = In.getSimpleValueType();
13275   SDLoc dl(Op);
13276
13277   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13278     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13279
13280   // Optimize vectors in AVX mode:
13281   //
13282   //   v8i16 -> v8i32
13283   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13284   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13285   //   Concat upper and lower parts.
13286   //
13287   //   v4i32 -> v4i64
13288   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13289   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13290   //   Concat upper and lower parts.
13291   //
13292
13293   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13294       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13295       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13296     return SDValue();
13297
13298   if (Subtarget->hasInt256())
13299     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13300
13301   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13302   SDValue Undef = DAG.getUNDEF(InVT);
13303   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13304   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13305   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13306
13307   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13308                              VT.getVectorNumElements()/2);
13309
13310   OpLo = DAG.getBitcast(HVT, OpLo);
13311   OpHi = DAG.getBitcast(HVT, OpHi);
13312
13313   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13314 }
13315
13316 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13317                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13318   MVT VT = Op->getSimpleValueType(0);
13319   SDValue In = Op->getOperand(0);
13320   MVT InVT = In.getSimpleValueType();
13321   SDLoc DL(Op);
13322   unsigned int NumElts = VT.getVectorNumElements();
13323   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13324     return SDValue();
13325
13326   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13327     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13328
13329   assert(InVT.getVectorElementType() == MVT::i1);
13330   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13331   SDValue One =
13332    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13333   SDValue Zero =
13334    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13335
13336   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13337   if (VT.is512BitVector())
13338     return V;
13339   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13340 }
13341
13342 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13343                                SelectionDAG &DAG) {
13344   if (Subtarget->hasFp256())
13345     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13346       return Res;
13347
13348   return SDValue();
13349 }
13350
13351 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13352                                 SelectionDAG &DAG) {
13353   SDLoc DL(Op);
13354   MVT VT = Op.getSimpleValueType();
13355   SDValue In = Op.getOperand(0);
13356   MVT SVT = In.getSimpleValueType();
13357
13358   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13359     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13360
13361   if (Subtarget->hasFp256())
13362     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13363       return Res;
13364
13365   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13366          VT.getVectorNumElements() != SVT.getVectorNumElements());
13367   return SDValue();
13368 }
13369
13370 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13371                                   const X86Subtarget *Subtarget) {
13372
13373   SDLoc DL(Op);
13374   MVT VT = Op.getSimpleValueType();
13375   SDValue In = Op.getOperand(0);
13376   MVT InVT = In.getSimpleValueType();
13377
13378   assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13379
13380   // Shift LSB to MSB and use VPMOVB2M - SKX.
13381   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13382   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13383          Subtarget->hasBWI()) ||     // legal, will go to VPMOVB2M, VPMOVW2M
13384       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13385              InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13386              Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13387     // Shift packed bytes not supported natively, bitcast to dword
13388     MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13389     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13390                                      DAG.getBitcast(ExtVT, In),
13391                                      DAG.getConstant(ShiftInx, DL, ExtVT));
13392     ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13393     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13394   }
13395   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13396          Subtarget->hasDQI()) ||  // legal, will go to VPMOVD2M, VPMOVQ2M
13397       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13398          InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13399          Subtarget->hasVLX())) {  // legal, will go to VPMOVD2M, VPMOVQ2M
13400
13401     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13402                                      DAG.getConstant(ShiftInx, DL, InVT));
13403     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13404   }
13405
13406   // Shift LSB to MSB, extend if necessary and use TESTM.
13407   unsigned NumElts = InVT.getVectorNumElements();
13408   if (InVT.getSizeInBits() < 512 &&
13409       (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13410        !Subtarget->hasVLX())) {
13411     assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13412
13413     // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13414     // so vector should be extended to packed dword/qword.
13415     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13416     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13417     InVT = ExtVT;
13418     ShiftInx = InVT.getScalarSizeInBits() - 1;
13419   }
13420
13421   SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13422                                    DAG.getConstant(ShiftInx, DL, InVT));
13423   return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13424 }
13425
13426 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13427   SDLoc DL(Op);
13428   MVT VT = Op.getSimpleValueType();
13429   SDValue In = Op.getOperand(0);
13430   MVT InVT = In.getSimpleValueType();
13431
13432   if (VT == MVT::i1) {
13433     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13434            "Invalid scalar TRUNCATE operation");
13435     if (InVT.getSizeInBits() >= 32)
13436       return SDValue();
13437     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13438     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13439   }
13440   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13441          "Invalid TRUNCATE operation");
13442
13443   if (VT.getVectorElementType() == MVT::i1)
13444     return LowerTruncateVecI1(Op, DAG, Subtarget);
13445
13446   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13447   if (Subtarget->hasAVX512()) {
13448     // word to byte only under BWI
13449     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13450       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13451                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13452     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13453   }
13454   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13455     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13456     if (Subtarget->hasInt256()) {
13457       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13458       In = DAG.getBitcast(MVT::v8i32, In);
13459       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13460                                 ShufMask);
13461       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13462                          DAG.getIntPtrConstant(0, DL));
13463     }
13464
13465     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13466                                DAG.getIntPtrConstant(0, DL));
13467     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13468                                DAG.getIntPtrConstant(2, DL));
13469     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13470     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13471     static const int ShufMask[] = {0, 2, 4, 6};
13472     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13473   }
13474
13475   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13476     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13477     if (Subtarget->hasInt256()) {
13478       In = DAG.getBitcast(MVT::v32i8, In);
13479
13480       SmallVector<SDValue,32> pshufbMask;
13481       for (unsigned i = 0; i < 2; ++i) {
13482         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13483         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13484         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13485         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13486         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13487         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13488         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13489         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13490         for (unsigned j = 0; j < 8; ++j)
13491           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13492       }
13493       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13494       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13495       In = DAG.getBitcast(MVT::v4i64, In);
13496
13497       static const int ShufMask[] = {0,  2,  -1,  -1};
13498       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13499                                 &ShufMask[0]);
13500       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13501                        DAG.getIntPtrConstant(0, DL));
13502       return DAG.getBitcast(VT, In);
13503     }
13504
13505     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13506                                DAG.getIntPtrConstant(0, DL));
13507
13508     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13509                                DAG.getIntPtrConstant(4, DL));
13510
13511     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13512     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13513
13514     // The PSHUFB mask:
13515     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13516                                    -1, -1, -1, -1, -1, -1, -1, -1};
13517
13518     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13519     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13520     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13521
13522     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13523     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13524
13525     // The MOVLHPS Mask:
13526     static const int ShufMask2[] = {0, 1, 4, 5};
13527     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13528     return DAG.getBitcast(MVT::v8i16, res);
13529   }
13530
13531   // Handle truncation of V256 to V128 using shuffles.
13532   if (!VT.is128BitVector() || !InVT.is256BitVector())
13533     return SDValue();
13534
13535   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13536
13537   unsigned NumElems = VT.getVectorNumElements();
13538   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13539
13540   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13541   // Prepare truncation shuffle mask
13542   for (unsigned i = 0; i != NumElems; ++i)
13543     MaskVec[i] = i * 2;
13544   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13545                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13546   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13547                      DAG.getIntPtrConstant(0, DL));
13548 }
13549
13550 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13551                                            SelectionDAG &DAG) const {
13552   assert(!Op.getSimpleValueType().isVector());
13553
13554   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13555     /*IsSigned=*/ true, /*IsReplace=*/ false);
13556   SDValue FIST = Vals.first, StackSlot = Vals.second;
13557   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13558   if (!FIST.getNode())
13559     return Op;
13560
13561   if (StackSlot.getNode())
13562     // Load the result.
13563     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13564                        FIST, StackSlot, MachinePointerInfo(),
13565                        false, false, false, 0);
13566
13567   // The node is the result.
13568   return FIST;
13569 }
13570
13571 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13572                                            SelectionDAG &DAG) const {
13573   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13574     /*IsSigned=*/ false, /*IsReplace=*/ false);
13575   SDValue FIST = Vals.first, StackSlot = Vals.second;
13576   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13577   if (!FIST.getNode())
13578     return Op;
13579
13580   if (StackSlot.getNode())
13581     // Load the result.
13582     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13583                        FIST, StackSlot, MachinePointerInfo(),
13584                        false, false, false, 0);
13585
13586   // The node is the result.
13587   return FIST;
13588 }
13589
13590 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13591   SDLoc DL(Op);
13592   MVT VT = Op.getSimpleValueType();
13593   SDValue In = Op.getOperand(0);
13594   MVT SVT = In.getSimpleValueType();
13595
13596   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13597
13598   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13599                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13600                                  In, DAG.getUNDEF(SVT)));
13601 }
13602
13603 /// The only differences between FABS and FNEG are the mask and the logic op.
13604 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13605 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13606   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13607          "Wrong opcode for lowering FABS or FNEG.");
13608
13609   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13610
13611   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13612   // into an FNABS. We'll lower the FABS after that if it is still in use.
13613   if (IsFABS)
13614     for (SDNode *User : Op->uses())
13615       if (User->getOpcode() == ISD::FNEG)
13616         return Op;
13617
13618   SDLoc dl(Op);
13619   MVT VT = Op.getSimpleValueType();
13620
13621   bool IsF128 = (VT == MVT::f128);
13622
13623   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13624   // decide if we should generate a 16-byte constant mask when we only need 4 or
13625   // 8 bytes for the scalar case.
13626
13627   MVT LogicVT;
13628   MVT EltVT;
13629   unsigned NumElts;
13630
13631   if (VT.isVector()) {
13632     LogicVT = VT;
13633     EltVT = VT.getVectorElementType();
13634     NumElts = VT.getVectorNumElements();
13635   } else if (IsF128) {
13636     // SSE instructions are used for optimized f128 logical operations.
13637     LogicVT = MVT::f128;
13638     EltVT = VT;
13639     NumElts = 1;
13640   } else {
13641     // There are no scalar bitwise logical SSE/AVX instructions, so we
13642     // generate a 16-byte vector constant and logic op even for the scalar case.
13643     // Using a 16-byte mask allows folding the load of the mask with
13644     // the logic op, so it can save (~4 bytes) on code size.
13645     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13646     EltVT = VT;
13647     NumElts = (VT == MVT::f64) ? 2 : 4;
13648   }
13649
13650   unsigned EltBits = EltVT.getSizeInBits();
13651   LLVMContext *Context = DAG.getContext();
13652   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13653   APInt MaskElt =
13654     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13655   Constant *C = ConstantInt::get(*Context, MaskElt);
13656   C = ConstantVector::getSplat(NumElts, C);
13657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13658   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13659   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13660   SDValue Mask =
13661       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13662                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13663                   false, false, false, Alignment);
13664
13665   SDValue Op0 = Op.getOperand(0);
13666   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13667   unsigned LogicOp =
13668     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13669   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13670
13671   if (VT.isVector() || IsF128)
13672     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13673
13674   // For the scalar case extend to a 128-bit vector, perform the logic op,
13675   // and extract the scalar result back out.
13676   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13677   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13678   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13679                      DAG.getIntPtrConstant(0, dl));
13680 }
13681
13682 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13683   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13684   LLVMContext *Context = DAG.getContext();
13685   SDValue Op0 = Op.getOperand(0);
13686   SDValue Op1 = Op.getOperand(1);
13687   SDLoc dl(Op);
13688   MVT VT = Op.getSimpleValueType();
13689   MVT SrcVT = Op1.getSimpleValueType();
13690   bool IsF128 = (VT == MVT::f128);
13691
13692   // If second operand is smaller, extend it first.
13693   if (SrcVT.bitsLT(VT)) {
13694     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13695     SrcVT = VT;
13696   }
13697   // And if it is bigger, shrink it first.
13698   if (SrcVT.bitsGT(VT)) {
13699     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13700     SrcVT = VT;
13701   }
13702
13703   // At this point the operands and the result should have the same
13704   // type, and that won't be f80 since that is not custom lowered.
13705   assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13706          "Unexpected type in LowerFCOPYSIGN");
13707
13708   const fltSemantics &Sem =
13709       VT == MVT::f64 ? APFloat::IEEEdouble :
13710           (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13711   const unsigned SizeInBits = VT.getSizeInBits();
13712
13713   SmallVector<Constant *, 4> CV(
13714       VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13715       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13716
13717   // First, clear all bits but the sign bit from the second operand (sign).
13718   CV[0] = ConstantFP::get(*Context,
13719                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13720   Constant *C = ConstantVector::get(CV);
13721   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13722   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13723
13724   // Perform all logic operations as 16-byte vectors because there are no
13725   // scalar FP logic instructions in SSE. This allows load folding of the
13726   // constants into the logic instructions.
13727   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13728   SDValue Mask1 =
13729       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13730                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13731                   false, false, false, 16);
13732   if (!IsF128)
13733     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13734   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13735
13736   // Next, clear the sign bit from the first operand (magnitude).
13737   // If it's a constant, we can clear it here.
13738   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13739     APFloat APF = Op0CN->getValueAPF();
13740     // If the magnitude is a positive zero, the sign bit alone is enough.
13741     if (APF.isPosZero())
13742       return IsF128 ? SignBit :
13743           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13744                       DAG.getIntPtrConstant(0, dl));
13745     APF.clearSign();
13746     CV[0] = ConstantFP::get(*Context, APF);
13747   } else {
13748     CV[0] = ConstantFP::get(
13749         *Context,
13750         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13751   }
13752   C = ConstantVector::get(CV);
13753   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13754   SDValue Val =
13755       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13756                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13757                   false, false, false, 16);
13758   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13759   if (!isa<ConstantFPSDNode>(Op0)) {
13760     if (!IsF128)
13761       Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13762     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13763   }
13764   // OR the magnitude value with the sign bit.
13765   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13766   return IsF128 ? Val :
13767       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13768                   DAG.getIntPtrConstant(0, dl));
13769 }
13770
13771 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13772   SDValue N0 = Op.getOperand(0);
13773   SDLoc dl(Op);
13774   MVT VT = Op.getSimpleValueType();
13775
13776   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13777   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13778                                   DAG.getConstant(1, dl, VT));
13779   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13780 }
13781
13782 // Check whether an OR'd tree is PTEST-able.
13783 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13784                                       SelectionDAG &DAG) {
13785   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13786
13787   if (!Subtarget->hasSSE41())
13788     return SDValue();
13789
13790   if (!Op->hasOneUse())
13791     return SDValue();
13792
13793   SDNode *N = Op.getNode();
13794   SDLoc DL(N);
13795
13796   SmallVector<SDValue, 8> Opnds;
13797   DenseMap<SDValue, unsigned> VecInMap;
13798   SmallVector<SDValue, 8> VecIns;
13799   EVT VT = MVT::Other;
13800
13801   // Recognize a special case where a vector is casted into wide integer to
13802   // test all 0s.
13803   Opnds.push_back(N->getOperand(0));
13804   Opnds.push_back(N->getOperand(1));
13805
13806   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13807     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13808     // BFS traverse all OR'd operands.
13809     if (I->getOpcode() == ISD::OR) {
13810       Opnds.push_back(I->getOperand(0));
13811       Opnds.push_back(I->getOperand(1));
13812       // Re-evaluate the number of nodes to be traversed.
13813       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13814       continue;
13815     }
13816
13817     // Quit if a non-EXTRACT_VECTOR_ELT
13818     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13819       return SDValue();
13820
13821     // Quit if without a constant index.
13822     SDValue Idx = I->getOperand(1);
13823     if (!isa<ConstantSDNode>(Idx))
13824       return SDValue();
13825
13826     SDValue ExtractedFromVec = I->getOperand(0);
13827     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13828     if (M == VecInMap.end()) {
13829       VT = ExtractedFromVec.getValueType();
13830       // Quit if not 128/256-bit vector.
13831       if (!VT.is128BitVector() && !VT.is256BitVector())
13832         return SDValue();
13833       // Quit if not the same type.
13834       if (VecInMap.begin() != VecInMap.end() &&
13835           VT != VecInMap.begin()->first.getValueType())
13836         return SDValue();
13837       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13838       VecIns.push_back(ExtractedFromVec);
13839     }
13840     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13841   }
13842
13843   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13844          "Not extracted from 128-/256-bit vector.");
13845
13846   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13847
13848   for (DenseMap<SDValue, unsigned>::const_iterator
13849         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13850     // Quit if not all elements are used.
13851     if (I->second != FullMask)
13852       return SDValue();
13853   }
13854
13855   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13856
13857   // Cast all vectors into TestVT for PTEST.
13858   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13859     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13860
13861   // If more than one full vectors are evaluated, OR them first before PTEST.
13862   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13863     // Each iteration will OR 2 nodes and append the result until there is only
13864     // 1 node left, i.e. the final OR'd value of all vectors.
13865     SDValue LHS = VecIns[Slot];
13866     SDValue RHS = VecIns[Slot + 1];
13867     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13868   }
13869
13870   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13871                      VecIns.back(), VecIns.back());
13872 }
13873
13874 /// \brief return true if \c Op has a use that doesn't just read flags.
13875 static bool hasNonFlagsUse(SDValue Op) {
13876   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13877        ++UI) {
13878     SDNode *User = *UI;
13879     unsigned UOpNo = UI.getOperandNo();
13880     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13881       // Look pass truncate.
13882       UOpNo = User->use_begin().getOperandNo();
13883       User = *User->use_begin();
13884     }
13885
13886     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13887         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13888       return true;
13889   }
13890   return false;
13891 }
13892
13893 /// Emit nodes that will be selected as "test Op0,Op0", or something
13894 /// equivalent.
13895 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13896                                     SelectionDAG &DAG) const {
13897   if (Op.getValueType() == MVT::i1) {
13898     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13899     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13900                        DAG.getConstant(0, dl, MVT::i8));
13901   }
13902   // CF and OF aren't always set the way we want. Determine which
13903   // of these we need.
13904   bool NeedCF = false;
13905   bool NeedOF = false;
13906   switch (X86CC) {
13907   default: break;
13908   case X86::COND_A: case X86::COND_AE:
13909   case X86::COND_B: case X86::COND_BE:
13910     NeedCF = true;
13911     break;
13912   case X86::COND_G: case X86::COND_GE:
13913   case X86::COND_L: case X86::COND_LE:
13914   case X86::COND_O: case X86::COND_NO: {
13915     // Check if we really need to set the
13916     // Overflow flag. If NoSignedWrap is present
13917     // that is not actually needed.
13918     switch (Op->getOpcode()) {
13919     case ISD::ADD:
13920     case ISD::SUB:
13921     case ISD::MUL:
13922     case ISD::SHL: {
13923       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13924       if (BinNode->Flags.hasNoSignedWrap())
13925         break;
13926     }
13927     default:
13928       NeedOF = true;
13929       break;
13930     }
13931     break;
13932   }
13933   }
13934   // See if we can use the EFLAGS value from the operand instead of
13935   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13936   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13937   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13938     // Emit a CMP with 0, which is the TEST pattern.
13939     //if (Op.getValueType() == MVT::i1)
13940     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13941     //                     DAG.getConstant(0, MVT::i1));
13942     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13943                        DAG.getConstant(0, dl, Op.getValueType()));
13944   }
13945   unsigned Opcode = 0;
13946   unsigned NumOperands = 0;
13947
13948   // Truncate operations may prevent the merge of the SETCC instruction
13949   // and the arithmetic instruction before it. Attempt to truncate the operands
13950   // of the arithmetic instruction and use a reduced bit-width instruction.
13951   bool NeedTruncation = false;
13952   SDValue ArithOp = Op;
13953   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13954     SDValue Arith = Op->getOperand(0);
13955     // Both the trunc and the arithmetic op need to have one user each.
13956     if (Arith->hasOneUse())
13957       switch (Arith.getOpcode()) {
13958         default: break;
13959         case ISD::ADD:
13960         case ISD::SUB:
13961         case ISD::AND:
13962         case ISD::OR:
13963         case ISD::XOR: {
13964           NeedTruncation = true;
13965           ArithOp = Arith;
13966         }
13967       }
13968   }
13969
13970   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13971   // which may be the result of a CAST.  We use the variable 'Op', which is the
13972   // non-casted variable when we check for possible users.
13973   switch (ArithOp.getOpcode()) {
13974   case ISD::ADD:
13975     // Due to an isel shortcoming, be conservative if this add is likely to be
13976     // selected as part of a load-modify-store instruction. When the root node
13977     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13978     // uses of other nodes in the match, such as the ADD in this case. This
13979     // leads to the ADD being left around and reselected, with the result being
13980     // two adds in the output.  Alas, even if none our users are stores, that
13981     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13982     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13983     // climbing the DAG back to the root, and it doesn't seem to be worth the
13984     // effort.
13985     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13986          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13987       if (UI->getOpcode() != ISD::CopyToReg &&
13988           UI->getOpcode() != ISD::SETCC &&
13989           UI->getOpcode() != ISD::STORE)
13990         goto default_case;
13991
13992     if (ConstantSDNode *C =
13993         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13994       // An add of one will be selected as an INC.
13995       if (C->isOne() && !Subtarget->slowIncDec()) {
13996         Opcode = X86ISD::INC;
13997         NumOperands = 1;
13998         break;
13999       }
14000
14001       // An add of negative one (subtract of one) will be selected as a DEC.
14002       if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14003         Opcode = X86ISD::DEC;
14004         NumOperands = 1;
14005         break;
14006       }
14007     }
14008
14009     // Otherwise use a regular EFLAGS-setting add.
14010     Opcode = X86ISD::ADD;
14011     NumOperands = 2;
14012     break;
14013   case ISD::SHL:
14014   case ISD::SRL:
14015     // If we have a constant logical shift that's only used in a comparison
14016     // against zero turn it into an equivalent AND. This allows turning it into
14017     // a TEST instruction later.
14018     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14019         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14020       EVT VT = Op.getValueType();
14021       unsigned BitWidth = VT.getSizeInBits();
14022       unsigned ShAmt = Op->getConstantOperandVal(1);
14023       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14024         break;
14025       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14026                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14027                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14028       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14029         break;
14030       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14031                                 DAG.getConstant(Mask, dl, VT));
14032       DAG.ReplaceAllUsesWith(Op, New);
14033       Op = New;
14034     }
14035     break;
14036
14037   case ISD::AND:
14038     // If the primary and result isn't used, don't bother using X86ISD::AND,
14039     // because a TEST instruction will be better.
14040     if (!hasNonFlagsUse(Op))
14041       break;
14042     // FALL THROUGH
14043   case ISD::SUB:
14044   case ISD::OR:
14045   case ISD::XOR:
14046     // Due to the ISEL shortcoming noted above, be conservative if this op is
14047     // likely to be selected as part of a load-modify-store instruction.
14048     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14049            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14050       if (UI->getOpcode() == ISD::STORE)
14051         goto default_case;
14052
14053     // Otherwise use a regular EFLAGS-setting instruction.
14054     switch (ArithOp.getOpcode()) {
14055     default: llvm_unreachable("unexpected operator!");
14056     case ISD::SUB: Opcode = X86ISD::SUB; break;
14057     case ISD::XOR: Opcode = X86ISD::XOR; break;
14058     case ISD::AND: Opcode = X86ISD::AND; break;
14059     case ISD::OR: {
14060       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14061         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14062         if (EFLAGS.getNode())
14063           return EFLAGS;
14064       }
14065       Opcode = X86ISD::OR;
14066       break;
14067     }
14068     }
14069
14070     NumOperands = 2;
14071     break;
14072   case X86ISD::ADD:
14073   case X86ISD::SUB:
14074   case X86ISD::INC:
14075   case X86ISD::DEC:
14076   case X86ISD::OR:
14077   case X86ISD::XOR:
14078   case X86ISD::AND:
14079     return SDValue(Op.getNode(), 1);
14080   default:
14081   default_case:
14082     break;
14083   }
14084
14085   // If we found that truncation is beneficial, perform the truncation and
14086   // update 'Op'.
14087   if (NeedTruncation) {
14088     EVT VT = Op.getValueType();
14089     SDValue WideVal = Op->getOperand(0);
14090     EVT WideVT = WideVal.getValueType();
14091     unsigned ConvertedOp = 0;
14092     // Use a target machine opcode to prevent further DAGCombine
14093     // optimizations that may separate the arithmetic operations
14094     // from the setcc node.
14095     switch (WideVal.getOpcode()) {
14096       default: break;
14097       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14098       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14099       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14100       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14101       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14102     }
14103
14104     if (ConvertedOp) {
14105       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14106       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14107         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14108         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14109         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14110       }
14111     }
14112   }
14113
14114   if (Opcode == 0)
14115     // Emit a CMP with 0, which is the TEST pattern.
14116     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14117                        DAG.getConstant(0, dl, Op.getValueType()));
14118
14119   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14120   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14121
14122   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14123   DAG.ReplaceAllUsesWith(Op, New);
14124   return SDValue(New.getNode(), 1);
14125 }
14126
14127 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14128 /// equivalent.
14129 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14130                                    SDLoc dl, SelectionDAG &DAG) const {
14131   if (isNullConstant(Op1))
14132     return EmitTest(Op0, X86CC, dl, DAG);
14133
14134   assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14135          "Unexpected comparison operation for MVT::i1 operands");
14136
14137   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14138        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14139     // Do the comparison at i32 if it's smaller, besides the Atom case.
14140     // This avoids subregister aliasing issues. Keep the smaller reference
14141     // if we're optimizing for size, however, as that'll allow better folding
14142     // of memory operations.
14143     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14144         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14145         !Subtarget->isAtom()) {
14146       unsigned ExtendOp =
14147           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14148       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14149       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14150     }
14151     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14152     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14153     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14154                               Op0, Op1);
14155     return SDValue(Sub.getNode(), 1);
14156   }
14157   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14158 }
14159
14160 /// Convert a comparison if required by the subtarget.
14161 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14162                                                  SelectionDAG &DAG) const {
14163   // If the subtarget does not support the FUCOMI instruction, floating-point
14164   // comparisons have to be converted.
14165   if (Subtarget->hasCMov() ||
14166       Cmp.getOpcode() != X86ISD::CMP ||
14167       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14168       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14169     return Cmp;
14170
14171   // The instruction selector will select an FUCOM instruction instead of
14172   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14173   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14174   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14175   SDLoc dl(Cmp);
14176   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14177   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14178   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14179                             DAG.getConstant(8, dl, MVT::i8));
14180   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14181
14182   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14183   assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14184   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14185 }
14186
14187 /// The minimum architected relative accuracy is 2^-12. We need one
14188 /// Newton-Raphson step to have a good float result (24 bits of precision).
14189 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14190                                             DAGCombinerInfo &DCI,
14191                                             unsigned &RefinementSteps,
14192                                             bool &UseOneConstNR) const {
14193   EVT VT = Op.getValueType();
14194   const char *RecipOp;
14195
14196   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14197   // TODO: Add support for AVX512 (v16f32).
14198   // It is likely not profitable to do this for f64 because a double-precision
14199   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14200   // instructions: convert to single, rsqrtss, convert back to double, refine
14201   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14202   // along with FMA, this could be a throughput win.
14203   if (VT == MVT::f32 && Subtarget->hasSSE1())
14204     RecipOp = "sqrtf";
14205   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14206            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14207     RecipOp = "vec-sqrtf";
14208   else
14209     return SDValue();
14210
14211   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14212   if (!Recips.isEnabled(RecipOp))
14213     return SDValue();
14214
14215   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14216   UseOneConstNR = false;
14217   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14218 }
14219
14220 /// The minimum architected relative accuracy is 2^-12. We need one
14221 /// Newton-Raphson step to have a good float result (24 bits of precision).
14222 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14223                                             DAGCombinerInfo &DCI,
14224                                             unsigned &RefinementSteps) const {
14225   EVT VT = Op.getValueType();
14226   const char *RecipOp;
14227
14228   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14229   // TODO: Add support for AVX512 (v16f32).
14230   // It is likely not profitable to do this for f64 because a double-precision
14231   // reciprocal estimate with refinement on x86 prior to FMA requires
14232   // 15 instructions: convert to single, rcpss, convert back to double, refine
14233   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14234   // along with FMA, this could be a throughput win.
14235   if (VT == MVT::f32 && Subtarget->hasSSE1())
14236     RecipOp = "divf";
14237   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14238            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14239     RecipOp = "vec-divf";
14240   else
14241     return SDValue();
14242
14243   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14244   if (!Recips.isEnabled(RecipOp))
14245     return SDValue();
14246
14247   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14248   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14249 }
14250
14251 /// If we have at least two divisions that use the same divisor, convert to
14252 /// multplication by a reciprocal. This may need to be adjusted for a given
14253 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14254 /// This is because we still need one division to calculate the reciprocal and
14255 /// then we need two multiplies by that reciprocal as replacements for the
14256 /// original divisions.
14257 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14258   return 2;
14259 }
14260
14261 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14262 /// if it's possible.
14263 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14264                                      SDLoc dl, SelectionDAG &DAG) const {
14265   SDValue Op0 = And.getOperand(0);
14266   SDValue Op1 = And.getOperand(1);
14267   if (Op0.getOpcode() == ISD::TRUNCATE)
14268     Op0 = Op0.getOperand(0);
14269   if (Op1.getOpcode() == ISD::TRUNCATE)
14270     Op1 = Op1.getOperand(0);
14271
14272   SDValue LHS, RHS;
14273   if (Op1.getOpcode() == ISD::SHL)
14274     std::swap(Op0, Op1);
14275   if (Op0.getOpcode() == ISD::SHL) {
14276     if (isOneConstant(Op0.getOperand(0))) {
14277         // If we looked past a truncate, check that it's only truncating away
14278         // known zeros.
14279         unsigned BitWidth = Op0.getValueSizeInBits();
14280         unsigned AndBitWidth = And.getValueSizeInBits();
14281         if (BitWidth > AndBitWidth) {
14282           APInt Zeros, Ones;
14283           DAG.computeKnownBits(Op0, Zeros, Ones);
14284           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14285             return SDValue();
14286         }
14287         LHS = Op1;
14288         RHS = Op0.getOperand(1);
14289       }
14290   } else if (Op1.getOpcode() == ISD::Constant) {
14291     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14292     uint64_t AndRHSVal = AndRHS->getZExtValue();
14293     SDValue AndLHS = Op0;
14294
14295     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14296       LHS = AndLHS.getOperand(0);
14297       RHS = AndLHS.getOperand(1);
14298     }
14299
14300     // Use BT if the immediate can't be encoded in a TEST instruction.
14301     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14302       LHS = AndLHS;
14303       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14304     }
14305   }
14306
14307   if (LHS.getNode()) {
14308     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14309     // instruction.  Since the shift amount is in-range-or-undefined, we know
14310     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14311     // the encoding for the i16 version is larger than the i32 version.
14312     // Also promote i16 to i32 for performance / code size reason.
14313     if (LHS.getValueType() == MVT::i8 ||
14314         LHS.getValueType() == MVT::i16)
14315       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14316
14317     // If the operand types disagree, extend the shift amount to match.  Since
14318     // BT ignores high bits (like shifts) we can use anyextend.
14319     if (LHS.getValueType() != RHS.getValueType())
14320       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14321
14322     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14323     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14324     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14325                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14326   }
14327
14328   return SDValue();
14329 }
14330
14331 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14332 /// mask CMPs.
14333 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14334                               SDValue &Op1) {
14335   unsigned SSECC;
14336   bool Swap = false;
14337
14338   // SSE Condition code mapping:
14339   //  0 - EQ
14340   //  1 - LT
14341   //  2 - LE
14342   //  3 - UNORD
14343   //  4 - NEQ
14344   //  5 - NLT
14345   //  6 - NLE
14346   //  7 - ORD
14347   switch (SetCCOpcode) {
14348   default: llvm_unreachable("Unexpected SETCC condition");
14349   case ISD::SETOEQ:
14350   case ISD::SETEQ:  SSECC = 0; break;
14351   case ISD::SETOGT:
14352   case ISD::SETGT:  Swap = true; // Fallthrough
14353   case ISD::SETLT:
14354   case ISD::SETOLT: SSECC = 1; break;
14355   case ISD::SETOGE:
14356   case ISD::SETGE:  Swap = true; // Fallthrough
14357   case ISD::SETLE:
14358   case ISD::SETOLE: SSECC = 2; break;
14359   case ISD::SETUO:  SSECC = 3; break;
14360   case ISD::SETUNE:
14361   case ISD::SETNE:  SSECC = 4; break;
14362   case ISD::SETULE: Swap = true; // Fallthrough
14363   case ISD::SETUGE: SSECC = 5; break;
14364   case ISD::SETULT: Swap = true; // Fallthrough
14365   case ISD::SETUGT: SSECC = 6; break;
14366   case ISD::SETO:   SSECC = 7; break;
14367   case ISD::SETUEQ:
14368   case ISD::SETONE: SSECC = 8; break;
14369   }
14370   if (Swap)
14371     std::swap(Op0, Op1);
14372
14373   return SSECC;
14374 }
14375
14376 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14377 // ones, and then concatenate the result back.
14378 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14379   MVT VT = Op.getSimpleValueType();
14380
14381   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14382          "Unsupported value type for operation");
14383
14384   unsigned NumElems = VT.getVectorNumElements();
14385   SDLoc dl(Op);
14386   SDValue CC = Op.getOperand(2);
14387
14388   // Extract the LHS vectors
14389   SDValue LHS = Op.getOperand(0);
14390   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14391   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14392
14393   // Extract the RHS vectors
14394   SDValue RHS = Op.getOperand(1);
14395   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14396   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14397
14398   // Issue the operation on the smaller types and concatenate the result back
14399   MVT EltVT = VT.getVectorElementType();
14400   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14401   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14402                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14403                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14404 }
14405
14406 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14407   SDValue Op0 = Op.getOperand(0);
14408   SDValue Op1 = Op.getOperand(1);
14409   SDValue CC = Op.getOperand(2);
14410   MVT VT = Op.getSimpleValueType();
14411   SDLoc dl(Op);
14412
14413   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14414          "Unexpected type for boolean compare operation");
14415   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14416   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14417                                DAG.getConstant(-1, dl, VT));
14418   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14419                                DAG.getConstant(-1, dl, VT));
14420   switch (SetCCOpcode) {
14421   default: llvm_unreachable("Unexpected SETCC condition");
14422   case ISD::SETEQ:
14423     // (x == y) -> ~(x ^ y)
14424     return DAG.getNode(ISD::XOR, dl, VT,
14425                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14426                        DAG.getConstant(-1, dl, VT));
14427   case ISD::SETNE:
14428     // (x != y) -> (x ^ y)
14429     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14430   case ISD::SETUGT:
14431   case ISD::SETGT:
14432     // (x > y) -> (x & ~y)
14433     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14434   case ISD::SETULT:
14435   case ISD::SETLT:
14436     // (x < y) -> (~x & y)
14437     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14438   case ISD::SETULE:
14439   case ISD::SETLE:
14440     // (x <= y) -> (~x | y)
14441     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14442   case ISD::SETUGE:
14443   case ISD::SETGE:
14444     // (x >=y) -> (x | ~y)
14445     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14446   }
14447 }
14448
14449 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14450                                      const X86Subtarget *Subtarget) {
14451   SDValue Op0 = Op.getOperand(0);
14452   SDValue Op1 = Op.getOperand(1);
14453   SDValue CC = Op.getOperand(2);
14454   MVT VT = Op.getSimpleValueType();
14455   SDLoc dl(Op);
14456
14457   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14458          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14459          "Cannot set masked compare for this operation");
14460
14461   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14462   unsigned  Opc = 0;
14463   bool Unsigned = false;
14464   bool Swap = false;
14465   unsigned SSECC;
14466   switch (SetCCOpcode) {
14467   default: llvm_unreachable("Unexpected SETCC condition");
14468   case ISD::SETNE:  SSECC = 4; break;
14469   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14470   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14471   case ISD::SETLT:  Swap = true; //fall-through
14472   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14473   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14474   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14475   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14476   case ISD::SETULE: Unsigned = true; //fall-through
14477   case ISD::SETLE:  SSECC = 2; break;
14478   }
14479
14480   if (Swap)
14481     std::swap(Op0, Op1);
14482   if (Opc)
14483     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14484   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14485   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14486                      DAG.getConstant(SSECC, dl, MVT::i8));
14487 }
14488
14489 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14490 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14491 /// return an empty value.
14492 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14493 {
14494   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14495   if (!BV)
14496     return SDValue();
14497
14498   MVT VT = Op1.getSimpleValueType();
14499   MVT EVT = VT.getVectorElementType();
14500   unsigned n = VT.getVectorNumElements();
14501   SmallVector<SDValue, 8> ULTOp1;
14502
14503   for (unsigned i = 0; i < n; ++i) {
14504     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14505     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14506       return SDValue();
14507
14508     // Avoid underflow.
14509     APInt Val = Elt->getAPIntValue();
14510     if (Val == 0)
14511       return SDValue();
14512
14513     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14514   }
14515
14516   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14517 }
14518
14519 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14520                            SelectionDAG &DAG) {
14521   SDValue Op0 = Op.getOperand(0);
14522   SDValue Op1 = Op.getOperand(1);
14523   SDValue CC = Op.getOperand(2);
14524   MVT VT = Op.getSimpleValueType();
14525   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14526   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14527   SDLoc dl(Op);
14528
14529   if (isFP) {
14530 #ifndef NDEBUG
14531     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14532     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14533 #endif
14534
14535     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14536     unsigned Opc = X86ISD::CMPP;
14537     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14538       assert(VT.getVectorNumElements() <= 16);
14539       Opc = X86ISD::CMPM;
14540     }
14541     // In the two special cases we can't handle, emit two comparisons.
14542     if (SSECC == 8) {
14543       unsigned CC0, CC1;
14544       unsigned CombineOpc;
14545       if (SetCCOpcode == ISD::SETUEQ) {
14546         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14547       } else {
14548         assert(SetCCOpcode == ISD::SETONE);
14549         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14550       }
14551
14552       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14553                                  DAG.getConstant(CC0, dl, MVT::i8));
14554       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14555                                  DAG.getConstant(CC1, dl, MVT::i8));
14556       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14557     }
14558     // Handle all other FP comparisons here.
14559     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14560                        DAG.getConstant(SSECC, dl, MVT::i8));
14561   }
14562
14563   MVT VTOp0 = Op0.getSimpleValueType();
14564   assert(VTOp0 == Op1.getSimpleValueType() &&
14565          "Expected operands with same type!");
14566   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14567          "Invalid number of packed elements for source and destination!");
14568
14569   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14570     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14571     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14572     // legalizer firstly checks if the first operand in input to the setcc has
14573     // a legal type. If so, then it promotes the return type to that same type.
14574     // Otherwise, the return type is promoted to the 'next legal type' which,
14575     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14576     //
14577     // We reach this code only if the following two conditions are met:
14578     // 1. Both return type and operand type have been promoted to wider types
14579     //    by the type legalizer.
14580     // 2. The original operand type has been promoted to a 256-bit vector.
14581     //
14582     // Note that condition 2. only applies for AVX targets.
14583     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14584     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14585   }
14586
14587   // The non-AVX512 code below works under the assumption that source and
14588   // destination types are the same.
14589   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14590          "Value types for source and destination must be the same!");
14591
14592   // Break 256-bit integer vector compare into smaller ones.
14593   if (VT.is256BitVector() && !Subtarget->hasInt256())
14594     return Lower256IntVSETCC(Op, DAG);
14595
14596   MVT OpVT = Op1.getSimpleValueType();
14597   if (OpVT.getVectorElementType() == MVT::i1)
14598     return LowerBoolVSETCC_AVX512(Op, DAG);
14599
14600   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14601   if (Subtarget->hasAVX512()) {
14602     if (Op1.getSimpleValueType().is512BitVector() ||
14603         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14604         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14605       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14606
14607     // In AVX-512 architecture setcc returns mask with i1 elements,
14608     // But there is no compare instruction for i8 and i16 elements in KNL.
14609     // We are not talking about 512-bit operands in this case, these
14610     // types are illegal.
14611     if (MaskResult &&
14612         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14613          OpVT.getVectorElementType().getSizeInBits() >= 8))
14614       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14615                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14616   }
14617
14618   // Lower using XOP integer comparisons.
14619   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14620        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14621     // Translate compare code to XOP PCOM compare mode.
14622     unsigned CmpMode = 0;
14623     switch (SetCCOpcode) {
14624     default: llvm_unreachable("Unexpected SETCC condition");
14625     case ISD::SETULT:
14626     case ISD::SETLT: CmpMode = 0x00; break;
14627     case ISD::SETULE:
14628     case ISD::SETLE: CmpMode = 0x01; break;
14629     case ISD::SETUGT:
14630     case ISD::SETGT: CmpMode = 0x02; break;
14631     case ISD::SETUGE:
14632     case ISD::SETGE: CmpMode = 0x03; break;
14633     case ISD::SETEQ: CmpMode = 0x04; break;
14634     case ISD::SETNE: CmpMode = 0x05; break;
14635     }
14636
14637     // Are we comparing unsigned or signed integers?
14638     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14639       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14640
14641     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14642                        DAG.getConstant(CmpMode, dl, MVT::i8));
14643   }
14644
14645   // We are handling one of the integer comparisons here.  Since SSE only has
14646   // GT and EQ comparisons for integer, swapping operands and multiple
14647   // operations may be required for some comparisons.
14648   unsigned Opc;
14649   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14650   bool Subus = false;
14651
14652   switch (SetCCOpcode) {
14653   default: llvm_unreachable("Unexpected SETCC condition");
14654   case ISD::SETNE:  Invert = true;
14655   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14656   case ISD::SETLT:  Swap = true;
14657   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14658   case ISD::SETGE:  Swap = true;
14659   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14660                     Invert = true; break;
14661   case ISD::SETULT: Swap = true;
14662   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14663                     FlipSigns = true; break;
14664   case ISD::SETUGE: Swap = true;
14665   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14666                     FlipSigns = true; Invert = true; break;
14667   }
14668
14669   // Special case: Use min/max operations for SETULE/SETUGE
14670   MVT VET = VT.getVectorElementType();
14671   bool hasMinMax =
14672        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14673     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14674
14675   if (hasMinMax) {
14676     switch (SetCCOpcode) {
14677     default: break;
14678     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14679     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14680     }
14681
14682     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14683   }
14684
14685   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14686   if (!MinMax && hasSubus) {
14687     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14688     // Op0 u<= Op1:
14689     //   t = psubus Op0, Op1
14690     //   pcmpeq t, <0..0>
14691     switch (SetCCOpcode) {
14692     default: break;
14693     case ISD::SETULT: {
14694       // If the comparison is against a constant we can turn this into a
14695       // setule.  With psubus, setule does not require a swap.  This is
14696       // beneficial because the constant in the register is no longer
14697       // destructed as the destination so it can be hoisted out of a loop.
14698       // Only do this pre-AVX since vpcmp* is no longer destructive.
14699       if (Subtarget->hasAVX())
14700         break;
14701       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14702       if (ULEOp1.getNode()) {
14703         Op1 = ULEOp1;
14704         Subus = true; Invert = false; Swap = false;
14705       }
14706       break;
14707     }
14708     // Psubus is better than flip-sign because it requires no inversion.
14709     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14710     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14711     }
14712
14713     if (Subus) {
14714       Opc = X86ISD::SUBUS;
14715       FlipSigns = false;
14716     }
14717   }
14718
14719   if (Swap)
14720     std::swap(Op0, Op1);
14721
14722   // Check that the operation in question is available (most are plain SSE2,
14723   // but PCMPGTQ and PCMPEQQ have different requirements).
14724   if (VT == MVT::v2i64) {
14725     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14726       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14727
14728       // First cast everything to the right type.
14729       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14730       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14731
14732       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14733       // bits of the inputs before performing those operations. The lower
14734       // compare is always unsigned.
14735       SDValue SB;
14736       if (FlipSigns) {
14737         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14738       } else {
14739         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14740         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14741         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14742                          Sign, Zero, Sign, Zero);
14743       }
14744       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14745       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14746
14747       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14748       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14749       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14750
14751       // Create masks for only the low parts/high parts of the 64 bit integers.
14752       static const int MaskHi[] = { 1, 1, 3, 3 };
14753       static const int MaskLo[] = { 0, 0, 2, 2 };
14754       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14755       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14756       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14757
14758       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14759       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14760
14761       if (Invert)
14762         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14763
14764       return DAG.getBitcast(VT, Result);
14765     }
14766
14767     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14768       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14769       // pcmpeqd + pshufd + pand.
14770       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14771
14772       // First cast everything to the right type.
14773       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14774       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14775
14776       // Do the compare.
14777       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14778
14779       // Make sure the lower and upper halves are both all-ones.
14780       static const int Mask[] = { 1, 0, 3, 2 };
14781       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14782       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14783
14784       if (Invert)
14785         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14786
14787       return DAG.getBitcast(VT, Result);
14788     }
14789   }
14790
14791   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14792   // bits of the inputs before performing those operations.
14793   if (FlipSigns) {
14794     MVT EltVT = VT.getVectorElementType();
14795     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14796                                  VT);
14797     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14798     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14799   }
14800
14801   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14802
14803   // If the logical-not of the result is required, perform that now.
14804   if (Invert)
14805     Result = DAG.getNOT(dl, Result, VT);
14806
14807   if (MinMax)
14808     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14809
14810   if (Subus)
14811     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14812                          getZeroVector(VT, Subtarget, DAG, dl));
14813
14814   return Result;
14815 }
14816
14817 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14818
14819   MVT VT = Op.getSimpleValueType();
14820
14821   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14822
14823   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14824          && "SetCC type must be 8-bit or 1-bit integer");
14825   SDValue Op0 = Op.getOperand(0);
14826   SDValue Op1 = Op.getOperand(1);
14827   SDLoc dl(Op);
14828   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14829
14830   // Optimize to BT if possible.
14831   // Lower (X & (1 << N)) == 0 to BT(X, N).
14832   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14833   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14834   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14835       isNullConstant(Op1) &&
14836       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14837     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14838       if (VT == MVT::i1)
14839         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14840       return NewSetCC;
14841     }
14842   }
14843
14844   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14845   // these.
14846   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14847       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14848
14849     // If the input is a setcc, then reuse the input setcc or use a new one with
14850     // the inverted condition.
14851     if (Op0.getOpcode() == X86ISD::SETCC) {
14852       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14853       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14854       if (!Invert)
14855         return Op0;
14856
14857       CCode = X86::GetOppositeBranchCondition(CCode);
14858       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14859                                   DAG.getConstant(CCode, dl, MVT::i8),
14860                                   Op0.getOperand(1));
14861       if (VT == MVT::i1)
14862         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14863       return SetCC;
14864     }
14865   }
14866   if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14867       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14868
14869     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14870     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14871   }
14872
14873   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14874   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14875   if (X86CC == X86::COND_INVALID)
14876     return SDValue();
14877
14878   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14879   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14880   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14881                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14882   if (VT == MVT::i1)
14883     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14884   return SetCC;
14885 }
14886
14887 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14888   SDValue LHS = Op.getOperand(0);
14889   SDValue RHS = Op.getOperand(1);
14890   SDValue Carry = Op.getOperand(2);
14891   SDValue Cond = Op.getOperand(3);
14892   SDLoc DL(Op);
14893
14894   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14895   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14896
14897   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14898   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14899   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14900   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14901                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14902 }
14903
14904 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14905 static bool isX86LogicalCmp(SDValue Op) {
14906   unsigned Opc = Op.getNode()->getOpcode();
14907   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14908       Opc == X86ISD::SAHF)
14909     return true;
14910   if (Op.getResNo() == 1 &&
14911       (Opc == X86ISD::ADD ||
14912        Opc == X86ISD::SUB ||
14913        Opc == X86ISD::ADC ||
14914        Opc == X86ISD::SBB ||
14915        Opc == X86ISD::SMUL ||
14916        Opc == X86ISD::UMUL ||
14917        Opc == X86ISD::INC ||
14918        Opc == X86ISD::DEC ||
14919        Opc == X86ISD::OR ||
14920        Opc == X86ISD::XOR ||
14921        Opc == X86ISD::AND))
14922     return true;
14923
14924   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14925     return true;
14926
14927   return false;
14928 }
14929
14930 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14931   if (V.getOpcode() != ISD::TRUNCATE)
14932     return false;
14933
14934   SDValue VOp0 = V.getOperand(0);
14935   unsigned InBits = VOp0.getValueSizeInBits();
14936   unsigned Bits = V.getValueSizeInBits();
14937   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14938 }
14939
14940 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14941   bool addTest = true;
14942   SDValue Cond  = Op.getOperand(0);
14943   SDValue Op1 = Op.getOperand(1);
14944   SDValue Op2 = Op.getOperand(2);
14945   SDLoc DL(Op);
14946   MVT VT = Op1.getSimpleValueType();
14947   SDValue CC;
14948
14949   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14950   // are available or VBLENDV if AVX is available.
14951   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14952   if (Cond.getOpcode() == ISD::SETCC &&
14953       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14954        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14955       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14956     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14957     int SSECC = translateX86FSETCC(
14958         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14959
14960     if (SSECC != 8) {
14961       if (Subtarget->hasAVX512()) {
14962         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14963                                   DAG.getConstant(SSECC, DL, MVT::i8));
14964         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14965       }
14966
14967       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14968                                 DAG.getConstant(SSECC, DL, MVT::i8));
14969
14970       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14971       // of 3 logic instructions for size savings and potentially speed.
14972       // Unfortunately, there is no scalar form of VBLENDV.
14973
14974       // If either operand is a constant, don't try this. We can expect to
14975       // optimize away at least one of the logic instructions later in that
14976       // case, so that sequence would be faster than a variable blend.
14977
14978       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14979       // uses XMM0 as the selection register. That may need just as many
14980       // instructions as the AND/ANDN/OR sequence due to register moves, so
14981       // don't bother.
14982
14983       if (Subtarget->hasAVX() &&
14984           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14985
14986         // Convert to vectors, do a VSELECT, and convert back to scalar.
14987         // All of the conversions should be optimized away.
14988
14989         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14990         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14991         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14992         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14993
14994         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14995         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14996
14997         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14998
14999         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15000                            VSel, DAG.getIntPtrConstant(0, DL));
15001       }
15002       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15003       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15004       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15005     }
15006   }
15007
15008   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15009     SDValue Op1Scalar;
15010     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15011       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15012     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15013       Op1Scalar = Op1.getOperand(0);
15014     SDValue Op2Scalar;
15015     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15016       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15017     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15018       Op2Scalar = Op2.getOperand(0);
15019     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15020       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15021                                       Op1Scalar.getValueType(),
15022                                       Cond, Op1Scalar, Op2Scalar);
15023       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15024         return DAG.getBitcast(VT, newSelect);
15025       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15026       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15027                          DAG.getIntPtrConstant(0, DL));
15028     }
15029   }
15030
15031   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15032     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15033     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15034                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15035     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15036                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15037     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15038                                     Cond, Op1, Op2);
15039     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15040   }
15041
15042   if (Cond.getOpcode() == ISD::SETCC) {
15043     SDValue NewCond = LowerSETCC(Cond, DAG);
15044     if (NewCond.getNode())
15045       Cond = NewCond;
15046   }
15047
15048   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15049   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15050   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15051   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15052   if (Cond.getOpcode() == X86ISD::SETCC &&
15053       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15054       isNullConstant(Cond.getOperand(1).getOperand(1))) {
15055     SDValue Cmp = Cond.getOperand(1);
15056
15057     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15058
15059     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15060         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15061       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15062
15063       SDValue CmpOp0 = Cmp.getOperand(0);
15064       // Apply further optimizations for special cases
15065       // (select (x != 0), -1, 0) -> neg & sbb
15066       // (select (x == 0), 0, -1) -> neg & sbb
15067       if (isNullConstant(Y) &&
15068             (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15069           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15070           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15071                                     DAG.getConstant(0, DL,
15072                                                     CmpOp0.getValueType()),
15073                                     CmpOp0);
15074           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15075                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
15076                                     SDValue(Neg.getNode(), 1));
15077           return Res;
15078         }
15079
15080       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15081                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15082       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15083
15084       SDValue Res =   // Res = 0 or -1.
15085         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15086                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15087
15088       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15089         Res = DAG.getNOT(DL, Res, Res.getValueType());
15090
15091       if (!isNullConstant(Op2))
15092         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15093       return Res;
15094     }
15095   }
15096
15097   // Look past (and (setcc_carry (cmp ...)), 1).
15098   if (Cond.getOpcode() == ISD::AND &&
15099       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15100       isOneConstant(Cond.getOperand(1)))
15101     Cond = Cond.getOperand(0);
15102
15103   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15104   // setting operand in place of the X86ISD::SETCC.
15105   unsigned CondOpcode = Cond.getOpcode();
15106   if (CondOpcode == X86ISD::SETCC ||
15107       CondOpcode == X86ISD::SETCC_CARRY) {
15108     CC = Cond.getOperand(0);
15109
15110     SDValue Cmp = Cond.getOperand(1);
15111     unsigned Opc = Cmp.getOpcode();
15112     MVT VT = Op.getSimpleValueType();
15113
15114     bool IllegalFPCMov = false;
15115     if (VT.isFloatingPoint() && !VT.isVector() &&
15116         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15117       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15118
15119     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15120         Opc == X86ISD::BT) { // FIXME
15121       Cond = Cmp;
15122       addTest = false;
15123     }
15124   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15125              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15126              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15127               Cond.getOperand(0).getValueType() != MVT::i8)) {
15128     SDValue LHS = Cond.getOperand(0);
15129     SDValue RHS = Cond.getOperand(1);
15130     unsigned X86Opcode;
15131     unsigned X86Cond;
15132     SDVTList VTs;
15133     switch (CondOpcode) {
15134     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15135     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15136     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15137     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15138     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15139     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15140     default: llvm_unreachable("unexpected overflowing operator");
15141     }
15142     if (CondOpcode == ISD::UMULO)
15143       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15144                           MVT::i32);
15145     else
15146       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15147
15148     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15149
15150     if (CondOpcode == ISD::UMULO)
15151       Cond = X86Op.getValue(2);
15152     else
15153       Cond = X86Op.getValue(1);
15154
15155     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15156     addTest = false;
15157   }
15158
15159   if (addTest) {
15160     // Look past the truncate if the high bits are known zero.
15161     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15162       Cond = Cond.getOperand(0);
15163
15164     // We know the result of AND is compared against zero. Try to match
15165     // it to BT.
15166     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15167       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15168         CC = NewSetCC.getOperand(0);
15169         Cond = NewSetCC.getOperand(1);
15170         addTest = false;
15171       }
15172     }
15173   }
15174
15175   if (addTest) {
15176     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15177     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15178   }
15179
15180   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15181   // a <  b ?  0 : -1 -> RES = setcc_carry
15182   // a >= b ? -1 :  0 -> RES = setcc_carry
15183   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15184   if (Cond.getOpcode() == X86ISD::SUB) {
15185     Cond = ConvertCmpIfNecessary(Cond, DAG);
15186     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15187
15188     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15189         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15190         (isNullConstant(Op1) || isNullConstant(Op2))) {
15191       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15192                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15193                                 Cond);
15194       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15195         return DAG.getNOT(DL, Res, Res.getValueType());
15196       return Res;
15197     }
15198   }
15199
15200   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15201   // widen the cmov and push the truncate through. This avoids introducing a new
15202   // branch during isel and doesn't add any extensions.
15203   if (Op.getValueType() == MVT::i8 &&
15204       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15205     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15206     if (T1.getValueType() == T2.getValueType() &&
15207         // Blacklist CopyFromReg to avoid partial register stalls.
15208         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15209       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15210       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15211       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15212     }
15213   }
15214
15215   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15216   // condition is true.
15217   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15218   SDValue Ops[] = { Op2, Op1, CC, Cond };
15219   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15220 }
15221
15222 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15223                                        const X86Subtarget *Subtarget,
15224                                        SelectionDAG &DAG) {
15225   MVT VT = Op->getSimpleValueType(0);
15226   SDValue In = Op->getOperand(0);
15227   MVT InVT = In.getSimpleValueType();
15228   MVT VTElt = VT.getVectorElementType();
15229   MVT InVTElt = InVT.getVectorElementType();
15230   SDLoc dl(Op);
15231
15232   // SKX processor
15233   if ((InVTElt == MVT::i1) &&
15234       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15235         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15236
15237        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15238         VTElt.getSizeInBits() <= 16)) ||
15239
15240        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15241         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15242
15243        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15244         VTElt.getSizeInBits() >= 32))))
15245     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15246
15247   unsigned int NumElts = VT.getVectorNumElements();
15248
15249   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15250     return SDValue();
15251
15252   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15253     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15254       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15255     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15256   }
15257
15258   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15259   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15260   SDValue NegOne =
15261    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15262                    ExtVT);
15263   SDValue Zero =
15264    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15265
15266   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15267   if (VT.is512BitVector())
15268     return V;
15269   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15270 }
15271
15272 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15273                                              const X86Subtarget *Subtarget,
15274                                              SelectionDAG &DAG) {
15275   SDValue In = Op->getOperand(0);
15276   MVT VT = Op->getSimpleValueType(0);
15277   MVT InVT = In.getSimpleValueType();
15278   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15279
15280   MVT InSVT = InVT.getVectorElementType();
15281   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15282
15283   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15284     return SDValue();
15285   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15286     return SDValue();
15287
15288   SDLoc dl(Op);
15289
15290   // SSE41 targets can use the pmovsx* instructions directly.
15291   if (Subtarget->hasSSE41())
15292     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15293
15294   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15295   SDValue Curr = In;
15296   MVT CurrVT = InVT;
15297
15298   // As SRAI is only available on i16/i32 types, we expand only up to i32
15299   // and handle i64 separately.
15300   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15301     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15302     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15303     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15304     Curr = DAG.getBitcast(CurrVT, Curr);
15305   }
15306
15307   SDValue SignExt = Curr;
15308   if (CurrVT != InVT) {
15309     unsigned SignExtShift =
15310         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15311     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15312                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15313   }
15314
15315   if (CurrVT == VT)
15316     return SignExt;
15317
15318   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15319     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15320                                DAG.getConstant(31, dl, MVT::i8));
15321     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15322     return DAG.getBitcast(VT, Ext);
15323   }
15324
15325   return SDValue();
15326 }
15327
15328 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15329                                 SelectionDAG &DAG) {
15330   MVT VT = Op->getSimpleValueType(0);
15331   SDValue In = Op->getOperand(0);
15332   MVT InVT = In.getSimpleValueType();
15333   SDLoc dl(Op);
15334
15335   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15336     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15337
15338   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15339       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15340       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15341     return SDValue();
15342
15343   if (Subtarget->hasInt256())
15344     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15345
15346   // Optimize vectors in AVX mode
15347   // Sign extend  v8i16 to v8i32 and
15348   //              v4i32 to v4i64
15349   //
15350   // Divide input vector into two parts
15351   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15352   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15353   // concat the vectors to original VT
15354
15355   unsigned NumElems = InVT.getVectorNumElements();
15356   SDValue Undef = DAG.getUNDEF(InVT);
15357
15358   SmallVector<int,8> ShufMask1(NumElems, -1);
15359   for (unsigned i = 0; i != NumElems/2; ++i)
15360     ShufMask1[i] = i;
15361
15362   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15363
15364   SmallVector<int,8> ShufMask2(NumElems, -1);
15365   for (unsigned i = 0; i != NumElems/2; ++i)
15366     ShufMask2[i] = i + NumElems/2;
15367
15368   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15369
15370   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15371                                 VT.getVectorNumElements()/2);
15372
15373   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15374   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15375
15376   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15377 }
15378
15379 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15380 // may emit an illegal shuffle but the expansion is still better than scalar
15381 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15382 // we'll emit a shuffle and a arithmetic shift.
15383 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15384 // TODO: It is possible to support ZExt by zeroing the undef values during
15385 // the shuffle phase or after the shuffle.
15386 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15387                                  SelectionDAG &DAG) {
15388   MVT RegVT = Op.getSimpleValueType();
15389   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15390   assert(RegVT.isInteger() &&
15391          "We only custom lower integer vector sext loads.");
15392
15393   // Nothing useful we can do without SSE2 shuffles.
15394   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15395
15396   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15397   SDLoc dl(Ld);
15398   EVT MemVT = Ld->getMemoryVT();
15399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15400   unsigned RegSz = RegVT.getSizeInBits();
15401
15402   ISD::LoadExtType Ext = Ld->getExtensionType();
15403
15404   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15405          && "Only anyext and sext are currently implemented.");
15406   assert(MemVT != RegVT && "Cannot extend to the same type");
15407   assert(MemVT.isVector() && "Must load a vector from memory");
15408
15409   unsigned NumElems = RegVT.getVectorNumElements();
15410   unsigned MemSz = MemVT.getSizeInBits();
15411   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15412
15413   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15414     // The only way in which we have a legal 256-bit vector result but not the
15415     // integer 256-bit operations needed to directly lower a sextload is if we
15416     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15417     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15418     // correctly legalized. We do this late to allow the canonical form of
15419     // sextload to persist throughout the rest of the DAG combiner -- it wants
15420     // to fold together any extensions it can, and so will fuse a sign_extend
15421     // of an sextload into a sextload targeting a wider value.
15422     SDValue Load;
15423     if (MemSz == 128) {
15424       // Just switch this to a normal load.
15425       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15426                                        "it must be a legal 128-bit vector "
15427                                        "type!");
15428       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15429                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15430                   Ld->isInvariant(), Ld->getAlignment());
15431     } else {
15432       assert(MemSz < 128 &&
15433              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15434       // Do an sext load to a 128-bit vector type. We want to use the same
15435       // number of elements, but elements half as wide. This will end up being
15436       // recursively lowered by this routine, but will succeed as we definitely
15437       // have all the necessary features if we're using AVX1.
15438       EVT HalfEltVT =
15439           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15440       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15441       Load =
15442           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15443                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15444                          Ld->isNonTemporal(), Ld->isInvariant(),
15445                          Ld->getAlignment());
15446     }
15447
15448     // Replace chain users with the new chain.
15449     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15450     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15451
15452     // Finally, do a normal sign-extend to the desired register.
15453     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15454   }
15455
15456   // All sizes must be a power of two.
15457   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15458          "Non-power-of-two elements are not custom lowered!");
15459
15460   // Attempt to load the original value using scalar loads.
15461   // Find the largest scalar type that divides the total loaded size.
15462   MVT SclrLoadTy = MVT::i8;
15463   for (MVT Tp : MVT::integer_valuetypes()) {
15464     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15465       SclrLoadTy = Tp;
15466     }
15467   }
15468
15469   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15470   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15471       (64 <= MemSz))
15472     SclrLoadTy = MVT::f64;
15473
15474   // Calculate the number of scalar loads that we need to perform
15475   // in order to load our vector from memory.
15476   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15477
15478   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15479          "Can only lower sext loads with a single scalar load!");
15480
15481   unsigned loadRegZize = RegSz;
15482   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15483     loadRegZize = 128;
15484
15485   // Represent our vector as a sequence of elements which are the
15486   // largest scalar that we can load.
15487   EVT LoadUnitVecVT = EVT::getVectorVT(
15488       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15489
15490   // Represent the data using the same element type that is stored in
15491   // memory. In practice, we ''widen'' MemVT.
15492   EVT WideVecVT =
15493       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15494                        loadRegZize / MemVT.getScalarSizeInBits());
15495
15496   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15497          "Invalid vector type");
15498
15499   // We can't shuffle using an illegal type.
15500   assert(TLI.isTypeLegal(WideVecVT) &&
15501          "We only lower types that form legal widened vector types");
15502
15503   SmallVector<SDValue, 8> Chains;
15504   SDValue Ptr = Ld->getBasePtr();
15505   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15506                                       TLI.getPointerTy(DAG.getDataLayout()));
15507   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15508
15509   for (unsigned i = 0; i < NumLoads; ++i) {
15510     // Perform a single load.
15511     SDValue ScalarLoad =
15512         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15513                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15514                     Ld->getAlignment());
15515     Chains.push_back(ScalarLoad.getValue(1));
15516     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15517     // another round of DAGCombining.
15518     if (i == 0)
15519       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15520     else
15521       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15522                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15523
15524     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15525   }
15526
15527   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15528
15529   // Bitcast the loaded value to a vector of the original element type, in
15530   // the size of the target vector type.
15531   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15532   unsigned SizeRatio = RegSz / MemSz;
15533
15534   if (Ext == ISD::SEXTLOAD) {
15535     // If we have SSE4.1, we can directly emit a VSEXT node.
15536     if (Subtarget->hasSSE41()) {
15537       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15538       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15539       return Sext;
15540     }
15541
15542     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15543     // lanes.
15544     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15545            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15546
15547     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15548     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15549     return Shuff;
15550   }
15551
15552   // Redistribute the loaded elements into the different locations.
15553   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15554   for (unsigned i = 0; i != NumElems; ++i)
15555     ShuffleVec[i * SizeRatio] = i;
15556
15557   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15558                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15559
15560   // Bitcast to the requested type.
15561   Shuff = DAG.getBitcast(RegVT, Shuff);
15562   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15563   return Shuff;
15564 }
15565
15566 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15567 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15568 // from the AND / OR.
15569 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15570   Opc = Op.getOpcode();
15571   if (Opc != ISD::OR && Opc != ISD::AND)
15572     return false;
15573   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15574           Op.getOperand(0).hasOneUse() &&
15575           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15576           Op.getOperand(1).hasOneUse());
15577 }
15578
15579 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15580 // 1 and that the SETCC node has a single use.
15581 static bool isXor1OfSetCC(SDValue Op) {
15582   if (Op.getOpcode() != ISD::XOR)
15583     return false;
15584   if (isOneConstant(Op.getOperand(1)))
15585     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15586            Op.getOperand(0).hasOneUse();
15587   return false;
15588 }
15589
15590 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15591   bool addTest = true;
15592   SDValue Chain = Op.getOperand(0);
15593   SDValue Cond  = Op.getOperand(1);
15594   SDValue Dest  = Op.getOperand(2);
15595   SDLoc dl(Op);
15596   SDValue CC;
15597   bool Inverted = false;
15598
15599   if (Cond.getOpcode() == ISD::SETCC) {
15600     // Check for setcc([su]{add,sub,mul}o == 0).
15601     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15602         isNullConstant(Cond.getOperand(1)) &&
15603         Cond.getOperand(0).getResNo() == 1 &&
15604         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15605          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15606          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15607          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15608          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15609          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15610       Inverted = true;
15611       Cond = Cond.getOperand(0);
15612     } else {
15613       SDValue NewCond = LowerSETCC(Cond, DAG);
15614       if (NewCond.getNode())
15615         Cond = NewCond;
15616     }
15617   }
15618 #if 0
15619   // FIXME: LowerXALUO doesn't handle these!!
15620   else if (Cond.getOpcode() == X86ISD::ADD  ||
15621            Cond.getOpcode() == X86ISD::SUB  ||
15622            Cond.getOpcode() == X86ISD::SMUL ||
15623            Cond.getOpcode() == X86ISD::UMUL)
15624     Cond = LowerXALUO(Cond, DAG);
15625 #endif
15626
15627   // Look pass (and (setcc_carry (cmp ...)), 1).
15628   if (Cond.getOpcode() == ISD::AND &&
15629       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15630       isOneConstant(Cond.getOperand(1)))
15631     Cond = Cond.getOperand(0);
15632
15633   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15634   // setting operand in place of the X86ISD::SETCC.
15635   unsigned CondOpcode = Cond.getOpcode();
15636   if (CondOpcode == X86ISD::SETCC ||
15637       CondOpcode == X86ISD::SETCC_CARRY) {
15638     CC = Cond.getOperand(0);
15639
15640     SDValue Cmp = Cond.getOperand(1);
15641     unsigned Opc = Cmp.getOpcode();
15642     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15643     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15644       Cond = Cmp;
15645       addTest = false;
15646     } else {
15647       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15648       default: break;
15649       case X86::COND_O:
15650       case X86::COND_B:
15651         // These can only come from an arithmetic instruction with overflow,
15652         // e.g. SADDO, UADDO.
15653         Cond = Cond.getNode()->getOperand(1);
15654         addTest = false;
15655         break;
15656       }
15657     }
15658   }
15659   CondOpcode = Cond.getOpcode();
15660   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15661       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15662       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15663        Cond.getOperand(0).getValueType() != MVT::i8)) {
15664     SDValue LHS = Cond.getOperand(0);
15665     SDValue RHS = Cond.getOperand(1);
15666     unsigned X86Opcode;
15667     unsigned X86Cond;
15668     SDVTList VTs;
15669     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15670     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15671     // X86ISD::INC).
15672     switch (CondOpcode) {
15673     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15674     case ISD::SADDO:
15675       if (isOneConstant(RHS)) {
15676           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15677           break;
15678         }
15679       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15680     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15681     case ISD::SSUBO:
15682       if (isOneConstant(RHS)) {
15683           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15684           break;
15685         }
15686       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15687     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15688     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15689     default: llvm_unreachable("unexpected overflowing operator");
15690     }
15691     if (Inverted)
15692       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15693     if (CondOpcode == ISD::UMULO)
15694       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15695                           MVT::i32);
15696     else
15697       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15698
15699     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15700
15701     if (CondOpcode == ISD::UMULO)
15702       Cond = X86Op.getValue(2);
15703     else
15704       Cond = X86Op.getValue(1);
15705
15706     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15707     addTest = false;
15708   } else {
15709     unsigned CondOpc;
15710     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15711       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15712       if (CondOpc == ISD::OR) {
15713         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15714         // two branches instead of an explicit OR instruction with a
15715         // separate test.
15716         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15717             isX86LogicalCmp(Cmp)) {
15718           CC = Cond.getOperand(0).getOperand(0);
15719           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15720                               Chain, Dest, CC, Cmp);
15721           CC = Cond.getOperand(1).getOperand(0);
15722           Cond = Cmp;
15723           addTest = false;
15724         }
15725       } else { // ISD::AND
15726         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15727         // two branches instead of an explicit AND instruction with a
15728         // separate test. However, we only do this if this block doesn't
15729         // have a fall-through edge, because this requires an explicit
15730         // jmp when the condition is false.
15731         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15732             isX86LogicalCmp(Cmp) &&
15733             Op.getNode()->hasOneUse()) {
15734           X86::CondCode CCode =
15735             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15736           CCode = X86::GetOppositeBranchCondition(CCode);
15737           CC = DAG.getConstant(CCode, dl, MVT::i8);
15738           SDNode *User = *Op.getNode()->use_begin();
15739           // Look for an unconditional branch following this conditional branch.
15740           // We need this because we need to reverse the successors in order
15741           // to implement FCMP_OEQ.
15742           if (User->getOpcode() == ISD::BR) {
15743             SDValue FalseBB = User->getOperand(1);
15744             SDNode *NewBR =
15745               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15746             assert(NewBR == User);
15747             (void)NewBR;
15748             Dest = FalseBB;
15749
15750             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15751                                 Chain, Dest, CC, Cmp);
15752             X86::CondCode CCode =
15753               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15754             CCode = X86::GetOppositeBranchCondition(CCode);
15755             CC = DAG.getConstant(CCode, dl, MVT::i8);
15756             Cond = Cmp;
15757             addTest = false;
15758           }
15759         }
15760       }
15761     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15762       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15763       // It should be transformed during dag combiner except when the condition
15764       // is set by a arithmetics with overflow node.
15765       X86::CondCode CCode =
15766         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15767       CCode = X86::GetOppositeBranchCondition(CCode);
15768       CC = DAG.getConstant(CCode, dl, MVT::i8);
15769       Cond = Cond.getOperand(0).getOperand(1);
15770       addTest = false;
15771     } else if (Cond.getOpcode() == ISD::SETCC &&
15772                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15773       // For FCMP_OEQ, we can emit
15774       // two branches instead of an explicit AND instruction with a
15775       // separate test. However, we only do this if this block doesn't
15776       // have a fall-through edge, because this requires an explicit
15777       // jmp when the condition is false.
15778       if (Op.getNode()->hasOneUse()) {
15779         SDNode *User = *Op.getNode()->use_begin();
15780         // Look for an unconditional branch following this conditional branch.
15781         // We need this because we need to reverse the successors in order
15782         // to implement FCMP_OEQ.
15783         if (User->getOpcode() == ISD::BR) {
15784           SDValue FalseBB = User->getOperand(1);
15785           SDNode *NewBR =
15786             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15787           assert(NewBR == User);
15788           (void)NewBR;
15789           Dest = FalseBB;
15790
15791           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15792                                     Cond.getOperand(0), Cond.getOperand(1));
15793           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15794           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15795           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15796                               Chain, Dest, CC, Cmp);
15797           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15798           Cond = Cmp;
15799           addTest = false;
15800         }
15801       }
15802     } else if (Cond.getOpcode() == ISD::SETCC &&
15803                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15804       // For FCMP_UNE, we can emit
15805       // two branches instead of an explicit AND instruction with a
15806       // separate test. However, we only do this if this block doesn't
15807       // have a fall-through edge, because this requires an explicit
15808       // jmp when the condition is false.
15809       if (Op.getNode()->hasOneUse()) {
15810         SDNode *User = *Op.getNode()->use_begin();
15811         // Look for an unconditional branch following this conditional branch.
15812         // We need this because we need to reverse the successors in order
15813         // to implement FCMP_UNE.
15814         if (User->getOpcode() == ISD::BR) {
15815           SDValue FalseBB = User->getOperand(1);
15816           SDNode *NewBR =
15817             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15818           assert(NewBR == User);
15819           (void)NewBR;
15820
15821           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15822                                     Cond.getOperand(0), Cond.getOperand(1));
15823           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15824           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15825           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15826                               Chain, Dest, CC, Cmp);
15827           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15828           Cond = Cmp;
15829           addTest = false;
15830           Dest = FalseBB;
15831         }
15832       }
15833     }
15834   }
15835
15836   if (addTest) {
15837     // Look pass the truncate if the high bits are known zero.
15838     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15839         Cond = Cond.getOperand(0);
15840
15841     // We know the result of AND is compared against zero. Try to match
15842     // it to BT.
15843     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15844       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15845         CC = NewSetCC.getOperand(0);
15846         Cond = NewSetCC.getOperand(1);
15847         addTest = false;
15848       }
15849     }
15850   }
15851
15852   if (addTest) {
15853     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15854     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15855     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15856   }
15857   Cond = ConvertCmpIfNecessary(Cond, DAG);
15858   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15859                      Chain, Dest, CC, Cond);
15860 }
15861
15862 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15863 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15864 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15865 // that the guard pages used by the OS virtual memory manager are allocated in
15866 // correct sequence.
15867 SDValue
15868 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15869                                            SelectionDAG &DAG) const {
15870   MachineFunction &MF = DAG.getMachineFunction();
15871   bool SplitStack = MF.shouldSplitStack();
15872   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15873                SplitStack;
15874   SDLoc dl(Op);
15875
15876   // Get the inputs.
15877   SDNode *Node = Op.getNode();
15878   SDValue Chain = Op.getOperand(0);
15879   SDValue Size  = Op.getOperand(1);
15880   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15881   EVT VT = Node->getValueType(0);
15882
15883   // Chain the dynamic stack allocation so that it doesn't modify the stack
15884   // pointer when other instructions are using the stack.
15885   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15886
15887   bool Is64Bit = Subtarget->is64Bit();
15888   MVT SPTy = getPointerTy(DAG.getDataLayout());
15889
15890   SDValue Result;
15891   if (!Lower) {
15892     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15893     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15894     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15895                     " not tell us which reg is the stack pointer!");
15896     EVT VT = Node->getValueType(0);
15897     SDValue Tmp3 = Node->getOperand(2);
15898
15899     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15900     Chain = SP.getValue(1);
15901     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15902     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15903     unsigned StackAlign = TFI.getStackAlignment();
15904     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15905     if (Align > StackAlign)
15906       Result = DAG.getNode(ISD::AND, dl, VT, Result,
15907                          DAG.getConstant(-(uint64_t)Align, dl, VT));
15908     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15909   } else if (SplitStack) {
15910     MachineRegisterInfo &MRI = MF.getRegInfo();
15911
15912     if (Is64Bit) {
15913       // The 64 bit implementation of segmented stacks needs to clobber both r10
15914       // r11. This makes it impossible to use it along with nested parameters.
15915       const Function *F = MF.getFunction();
15916
15917       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15918            I != E; ++I)
15919         if (I->hasNestAttr())
15920           report_fatal_error("Cannot use segmented stacks with functions that "
15921                              "have nested arguments.");
15922     }
15923
15924     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15925     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15926     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15927     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15928                                 DAG.getRegister(Vreg, SPTy));
15929   } else {
15930     SDValue Flag;
15931     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15932
15933     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15934     Flag = Chain.getValue(1);
15935     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15936
15937     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15938
15939     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15940     unsigned SPReg = RegInfo->getStackRegister();
15941     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15942     Chain = SP.getValue(1);
15943
15944     if (Align) {
15945       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15946                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15947       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15948     }
15949
15950     Result = SP;
15951   }
15952
15953   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15954                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
15955
15956   SDValue Ops[2] = {Result, Chain};
15957   return DAG.getMergeValues(Ops, dl);
15958 }
15959
15960 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15961   MachineFunction &MF = DAG.getMachineFunction();
15962   auto PtrVT = getPointerTy(MF.getDataLayout());
15963   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15964
15965   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15966   SDLoc DL(Op);
15967
15968   if (!Subtarget->is64Bit() ||
15969       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15970     // vastart just stores the address of the VarArgsFrameIndex slot into the
15971     // memory location argument.
15972     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15973     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15974                         MachinePointerInfo(SV), false, false, 0);
15975   }
15976
15977   // __va_list_tag:
15978   //   gp_offset         (0 - 6 * 8)
15979   //   fp_offset         (48 - 48 + 8 * 16)
15980   //   overflow_arg_area (point to parameters coming in memory).
15981   //   reg_save_area
15982   SmallVector<SDValue, 8> MemOps;
15983   SDValue FIN = Op.getOperand(1);
15984   // Store gp_offset
15985   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15986                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15987                                                DL, MVT::i32),
15988                                FIN, MachinePointerInfo(SV), false, false, 0);
15989   MemOps.push_back(Store);
15990
15991   // Store fp_offset
15992   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15993   Store = DAG.getStore(Op.getOperand(0), DL,
15994                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15995                                        MVT::i32),
15996                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15997   MemOps.push_back(Store);
15998
15999   // Store ptr to overflow_arg_area
16000   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16001   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16002   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16003                        MachinePointerInfo(SV, 8),
16004                        false, false, 0);
16005   MemOps.push_back(Store);
16006
16007   // Store ptr to reg_save_area.
16008   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16009       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16010   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16011   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16012       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16013   MemOps.push_back(Store);
16014   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16015 }
16016
16017 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16018   assert(Subtarget->is64Bit() &&
16019          "LowerVAARG only handles 64-bit va_arg!");
16020   assert(Op.getNode()->getNumOperands() == 4);
16021
16022   MachineFunction &MF = DAG.getMachineFunction();
16023   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16024     // The Win64 ABI uses char* instead of a structure.
16025     return DAG.expandVAArg(Op.getNode());
16026
16027   SDValue Chain = Op.getOperand(0);
16028   SDValue SrcPtr = Op.getOperand(1);
16029   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16030   unsigned Align = Op.getConstantOperandVal(3);
16031   SDLoc dl(Op);
16032
16033   EVT ArgVT = Op.getNode()->getValueType(0);
16034   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16035   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16036   uint8_t ArgMode;
16037
16038   // Decide which area this value should be read from.
16039   // TODO: Implement the AMD64 ABI in its entirety. This simple
16040   // selection mechanism works only for the basic types.
16041   if (ArgVT == MVT::f80) {
16042     llvm_unreachable("va_arg for f80 not yet implemented");
16043   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16044     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16045   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16046     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16047   } else {
16048     llvm_unreachable("Unhandled argument type in LowerVAARG");
16049   }
16050
16051   if (ArgMode == 2) {
16052     // Sanity Check: Make sure using fp_offset makes sense.
16053     assert(!Subtarget->useSoftFloat() &&
16054            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16055            Subtarget->hasSSE1());
16056   }
16057
16058   // Insert VAARG_64 node into the DAG
16059   // VAARG_64 returns two values: Variable Argument Address, Chain
16060   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16061                        DAG.getConstant(ArgMode, dl, MVT::i8),
16062                        DAG.getConstant(Align, dl, MVT::i32)};
16063   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16064   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16065                                           VTs, InstOps, MVT::i64,
16066                                           MachinePointerInfo(SV),
16067                                           /*Align=*/0,
16068                                           /*Volatile=*/false,
16069                                           /*ReadMem=*/true,
16070                                           /*WriteMem=*/true);
16071   Chain = VAARG.getValue(1);
16072
16073   // Load the next argument and return it
16074   return DAG.getLoad(ArgVT, dl,
16075                      Chain,
16076                      VAARG,
16077                      MachinePointerInfo(),
16078                      false, false, false, 0);
16079 }
16080
16081 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16082                            SelectionDAG &DAG) {
16083   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16084   // where a va_list is still an i8*.
16085   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16086   if (Subtarget->isCallingConvWin64(
16087         DAG.getMachineFunction().getFunction()->getCallingConv()))
16088     // Probably a Win64 va_copy.
16089     return DAG.expandVACopy(Op.getNode());
16090
16091   SDValue Chain = Op.getOperand(0);
16092   SDValue DstPtr = Op.getOperand(1);
16093   SDValue SrcPtr = Op.getOperand(2);
16094   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16095   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16096   SDLoc DL(Op);
16097
16098   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16099                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16100                        false, false,
16101                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16102 }
16103
16104 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16105 // amount is a constant. Takes immediate version of shift as input.
16106 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16107                                           SDValue SrcOp, uint64_t ShiftAmt,
16108                                           SelectionDAG &DAG) {
16109   MVT ElementType = VT.getVectorElementType();
16110
16111   // Fold this packed shift into its first operand if ShiftAmt is 0.
16112   if (ShiftAmt == 0)
16113     return SrcOp;
16114
16115   // Check for ShiftAmt >= element width
16116   if (ShiftAmt >= ElementType.getSizeInBits()) {
16117     if (Opc == X86ISD::VSRAI)
16118       ShiftAmt = ElementType.getSizeInBits() - 1;
16119     else
16120       return DAG.getConstant(0, dl, VT);
16121   }
16122
16123   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16124          && "Unknown target vector shift-by-constant node");
16125
16126   // Fold this packed vector shift into a build vector if SrcOp is a
16127   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16128   if (VT == SrcOp.getSimpleValueType() &&
16129       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16130     SmallVector<SDValue, 8> Elts;
16131     unsigned NumElts = SrcOp->getNumOperands();
16132     ConstantSDNode *ND;
16133
16134     switch(Opc) {
16135     default: llvm_unreachable(nullptr);
16136     case X86ISD::VSHLI:
16137       for (unsigned i=0; i!=NumElts; ++i) {
16138         SDValue CurrentOp = SrcOp->getOperand(i);
16139         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16140           Elts.push_back(CurrentOp);
16141           continue;
16142         }
16143         ND = cast<ConstantSDNode>(CurrentOp);
16144         const APInt &C = ND->getAPIntValue();
16145         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16146       }
16147       break;
16148     case X86ISD::VSRLI:
16149       for (unsigned i=0; i!=NumElts; ++i) {
16150         SDValue CurrentOp = SrcOp->getOperand(i);
16151         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16152           Elts.push_back(CurrentOp);
16153           continue;
16154         }
16155         ND = cast<ConstantSDNode>(CurrentOp);
16156         const APInt &C = ND->getAPIntValue();
16157         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16158       }
16159       break;
16160     case X86ISD::VSRAI:
16161       for (unsigned i=0; i!=NumElts; ++i) {
16162         SDValue CurrentOp = SrcOp->getOperand(i);
16163         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16164           Elts.push_back(CurrentOp);
16165           continue;
16166         }
16167         ND = cast<ConstantSDNode>(CurrentOp);
16168         const APInt &C = ND->getAPIntValue();
16169         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16170       }
16171       break;
16172     }
16173
16174     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16175   }
16176
16177   return DAG.getNode(Opc, dl, VT, SrcOp,
16178                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
16179 }
16180
16181 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16182 // may or may not be a constant. Takes immediate version of shift as input.
16183 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16184                                    SDValue SrcOp, SDValue ShAmt,
16185                                    SelectionDAG &DAG) {
16186   MVT SVT = ShAmt.getSimpleValueType();
16187   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16188
16189   // Catch shift-by-constant.
16190   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16191     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16192                                       CShAmt->getZExtValue(), DAG);
16193
16194   // Change opcode to non-immediate version
16195   switch (Opc) {
16196     default: llvm_unreachable("Unknown target vector shift node");
16197     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16198     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16199     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16200   }
16201
16202   const X86Subtarget &Subtarget =
16203       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16204   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16205       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16206     // Let the shuffle legalizer expand this shift amount node.
16207     SDValue Op0 = ShAmt.getOperand(0);
16208     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16209     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16210   } else {
16211     // Need to build a vector containing shift amount.
16212     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16213     SmallVector<SDValue, 4> ShOps;
16214     ShOps.push_back(ShAmt);
16215     if (SVT == MVT::i32) {
16216       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16217       ShOps.push_back(DAG.getUNDEF(SVT));
16218     }
16219     ShOps.push_back(DAG.getUNDEF(SVT));
16220
16221     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16222     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16223   }
16224
16225   // The return type has to be a 128-bit type with the same element
16226   // type as the input type.
16227   MVT EltVT = VT.getVectorElementType();
16228   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16229
16230   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16231   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16232 }
16233
16234 /// \brief Return Mask with the necessary casting or extending
16235 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16236 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16237                            const X86Subtarget *Subtarget,
16238                            SelectionDAG &DAG, SDLoc dl) {
16239
16240   if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16241     // Mask should be extended
16242     Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16243                        MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16244   }
16245
16246   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16247     if (MaskVT == MVT::v64i1) {
16248       assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16249       // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16250       SDValue Lo, Hi;
16251       Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16252                           DAG.getConstant(0, dl, MVT::i32));
16253       Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16254                           DAG.getConstant(1, dl, MVT::i32));
16255
16256       Lo = DAG.getBitcast(MVT::v32i1, Lo);
16257       Hi = DAG.getBitcast(MVT::v32i1, Hi);
16258
16259       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16260     } else {
16261       // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16262       // and bitcast.
16263       MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16264       return DAG.getBitcast(MaskVT,
16265                             DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16266     }
16267
16268   } else {
16269     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16270                                      Mask.getSimpleValueType().getSizeInBits());
16271     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16272     // are extracted by EXTRACT_SUBVECTOR.
16273     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16274                        DAG.getBitcast(BitcastVT, Mask),
16275                        DAG.getIntPtrConstant(0, dl));
16276   }
16277 }
16278
16279 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16280 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16281 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16282 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16283                   SDValue PreservedSrc,
16284                   const X86Subtarget *Subtarget,
16285                   SelectionDAG &DAG) {
16286   MVT VT = Op.getSimpleValueType();
16287   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16288   unsigned OpcodeSelect = ISD::VSELECT;
16289   SDLoc dl(Op);
16290
16291   if (isAllOnesConstant(Mask))
16292     return Op;
16293
16294   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16295
16296   switch (Op.getOpcode()) {
16297   default: break;
16298   case X86ISD::PCMPEQM:
16299   case X86ISD::PCMPGTM:
16300   case X86ISD::CMPM:
16301   case X86ISD::CMPMU:
16302     return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16303   case X86ISD::VFPCLASS:
16304     case X86ISD::VFPCLASSS:
16305     return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16306   case X86ISD::VTRUNC:
16307   case X86ISD::VTRUNCS:
16308   case X86ISD::VTRUNCUS:
16309     // We can't use ISD::VSELECT here because it is not always "Legal"
16310     // for the destination type. For example vpmovqb require only AVX512
16311     // and vselect that can operate on byte element type require BWI
16312     OpcodeSelect = X86ISD::SELECT;
16313     break;
16314   }
16315   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16316     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16317   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16318 }
16319
16320 /// \brief Creates an SDNode for a predicated scalar operation.
16321 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16322 /// The mask is coming as MVT::i8 and it should be truncated
16323 /// to MVT::i1 while lowering masking intrinsics.
16324 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16325 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16326 /// for a scalar instruction.
16327 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16328                                     SDValue PreservedSrc,
16329                                     const X86Subtarget *Subtarget,
16330                                     SelectionDAG &DAG) {
16331   if (isAllOnesConstant(Mask))
16332     return Op;
16333
16334   MVT VT = Op.getSimpleValueType();
16335   SDLoc dl(Op);
16336   // The mask should be of type MVT::i1
16337   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16338
16339   if (Op.getOpcode() == X86ISD::FSETCC)
16340     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16341   if (Op.getOpcode() == X86ISD::VFPCLASS ||
16342       Op.getOpcode() == X86ISD::VFPCLASSS)
16343     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16344
16345   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16346     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16347   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16348 }
16349
16350 static int getSEHRegistrationNodeSize(const Function *Fn) {
16351   if (!Fn->hasPersonalityFn())
16352     report_fatal_error(
16353         "querying registration node size for function without personality");
16354   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16355   // WinEHStatePass for the full struct definition.
16356   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16357   case EHPersonality::MSVC_X86SEH: return 24;
16358   case EHPersonality::MSVC_CXX: return 16;
16359   default: break;
16360   }
16361   report_fatal_error(
16362       "can only recover FP for 32-bit MSVC EH personality functions");
16363 }
16364
16365 /// When the MSVC runtime transfers control to us, either to an outlined
16366 /// function or when returning to a parent frame after catching an exception, we
16367 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16368 /// Here's the math:
16369 ///   RegNodeBase = EntryEBP - RegNodeSize
16370 ///   ParentFP = RegNodeBase - ParentFrameOffset
16371 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16372 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16373 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16374                                    SDValue EntryEBP) {
16375   MachineFunction &MF = DAG.getMachineFunction();
16376   SDLoc dl;
16377
16378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16379   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16380
16381   // It's possible that the parent function no longer has a personality function
16382   // if the exceptional code was optimized away, in which case we just return
16383   // the incoming EBP.
16384   if (!Fn->hasPersonalityFn())
16385     return EntryEBP;
16386
16387   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16388   // registration, or the .set_setframe offset.
16389   MCSymbol *OffsetSym =
16390       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16391           GlobalValue::getRealLinkageName(Fn->getName()));
16392   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16393   SDValue ParentFrameOffset =
16394       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16395
16396   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16397   // prologue to RBP in the parent function.
16398   const X86Subtarget &Subtarget =
16399       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16400   if (Subtarget.is64Bit())
16401     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16402
16403   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16404   // RegNodeBase = EntryEBP - RegNodeSize
16405   // ParentFP = RegNodeBase - ParentFrameOffset
16406   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16407                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16408   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16409 }
16410
16411 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16412                                        SelectionDAG &DAG) {
16413   SDLoc dl(Op);
16414   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16415   MVT VT = Op.getSimpleValueType();
16416   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16417   if (IntrData) {
16418     switch(IntrData->Type) {
16419     case INTR_TYPE_1OP:
16420       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16421     case INTR_TYPE_2OP:
16422       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16423         Op.getOperand(2));
16424     case INTR_TYPE_2OP_IMM8:
16425       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16426                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16427     case INTR_TYPE_3OP:
16428       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16429         Op.getOperand(2), Op.getOperand(3));
16430     case INTR_TYPE_4OP:
16431       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16432         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16433     case INTR_TYPE_1OP_MASK_RM: {
16434       SDValue Src = Op.getOperand(1);
16435       SDValue PassThru = Op.getOperand(2);
16436       SDValue Mask = Op.getOperand(3);
16437       SDValue RoundingMode;
16438       // We allways add rounding mode to the Node.
16439       // If the rounding mode is not specified, we add the
16440       // "current direction" mode.
16441       if (Op.getNumOperands() == 4)
16442         RoundingMode =
16443           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16444       else
16445         RoundingMode = Op.getOperand(4);
16446       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16447       if (IntrWithRoundingModeOpcode != 0)
16448         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16449             X86::STATIC_ROUNDING::CUR_DIRECTION)
16450           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16451                                       dl, Op.getValueType(), Src, RoundingMode),
16452                                       Mask, PassThru, Subtarget, DAG);
16453       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16454                                               RoundingMode),
16455                                   Mask, PassThru, Subtarget, DAG);
16456     }
16457     case INTR_TYPE_1OP_MASK: {
16458       SDValue Src = Op.getOperand(1);
16459       SDValue PassThru = Op.getOperand(2);
16460       SDValue Mask = Op.getOperand(3);
16461       // We add rounding mode to the Node when
16462       //   - RM Opcode is specified and
16463       //   - RM is not "current direction".
16464       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16465       if (IntrWithRoundingModeOpcode != 0) {
16466         SDValue Rnd = Op.getOperand(4);
16467         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16468         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16469           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16470                                       dl, Op.getValueType(),
16471                                       Src, Rnd),
16472                                       Mask, PassThru, Subtarget, DAG);
16473         }
16474       }
16475       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16476                                   Mask, PassThru, Subtarget, DAG);
16477     }
16478     case INTR_TYPE_SCALAR_MASK: {
16479       SDValue Src1 = Op.getOperand(1);
16480       SDValue Src2 = Op.getOperand(2);
16481       SDValue passThru = Op.getOperand(3);
16482       SDValue Mask = Op.getOperand(4);
16483       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16484                                   Mask, passThru, Subtarget, DAG);
16485     }
16486     case INTR_TYPE_SCALAR_MASK_RM: {
16487       SDValue Src1 = Op.getOperand(1);
16488       SDValue Src2 = Op.getOperand(2);
16489       SDValue Src0 = Op.getOperand(3);
16490       SDValue Mask = Op.getOperand(4);
16491       // There are 2 kinds of intrinsics in this group:
16492       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16493       // (2) With rounding mode and sae - 7 operands.
16494       if (Op.getNumOperands() == 6) {
16495         SDValue Sae  = Op.getOperand(5);
16496         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16497         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16498                                                 Sae),
16499                                     Mask, Src0, Subtarget, DAG);
16500       }
16501       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16502       SDValue RoundingMode  = Op.getOperand(5);
16503       SDValue Sae  = Op.getOperand(6);
16504       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16505                                               RoundingMode, Sae),
16506                                   Mask, Src0, Subtarget, DAG);
16507     }
16508     case INTR_TYPE_2OP_MASK:
16509     case INTR_TYPE_2OP_IMM8_MASK: {
16510       SDValue Src1 = Op.getOperand(1);
16511       SDValue Src2 = Op.getOperand(2);
16512       SDValue PassThru = Op.getOperand(3);
16513       SDValue Mask = Op.getOperand(4);
16514
16515       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16516         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16517
16518       // We specify 2 possible opcodes for intrinsics with rounding modes.
16519       // First, we check if the intrinsic may have non-default rounding mode,
16520       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16521       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16522       if (IntrWithRoundingModeOpcode != 0) {
16523         SDValue Rnd = Op.getOperand(5);
16524         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16525         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16526           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16527                                       dl, Op.getValueType(),
16528                                       Src1, Src2, Rnd),
16529                                       Mask, PassThru, Subtarget, DAG);
16530         }
16531       }
16532       // TODO: Intrinsics should have fast-math-flags to propagate.
16533       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16534                                   Mask, PassThru, Subtarget, DAG);
16535     }
16536     case INTR_TYPE_2OP_MASK_RM: {
16537       SDValue Src1 = Op.getOperand(1);
16538       SDValue Src2 = Op.getOperand(2);
16539       SDValue PassThru = Op.getOperand(3);
16540       SDValue Mask = Op.getOperand(4);
16541       // We specify 2 possible modes for intrinsics, with/without rounding
16542       // modes.
16543       // First, we check if the intrinsic have rounding mode (6 operands),
16544       // if not, we set rounding mode to "current".
16545       SDValue Rnd;
16546       if (Op.getNumOperands() == 6)
16547         Rnd = Op.getOperand(5);
16548       else
16549         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16550       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16551                                               Src1, Src2, Rnd),
16552                                   Mask, PassThru, Subtarget, DAG);
16553     }
16554     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16555       SDValue Src1 = Op.getOperand(1);
16556       SDValue Src2 = Op.getOperand(2);
16557       SDValue Src3 = Op.getOperand(3);
16558       SDValue PassThru = Op.getOperand(4);
16559       SDValue Mask = Op.getOperand(5);
16560       SDValue Sae  = Op.getOperand(6);
16561
16562       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16563                                               Src2, Src3, Sae),
16564                                   Mask, PassThru, Subtarget, DAG);
16565     }
16566     case INTR_TYPE_3OP_MASK_RM: {
16567       SDValue Src1 = Op.getOperand(1);
16568       SDValue Src2 = Op.getOperand(2);
16569       SDValue Imm = Op.getOperand(3);
16570       SDValue PassThru = Op.getOperand(4);
16571       SDValue Mask = Op.getOperand(5);
16572       // We specify 2 possible modes for intrinsics, with/without rounding
16573       // modes.
16574       // First, we check if the intrinsic have rounding mode (7 operands),
16575       // if not, we set rounding mode to "current".
16576       SDValue Rnd;
16577       if (Op.getNumOperands() == 7)
16578         Rnd = Op.getOperand(6);
16579       else
16580         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16581       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16582         Src1, Src2, Imm, Rnd),
16583         Mask, PassThru, Subtarget, DAG);
16584     }
16585     case INTR_TYPE_3OP_IMM8_MASK:
16586     case INTR_TYPE_3OP_MASK:
16587     case INSERT_SUBVEC: {
16588       SDValue Src1 = Op.getOperand(1);
16589       SDValue Src2 = Op.getOperand(2);
16590       SDValue Src3 = Op.getOperand(3);
16591       SDValue PassThru = Op.getOperand(4);
16592       SDValue Mask = Op.getOperand(5);
16593
16594       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16595         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16596       else if (IntrData->Type == INSERT_SUBVEC) {
16597         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16598         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16599         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16600         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16601         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16602       }
16603
16604       // We specify 2 possible opcodes for intrinsics with rounding modes.
16605       // First, we check if the intrinsic may have non-default rounding mode,
16606       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16607       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16608       if (IntrWithRoundingModeOpcode != 0) {
16609         SDValue Rnd = Op.getOperand(6);
16610         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16611         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16612           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16613                                       dl, Op.getValueType(),
16614                                       Src1, Src2, Src3, Rnd),
16615                                       Mask, PassThru, Subtarget, DAG);
16616         }
16617       }
16618       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16619                                               Src1, Src2, Src3),
16620                                   Mask, PassThru, Subtarget, DAG);
16621     }
16622     case VPERM_3OP_MASKZ:
16623     case VPERM_3OP_MASK:{
16624       // Src2 is the PassThru
16625       SDValue Src1 = Op.getOperand(1);
16626       SDValue Src2 = Op.getOperand(2);
16627       SDValue Src3 = Op.getOperand(3);
16628       SDValue Mask = Op.getOperand(4);
16629       MVT VT = Op.getSimpleValueType();
16630       SDValue PassThru = SDValue();
16631
16632       // set PassThru element
16633       if (IntrData->Type == VPERM_3OP_MASKZ)
16634         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16635       else
16636         PassThru = DAG.getBitcast(VT, Src2);
16637
16638       // Swap Src1 and Src2 in the node creation
16639       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16640                                               dl, Op.getValueType(),
16641                                               Src2, Src1, Src3),
16642                                   Mask, PassThru, Subtarget, DAG);
16643     }
16644     case FMA_OP_MASK3:
16645     case FMA_OP_MASKZ:
16646     case FMA_OP_MASK: {
16647       SDValue Src1 = Op.getOperand(1);
16648       SDValue Src2 = Op.getOperand(2);
16649       SDValue Src3 = Op.getOperand(3);
16650       SDValue Mask = Op.getOperand(4);
16651       MVT VT = Op.getSimpleValueType();
16652       SDValue PassThru = SDValue();
16653
16654       // set PassThru element
16655       if (IntrData->Type == FMA_OP_MASKZ)
16656         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16657       else if (IntrData->Type == FMA_OP_MASK3)
16658         PassThru = Src3;
16659       else
16660         PassThru = Src1;
16661
16662       // We specify 2 possible opcodes for intrinsics with rounding modes.
16663       // First, we check if the intrinsic may have non-default rounding mode,
16664       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16665       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16666       if (IntrWithRoundingModeOpcode != 0) {
16667         SDValue Rnd = Op.getOperand(5);
16668         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16669             X86::STATIC_ROUNDING::CUR_DIRECTION)
16670           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16671                                                   dl, Op.getValueType(),
16672                                                   Src1, Src2, Src3, Rnd),
16673                                       Mask, PassThru, Subtarget, DAG);
16674       }
16675       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16676                                               dl, Op.getValueType(),
16677                                               Src1, Src2, Src3),
16678                                   Mask, PassThru, Subtarget, DAG);
16679     }
16680     case TERLOG_OP_MASK:
16681     case TERLOG_OP_MASKZ: {
16682       SDValue Src1 = Op.getOperand(1);
16683       SDValue Src2 = Op.getOperand(2);
16684       SDValue Src3 = Op.getOperand(3);
16685       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16686       SDValue Mask = Op.getOperand(5);
16687       MVT VT = Op.getSimpleValueType();
16688       SDValue PassThru = Src1;
16689       // Set PassThru element.
16690       if (IntrData->Type == TERLOG_OP_MASKZ)
16691         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16692
16693       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16694                                               Src1, Src2, Src3, Src4),
16695                                   Mask, PassThru, Subtarget, DAG);
16696     }
16697     case FPCLASS: {
16698       // FPclass intrinsics with mask
16699        SDValue Src1 = Op.getOperand(1);
16700        MVT VT = Src1.getSimpleValueType();
16701        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16702        SDValue Imm = Op.getOperand(2);
16703        SDValue Mask = Op.getOperand(3);
16704        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16705                                      Mask.getSimpleValueType().getSizeInBits());
16706        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16707        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16708                                                  DAG.getTargetConstant(0, dl, MaskVT),
16709                                                  Subtarget, DAG);
16710        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16711                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16712                                  DAG.getIntPtrConstant(0, dl));
16713        return DAG.getBitcast(Op.getValueType(), Res);
16714     }
16715     case FPCLASSS: {
16716       SDValue Src1 = Op.getOperand(1);
16717       SDValue Imm = Op.getOperand(2);
16718       SDValue Mask = Op.getOperand(3);
16719       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16720       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16721         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16722       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16723     }
16724     case CMP_MASK:
16725     case CMP_MASK_CC: {
16726       // Comparison intrinsics with masks.
16727       // Example of transformation:
16728       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16729       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16730       // (i8 (bitcast
16731       //   (v8i1 (insert_subvector undef,
16732       //           (v2i1 (and (PCMPEQM %a, %b),
16733       //                      (extract_subvector
16734       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16735       MVT VT = Op.getOperand(1).getSimpleValueType();
16736       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16737       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16738       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16739                                        Mask.getSimpleValueType().getSizeInBits());
16740       SDValue Cmp;
16741       if (IntrData->Type == CMP_MASK_CC) {
16742         SDValue CC = Op.getOperand(3);
16743         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16744         // We specify 2 possible opcodes for intrinsics with rounding modes.
16745         // First, we check if the intrinsic may have non-default rounding mode,
16746         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16747         if (IntrData->Opc1 != 0) {
16748           SDValue Rnd = Op.getOperand(5);
16749           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16750               X86::STATIC_ROUNDING::CUR_DIRECTION)
16751             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16752                               Op.getOperand(2), CC, Rnd);
16753         }
16754         //default rounding mode
16755         if(!Cmp.getNode())
16756             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16757                               Op.getOperand(2), CC);
16758
16759       } else {
16760         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16761         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16762                           Op.getOperand(2));
16763       }
16764       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16765                                              DAG.getTargetConstant(0, dl,
16766                                                                    MaskVT),
16767                                              Subtarget, DAG);
16768       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16769                                 DAG.getUNDEF(BitcastVT), CmpMask,
16770                                 DAG.getIntPtrConstant(0, dl));
16771       return DAG.getBitcast(Op.getValueType(), Res);
16772     }
16773     case CMP_MASK_SCALAR_CC: {
16774       SDValue Src1 = Op.getOperand(1);
16775       SDValue Src2 = Op.getOperand(2);
16776       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16777       SDValue Mask = Op.getOperand(4);
16778
16779       SDValue Cmp;
16780       if (IntrData->Opc1 != 0) {
16781         SDValue Rnd = Op.getOperand(5);
16782         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16783             X86::STATIC_ROUNDING::CUR_DIRECTION)
16784           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16785       }
16786       //default rounding mode
16787       if(!Cmp.getNode())
16788         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16789
16790       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16791                                              DAG.getTargetConstant(0, dl,
16792                                                                    MVT::i1),
16793                                              Subtarget, DAG);
16794
16795       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16796                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16797                          DAG.getValueType(MVT::i1));
16798     }
16799     case COMI: { // Comparison intrinsics
16800       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16801       SDValue LHS = Op.getOperand(1);
16802       SDValue RHS = Op.getOperand(2);
16803       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16804       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16805       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16806       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16807                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16808       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16809     }
16810     case COMI_RM: { // Comparison intrinsics with Sae
16811       SDValue LHS = Op.getOperand(1);
16812       SDValue RHS = Op.getOperand(2);
16813       SDValue CC = Op.getOperand(3);
16814       SDValue Sae = Op.getOperand(4);
16815       auto ComiType = TranslateX86ConstCondToX86CC(CC);
16816       // choose between ordered and unordered (comi/ucomi)
16817       unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16818       SDValue Cond;
16819       if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16820                                            X86::STATIC_ROUNDING::CUR_DIRECTION)
16821         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16822       else
16823         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16824       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16825         DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16826       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16827     }
16828     case VSHIFT:
16829       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16830                                  Op.getOperand(1), Op.getOperand(2), DAG);
16831     case VSHIFT_MASK:
16832       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16833                                                       Op.getSimpleValueType(),
16834                                                       Op.getOperand(1),
16835                                                       Op.getOperand(2), DAG),
16836                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16837                                   DAG);
16838     case COMPRESS_EXPAND_IN_REG: {
16839       SDValue Mask = Op.getOperand(3);
16840       SDValue DataToCompress = Op.getOperand(1);
16841       SDValue PassThru = Op.getOperand(2);
16842       if (isAllOnesConstant(Mask)) // return data as is
16843         return Op.getOperand(1);
16844
16845       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16846                                               DataToCompress),
16847                                   Mask, PassThru, Subtarget, DAG);
16848     }
16849     case BROADCASTM: {
16850       SDValue Mask = Op.getOperand(1);
16851       MVT MaskVT = MVT::getVectorVT(MVT::i1,
16852                                     Mask.getSimpleValueType().getSizeInBits());
16853       Mask = DAG.getBitcast(MaskVT, Mask);
16854       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16855     }
16856     case BLEND: {
16857       SDValue Mask = Op.getOperand(3);
16858       MVT VT = Op.getSimpleValueType();
16859       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16860       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16861       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16862                          Op.getOperand(2));
16863     }
16864     case KUNPCK: {
16865       MVT VT = Op.getSimpleValueType();
16866       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16867
16868       SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16869       SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16870       // Arguments should be swapped.
16871       SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16872                                 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16873                                 Src2, Src1);
16874       return DAG.getBitcast(VT, Res);
16875     }
16876     case CONVERT_TO_MASK: {
16877       MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16878       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16879       MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16880
16881       SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16882                                     Op.getOperand(1));
16883       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16884                                 DAG.getUNDEF(BitcastVT), CvtMask,
16885                                 DAG.getIntPtrConstant(0, dl));
16886       return DAG.getBitcast(Op.getValueType(), Res);
16887     }
16888     case CONVERT_MASK_TO_VEC: {
16889       SDValue Mask = Op.getOperand(1);
16890       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16891       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16892       return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16893     }
16894     case BRCST_SUBVEC_TO_VEC: {
16895       SDValue Src = Op.getOperand(1);
16896       SDValue Passthru = Op.getOperand(2);
16897       SDValue Mask = Op.getOperand(3);
16898       EVT resVT = Passthru.getValueType();
16899       SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16900                                        DAG.getUNDEF(resVT), Src,
16901                                        DAG.getIntPtrConstant(0, dl));
16902       SDValue immVal;
16903       if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16904         immVal = DAG.getConstant(0x44, dl, MVT::i8);
16905       else
16906         immVal = DAG.getConstant(0, dl, MVT::i8);
16907       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16908                                               subVec, subVec, immVal),
16909                                   Mask, Passthru, Subtarget, DAG);
16910     }
16911     default:
16912       break;
16913     }
16914   }
16915
16916   switch (IntNo) {
16917   default: return SDValue();    // Don't custom lower most intrinsics.
16918
16919   case Intrinsic::x86_avx2_permd:
16920   case Intrinsic::x86_avx2_permps:
16921     // Operands intentionally swapped. Mask is last operand to intrinsic,
16922     // but second operand for node/instruction.
16923     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16924                        Op.getOperand(2), Op.getOperand(1));
16925
16926   // ptest and testp intrinsics. The intrinsic these come from are designed to
16927   // return an integer value, not just an instruction so lower it to the ptest
16928   // or testp pattern and a setcc for the result.
16929   case Intrinsic::x86_sse41_ptestz:
16930   case Intrinsic::x86_sse41_ptestc:
16931   case Intrinsic::x86_sse41_ptestnzc:
16932   case Intrinsic::x86_avx_ptestz_256:
16933   case Intrinsic::x86_avx_ptestc_256:
16934   case Intrinsic::x86_avx_ptestnzc_256:
16935   case Intrinsic::x86_avx_vtestz_ps:
16936   case Intrinsic::x86_avx_vtestc_ps:
16937   case Intrinsic::x86_avx_vtestnzc_ps:
16938   case Intrinsic::x86_avx_vtestz_pd:
16939   case Intrinsic::x86_avx_vtestc_pd:
16940   case Intrinsic::x86_avx_vtestnzc_pd:
16941   case Intrinsic::x86_avx_vtestz_ps_256:
16942   case Intrinsic::x86_avx_vtestc_ps_256:
16943   case Intrinsic::x86_avx_vtestnzc_ps_256:
16944   case Intrinsic::x86_avx_vtestz_pd_256:
16945   case Intrinsic::x86_avx_vtestc_pd_256:
16946   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16947     bool IsTestPacked = false;
16948     unsigned X86CC;
16949     switch (IntNo) {
16950     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16951     case Intrinsic::x86_avx_vtestz_ps:
16952     case Intrinsic::x86_avx_vtestz_pd:
16953     case Intrinsic::x86_avx_vtestz_ps_256:
16954     case Intrinsic::x86_avx_vtestz_pd_256:
16955       IsTestPacked = true; // Fallthrough
16956     case Intrinsic::x86_sse41_ptestz:
16957     case Intrinsic::x86_avx_ptestz_256:
16958       // ZF = 1
16959       X86CC = X86::COND_E;
16960       break;
16961     case Intrinsic::x86_avx_vtestc_ps:
16962     case Intrinsic::x86_avx_vtestc_pd:
16963     case Intrinsic::x86_avx_vtestc_ps_256:
16964     case Intrinsic::x86_avx_vtestc_pd_256:
16965       IsTestPacked = true; // Fallthrough
16966     case Intrinsic::x86_sse41_ptestc:
16967     case Intrinsic::x86_avx_ptestc_256:
16968       // CF = 1
16969       X86CC = X86::COND_B;
16970       break;
16971     case Intrinsic::x86_avx_vtestnzc_ps:
16972     case Intrinsic::x86_avx_vtestnzc_pd:
16973     case Intrinsic::x86_avx_vtestnzc_ps_256:
16974     case Intrinsic::x86_avx_vtestnzc_pd_256:
16975       IsTestPacked = true; // Fallthrough
16976     case Intrinsic::x86_sse41_ptestnzc:
16977     case Intrinsic::x86_avx_ptestnzc_256:
16978       // ZF and CF = 0
16979       X86CC = X86::COND_A;
16980       break;
16981     }
16982
16983     SDValue LHS = Op.getOperand(1);
16984     SDValue RHS = Op.getOperand(2);
16985     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16986     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16987     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16988     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16989     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16990   }
16991   case Intrinsic::x86_avx512_kortestz_w:
16992   case Intrinsic::x86_avx512_kortestc_w: {
16993     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16994     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16995     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16996     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16997     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16998     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16999     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17000   }
17001
17002   case Intrinsic::x86_sse42_pcmpistria128:
17003   case Intrinsic::x86_sse42_pcmpestria128:
17004   case Intrinsic::x86_sse42_pcmpistric128:
17005   case Intrinsic::x86_sse42_pcmpestric128:
17006   case Intrinsic::x86_sse42_pcmpistrio128:
17007   case Intrinsic::x86_sse42_pcmpestrio128:
17008   case Intrinsic::x86_sse42_pcmpistris128:
17009   case Intrinsic::x86_sse42_pcmpestris128:
17010   case Intrinsic::x86_sse42_pcmpistriz128:
17011   case Intrinsic::x86_sse42_pcmpestriz128: {
17012     unsigned Opcode;
17013     unsigned X86CC;
17014     switch (IntNo) {
17015     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17016     case Intrinsic::x86_sse42_pcmpistria128:
17017       Opcode = X86ISD::PCMPISTRI;
17018       X86CC = X86::COND_A;
17019       break;
17020     case Intrinsic::x86_sse42_pcmpestria128:
17021       Opcode = X86ISD::PCMPESTRI;
17022       X86CC = X86::COND_A;
17023       break;
17024     case Intrinsic::x86_sse42_pcmpistric128:
17025       Opcode = X86ISD::PCMPISTRI;
17026       X86CC = X86::COND_B;
17027       break;
17028     case Intrinsic::x86_sse42_pcmpestric128:
17029       Opcode = X86ISD::PCMPESTRI;
17030       X86CC = X86::COND_B;
17031       break;
17032     case Intrinsic::x86_sse42_pcmpistrio128:
17033       Opcode = X86ISD::PCMPISTRI;
17034       X86CC = X86::COND_O;
17035       break;
17036     case Intrinsic::x86_sse42_pcmpestrio128:
17037       Opcode = X86ISD::PCMPESTRI;
17038       X86CC = X86::COND_O;
17039       break;
17040     case Intrinsic::x86_sse42_pcmpistris128:
17041       Opcode = X86ISD::PCMPISTRI;
17042       X86CC = X86::COND_S;
17043       break;
17044     case Intrinsic::x86_sse42_pcmpestris128:
17045       Opcode = X86ISD::PCMPESTRI;
17046       X86CC = X86::COND_S;
17047       break;
17048     case Intrinsic::x86_sse42_pcmpistriz128:
17049       Opcode = X86ISD::PCMPISTRI;
17050       X86CC = X86::COND_E;
17051       break;
17052     case Intrinsic::x86_sse42_pcmpestriz128:
17053       Opcode = X86ISD::PCMPESTRI;
17054       X86CC = X86::COND_E;
17055       break;
17056     }
17057     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17058     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17059     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17060     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17061                                 DAG.getConstant(X86CC, dl, MVT::i8),
17062                                 SDValue(PCMP.getNode(), 1));
17063     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17064   }
17065
17066   case Intrinsic::x86_sse42_pcmpistri128:
17067   case Intrinsic::x86_sse42_pcmpestri128: {
17068     unsigned Opcode;
17069     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17070       Opcode = X86ISD::PCMPISTRI;
17071     else
17072       Opcode = X86ISD::PCMPESTRI;
17073
17074     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17075     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17076     return DAG.getNode(Opcode, dl, VTs, NewOps);
17077   }
17078
17079   case Intrinsic::x86_seh_lsda: {
17080     // Compute the symbol for the LSDA. We know it'll get emitted later.
17081     MachineFunction &MF = DAG.getMachineFunction();
17082     SDValue Op1 = Op.getOperand(1);
17083     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17084     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17085         GlobalValue::getRealLinkageName(Fn->getName()));
17086
17087     // Generate a simple absolute symbol reference. This intrinsic is only
17088     // supported on 32-bit Windows, which isn't PIC.
17089     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17090     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17091   }
17092
17093   case Intrinsic::x86_seh_recoverfp: {
17094     SDValue FnOp = Op.getOperand(1);
17095     SDValue IncomingFPOp = Op.getOperand(2);
17096     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17097     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17098     if (!Fn)
17099       report_fatal_error(
17100           "llvm.x86.seh.recoverfp must take a function as the first argument");
17101     return recoverFramePointer(DAG, Fn, IncomingFPOp);
17102   }
17103
17104   case Intrinsic::localaddress: {
17105     // Returns one of the stack, base, or frame pointer registers, depending on
17106     // which is used to reference local variables.
17107     MachineFunction &MF = DAG.getMachineFunction();
17108     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17109     unsigned Reg;
17110     if (RegInfo->hasBasePointer(MF))
17111       Reg = RegInfo->getBaseRegister();
17112     else // This function handles the SP or FP case.
17113       Reg = RegInfo->getPtrSizedFrameRegister(MF);
17114     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17115   }
17116   }
17117 }
17118
17119 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17120                               SDValue Src, SDValue Mask, SDValue Base,
17121                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17122                               const X86Subtarget * Subtarget) {
17123   SDLoc dl(Op);
17124   auto *C = cast<ConstantSDNode>(ScaleOp);
17125   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17126   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17127                              Index.getSimpleValueType().getVectorNumElements());
17128   SDValue MaskInReg;
17129   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17130   if (MaskC)
17131     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17132   else {
17133     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17134                                      Mask.getSimpleValueType().getSizeInBits());
17135
17136     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17137     // are extracted by EXTRACT_SUBVECTOR.
17138     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17139                             DAG.getBitcast(BitcastVT, Mask),
17140                             DAG.getIntPtrConstant(0, dl));
17141   }
17142   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17143   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17144   SDValue Segment = DAG.getRegister(0, MVT::i32);
17145   if (Src.getOpcode() == ISD::UNDEF)
17146     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17147   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17148   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17149   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17150   return DAG.getMergeValues(RetOps, dl);
17151 }
17152
17153 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17154                                SDValue Src, SDValue Mask, SDValue Base,
17155                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17156   SDLoc dl(Op);
17157   auto *C = cast<ConstantSDNode>(ScaleOp);
17158   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17159   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17160   SDValue Segment = DAG.getRegister(0, MVT::i32);
17161   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17162                              Index.getSimpleValueType().getVectorNumElements());
17163   SDValue MaskInReg;
17164   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17165   if (MaskC)
17166     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17167   else {
17168     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17169                                      Mask.getSimpleValueType().getSizeInBits());
17170
17171     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17172     // are extracted by EXTRACT_SUBVECTOR.
17173     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17174                             DAG.getBitcast(BitcastVT, Mask),
17175                             DAG.getIntPtrConstant(0, dl));
17176   }
17177   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17178   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17179   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17180   return SDValue(Res, 1);
17181 }
17182
17183 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17184                                SDValue Mask, SDValue Base, SDValue Index,
17185                                SDValue ScaleOp, SDValue Chain) {
17186   SDLoc dl(Op);
17187   auto *C = cast<ConstantSDNode>(ScaleOp);
17188   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17189   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17190   SDValue Segment = DAG.getRegister(0, MVT::i32);
17191   MVT MaskVT =
17192     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17193   SDValue MaskInReg;
17194   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17195   if (MaskC)
17196     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17197   else
17198     MaskInReg = DAG.getBitcast(MaskVT, Mask);
17199   //SDVTList VTs = DAG.getVTList(MVT::Other);
17200   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17201   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17202   return SDValue(Res, 0);
17203 }
17204
17205 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17206 // read performance monitor counters (x86_rdpmc).
17207 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17208                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17209                               SmallVectorImpl<SDValue> &Results) {
17210   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17211   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17212   SDValue LO, HI;
17213
17214   // The ECX register is used to select the index of the performance counter
17215   // to read.
17216   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17217                                    N->getOperand(2));
17218   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17219
17220   // Reads the content of a 64-bit performance counter and returns it in the
17221   // registers EDX:EAX.
17222   if (Subtarget->is64Bit()) {
17223     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17224     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17225                             LO.getValue(2));
17226   } else {
17227     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17228     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17229                             LO.getValue(2));
17230   }
17231   Chain = HI.getValue(1);
17232
17233   if (Subtarget->is64Bit()) {
17234     // The EAX register is loaded with the low-order 32 bits. The EDX register
17235     // is loaded with the supported high-order bits of the counter.
17236     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17237                               DAG.getConstant(32, DL, MVT::i8));
17238     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17239     Results.push_back(Chain);
17240     return;
17241   }
17242
17243   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17244   SDValue Ops[] = { LO, HI };
17245   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17246   Results.push_back(Pair);
17247   Results.push_back(Chain);
17248 }
17249
17250 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17251 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17252 // also used to custom lower READCYCLECOUNTER nodes.
17253 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17254                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17255                               SmallVectorImpl<SDValue> &Results) {
17256   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17257   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17258   SDValue LO, HI;
17259
17260   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17261   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17262   // and the EAX register is loaded with the low-order 32 bits.
17263   if (Subtarget->is64Bit()) {
17264     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17265     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17266                             LO.getValue(2));
17267   } else {
17268     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17269     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17270                             LO.getValue(2));
17271   }
17272   SDValue Chain = HI.getValue(1);
17273
17274   if (Opcode == X86ISD::RDTSCP_DAG) {
17275     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17276
17277     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17278     // the ECX register. Add 'ecx' explicitly to the chain.
17279     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17280                                      HI.getValue(2));
17281     // Explicitly store the content of ECX at the location passed in input
17282     // to the 'rdtscp' intrinsic.
17283     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17284                          MachinePointerInfo(), false, false, 0);
17285   }
17286
17287   if (Subtarget->is64Bit()) {
17288     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17289     // the EAX register is loaded with the low-order 32 bits.
17290     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17291                               DAG.getConstant(32, DL, MVT::i8));
17292     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17293     Results.push_back(Chain);
17294     return;
17295   }
17296
17297   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17298   SDValue Ops[] = { LO, HI };
17299   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17300   Results.push_back(Pair);
17301   Results.push_back(Chain);
17302 }
17303
17304 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17305                                      SelectionDAG &DAG) {
17306   SmallVector<SDValue, 2> Results;
17307   SDLoc DL(Op);
17308   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17309                           Results);
17310   return DAG.getMergeValues(Results, DL);
17311 }
17312
17313 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17314   MachineFunction &MF = DAG.getMachineFunction();
17315   SDValue Chain = Op.getOperand(0);
17316   SDValue RegNode = Op.getOperand(2);
17317   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17318   if (!EHInfo)
17319     report_fatal_error("EH registrations only live in functions using WinEH");
17320
17321   // Cast the operand to an alloca, and remember the frame index.
17322   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17323   if (!FINode)
17324     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17325   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17326
17327   // Return the chain operand without making any DAG nodes.
17328   return Chain;
17329 }
17330
17331 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17332 /// return truncate Store/MaskedStore Node
17333 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17334                                                SelectionDAG &DAG,
17335                                                MVT ElementType) {
17336   SDLoc dl(Op);
17337   SDValue Mask = Op.getOperand(4);
17338   SDValue DataToTruncate = Op.getOperand(3);
17339   SDValue Addr = Op.getOperand(2);
17340   SDValue Chain = Op.getOperand(0);
17341
17342   MVT VT  = DataToTruncate.getSimpleValueType();
17343   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17344
17345   if (isAllOnesConstant(Mask)) // return just a truncate store
17346     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17347                              MachinePointerInfo(), SVT, false, false,
17348                              SVT.getScalarSizeInBits()/8);
17349
17350   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17351   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17352                                    Mask.getSimpleValueType().getSizeInBits());
17353   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17354   // are extracted by EXTRACT_SUBVECTOR.
17355   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17356                               DAG.getBitcast(BitcastVT, Mask),
17357                               DAG.getIntPtrConstant(0, dl));
17358
17359   MachineMemOperand *MMO = DAG.getMachineFunction().
17360     getMachineMemOperand(MachinePointerInfo(),
17361                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17362                          SVT.getScalarSizeInBits()/8);
17363
17364   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17365                             VMask, SVT, MMO, true);
17366 }
17367
17368 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17369                                       SelectionDAG &DAG) {
17370   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17371
17372   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17373   if (!IntrData) {
17374     if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17375       return MarkEHRegistrationNode(Op, DAG);
17376     return SDValue();
17377   }
17378
17379   SDLoc dl(Op);
17380   switch(IntrData->Type) {
17381   default: llvm_unreachable("Unknown Intrinsic Type");
17382   case RDSEED:
17383   case RDRAND: {
17384     // Emit the node with the right value type.
17385     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17386     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17387
17388     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17389     // Otherwise return the value from Rand, which is always 0, casted to i32.
17390     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17391                       DAG.getConstant(1, dl, Op->getValueType(1)),
17392                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17393                       SDValue(Result.getNode(), 1) };
17394     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17395                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17396                                   Ops);
17397
17398     // Return { result, isValid, chain }.
17399     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17400                        SDValue(Result.getNode(), 2));
17401   }
17402   case GATHER: {
17403   //gather(v1, mask, index, base, scale);
17404     SDValue Chain = Op.getOperand(0);
17405     SDValue Src   = Op.getOperand(2);
17406     SDValue Base  = Op.getOperand(3);
17407     SDValue Index = Op.getOperand(4);
17408     SDValue Mask  = Op.getOperand(5);
17409     SDValue Scale = Op.getOperand(6);
17410     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17411                          Chain, Subtarget);
17412   }
17413   case SCATTER: {
17414   //scatter(base, mask, index, v1, scale);
17415     SDValue Chain = Op.getOperand(0);
17416     SDValue Base  = Op.getOperand(2);
17417     SDValue Mask  = Op.getOperand(3);
17418     SDValue Index = Op.getOperand(4);
17419     SDValue Src   = Op.getOperand(5);
17420     SDValue Scale = Op.getOperand(6);
17421     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17422                           Scale, Chain);
17423   }
17424   case PREFETCH: {
17425     SDValue Hint = Op.getOperand(6);
17426     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17427     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17428     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17429     SDValue Chain = Op.getOperand(0);
17430     SDValue Mask  = Op.getOperand(2);
17431     SDValue Index = Op.getOperand(3);
17432     SDValue Base  = Op.getOperand(4);
17433     SDValue Scale = Op.getOperand(5);
17434     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17435   }
17436   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17437   case RDTSC: {
17438     SmallVector<SDValue, 2> Results;
17439     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17440                             Results);
17441     return DAG.getMergeValues(Results, dl);
17442   }
17443   // Read Performance Monitoring Counters.
17444   case RDPMC: {
17445     SmallVector<SDValue, 2> Results;
17446     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17447     return DAG.getMergeValues(Results, dl);
17448   }
17449   // XTEST intrinsics.
17450   case XTEST: {
17451     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17452     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17453     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17454                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17455                                 InTrans);
17456     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17457     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17458                        Ret, SDValue(InTrans.getNode(), 1));
17459   }
17460   // ADC/ADCX/SBB
17461   case ADX: {
17462     SmallVector<SDValue, 2> Results;
17463     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17464     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17465     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17466                                 DAG.getConstant(-1, dl, MVT::i8));
17467     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17468                               Op.getOperand(4), GenCF.getValue(1));
17469     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17470                                  Op.getOperand(5), MachinePointerInfo(),
17471                                  false, false, 0);
17472     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17473                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17474                                 Res.getValue(1));
17475     Results.push_back(SetCC);
17476     Results.push_back(Store);
17477     return DAG.getMergeValues(Results, dl);
17478   }
17479   case COMPRESS_TO_MEM: {
17480     SDLoc dl(Op);
17481     SDValue Mask = Op.getOperand(4);
17482     SDValue DataToCompress = Op.getOperand(3);
17483     SDValue Addr = Op.getOperand(2);
17484     SDValue Chain = Op.getOperand(0);
17485
17486     MVT VT = DataToCompress.getSimpleValueType();
17487     if (isAllOnesConstant(Mask)) // return just a store
17488       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17489                           MachinePointerInfo(), false, false,
17490                           VT.getScalarSizeInBits()/8);
17491
17492     SDValue Compressed =
17493       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17494                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17495     return DAG.getStore(Chain, dl, Compressed, Addr,
17496                         MachinePointerInfo(), false, false,
17497                         VT.getScalarSizeInBits()/8);
17498   }
17499   case TRUNCATE_TO_MEM_VI8:
17500     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17501   case TRUNCATE_TO_MEM_VI16:
17502     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17503   case TRUNCATE_TO_MEM_VI32:
17504     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17505   case EXPAND_FROM_MEM: {
17506     SDLoc dl(Op);
17507     SDValue Mask = Op.getOperand(4);
17508     SDValue PassThru = Op.getOperand(3);
17509     SDValue Addr = Op.getOperand(2);
17510     SDValue Chain = Op.getOperand(0);
17511     MVT VT = Op.getSimpleValueType();
17512
17513     if (isAllOnesConstant(Mask)) // return just a load
17514       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17515                          false, VT.getScalarSizeInBits()/8);
17516
17517     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17518                                        false, false, false,
17519                                        VT.getScalarSizeInBits()/8);
17520
17521     SDValue Results[] = {
17522       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17523                            Mask, PassThru, Subtarget, DAG), Chain};
17524     return DAG.getMergeValues(Results, dl);
17525   }
17526   }
17527 }
17528
17529 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17530                                            SelectionDAG &DAG) const {
17531   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17532   MFI->setReturnAddressIsTaken(true);
17533
17534   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17535     return SDValue();
17536
17537   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17538   SDLoc dl(Op);
17539   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17540
17541   if (Depth > 0) {
17542     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17543     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17544     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17545     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17546                        DAG.getNode(ISD::ADD, dl, PtrVT,
17547                                    FrameAddr, Offset),
17548                        MachinePointerInfo(), false, false, false, 0);
17549   }
17550
17551   // Just load the return address.
17552   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17553   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17554                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17555 }
17556
17557 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17558   MachineFunction &MF = DAG.getMachineFunction();
17559   MachineFrameInfo *MFI = MF.getFrameInfo();
17560   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17561   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17562   EVT VT = Op.getValueType();
17563
17564   MFI->setFrameAddressIsTaken(true);
17565
17566   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17567     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17568     // is not possible to crawl up the stack without looking at the unwind codes
17569     // simultaneously.
17570     int FrameAddrIndex = FuncInfo->getFAIndex();
17571     if (!FrameAddrIndex) {
17572       // Set up a frame object for the return address.
17573       unsigned SlotSize = RegInfo->getSlotSize();
17574       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17575           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17576       FuncInfo->setFAIndex(FrameAddrIndex);
17577     }
17578     return DAG.getFrameIndex(FrameAddrIndex, VT);
17579   }
17580
17581   unsigned FrameReg =
17582       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17583   SDLoc dl(Op);  // FIXME probably not meaningful
17584   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17585   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17586           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17587          "Invalid Frame Register!");
17588   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17589   while (Depth--)
17590     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17591                             MachinePointerInfo(),
17592                             false, false, false, 0);
17593   return FrameAddr;
17594 }
17595
17596 // FIXME? Maybe this could be a TableGen attribute on some registers and
17597 // this table could be generated automatically from RegInfo.
17598 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17599                                               SelectionDAG &DAG) const {
17600   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17601   const MachineFunction &MF = DAG.getMachineFunction();
17602
17603   unsigned Reg = StringSwitch<unsigned>(RegName)
17604                        .Case("esp", X86::ESP)
17605                        .Case("rsp", X86::RSP)
17606                        .Case("ebp", X86::EBP)
17607                        .Case("rbp", X86::RBP)
17608                        .Default(0);
17609
17610   if (Reg == X86::EBP || Reg == X86::RBP) {
17611     if (!TFI.hasFP(MF))
17612       report_fatal_error("register " + StringRef(RegName) +
17613                          " is allocatable: function has no frame pointer");
17614 #ifndef NDEBUG
17615     else {
17616       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17617       unsigned FrameReg =
17618           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17619       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17620              "Invalid Frame Register!");
17621     }
17622 #endif
17623   }
17624
17625   if (Reg)
17626     return Reg;
17627
17628   report_fatal_error("Invalid register name global variable");
17629 }
17630
17631 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17632                                                      SelectionDAG &DAG) const {
17633   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17634   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17635 }
17636
17637 unsigned X86TargetLowering::getExceptionPointerRegister(
17638     const Constant *PersonalityFn) const {
17639   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17640     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17641
17642   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17643 }
17644
17645 unsigned X86TargetLowering::getExceptionSelectorRegister(
17646     const Constant *PersonalityFn) const {
17647   // Funclet personalities don't use selectors (the runtime does the selection).
17648   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17649   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17650 }
17651
17652 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17653   SDValue Chain     = Op.getOperand(0);
17654   SDValue Offset    = Op.getOperand(1);
17655   SDValue Handler   = Op.getOperand(2);
17656   SDLoc dl      (Op);
17657
17658   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17659   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17660   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17661   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17662           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17663          "Invalid Frame Register!");
17664   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17665   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17666
17667   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17668                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17669                                                        dl));
17670   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17671   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17672                        false, false, 0);
17673   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17674
17675   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17676                      DAG.getRegister(StoreAddrReg, PtrVT));
17677 }
17678
17679 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17680                                                SelectionDAG &DAG) const {
17681   SDLoc DL(Op);
17682   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17683                      DAG.getVTList(MVT::i32, MVT::Other),
17684                      Op.getOperand(0), Op.getOperand(1));
17685 }
17686
17687 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17688                                                 SelectionDAG &DAG) const {
17689   SDLoc DL(Op);
17690   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17691                      Op.getOperand(0), Op.getOperand(1));
17692 }
17693
17694 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17695   return Op.getOperand(0);
17696 }
17697
17698 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17699                                                 SelectionDAG &DAG) const {
17700   SDValue Root = Op.getOperand(0);
17701   SDValue Trmp = Op.getOperand(1); // trampoline
17702   SDValue FPtr = Op.getOperand(2); // nested function
17703   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17704   SDLoc dl (Op);
17705
17706   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17707   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17708
17709   if (Subtarget->is64Bit()) {
17710     SDValue OutChains[6];
17711
17712     // Large code-model.
17713     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17714     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17715
17716     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17717     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17718
17719     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17720
17721     // Load the pointer to the nested function into R11.
17722     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17723     SDValue Addr = Trmp;
17724     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17725                                 Addr, MachinePointerInfo(TrmpAddr),
17726                                 false, false, 0);
17727
17728     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17729                        DAG.getConstant(2, dl, MVT::i64));
17730     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17731                                 MachinePointerInfo(TrmpAddr, 2),
17732                                 false, false, 2);
17733
17734     // Load the 'nest' parameter value into R10.
17735     // R10 is specified in X86CallingConv.td
17736     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17737     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17738                        DAG.getConstant(10, dl, MVT::i64));
17739     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17740                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17741                                 false, false, 0);
17742
17743     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17744                        DAG.getConstant(12, dl, MVT::i64));
17745     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17746                                 MachinePointerInfo(TrmpAddr, 12),
17747                                 false, false, 2);
17748
17749     // Jump to the nested function.
17750     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17751     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17752                        DAG.getConstant(20, dl, MVT::i64));
17753     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17754                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17755                                 false, false, 0);
17756
17757     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17758     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17759                        DAG.getConstant(22, dl, MVT::i64));
17760     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17761                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17762                                 false, false, 0);
17763
17764     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17765   } else {
17766     const Function *Func =
17767       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17768     CallingConv::ID CC = Func->getCallingConv();
17769     unsigned NestReg;
17770
17771     switch (CC) {
17772     default:
17773       llvm_unreachable("Unsupported calling convention");
17774     case CallingConv::C:
17775     case CallingConv::X86_StdCall: {
17776       // Pass 'nest' parameter in ECX.
17777       // Must be kept in sync with X86CallingConv.td
17778       NestReg = X86::ECX;
17779
17780       // Check that ECX wasn't needed by an 'inreg' parameter.
17781       FunctionType *FTy = Func->getFunctionType();
17782       const AttributeSet &Attrs = Func->getAttributes();
17783
17784       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17785         unsigned InRegCount = 0;
17786         unsigned Idx = 1;
17787
17788         for (FunctionType::param_iterator I = FTy->param_begin(),
17789              E = FTy->param_end(); I != E; ++I, ++Idx)
17790           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17791             auto &DL = DAG.getDataLayout();
17792             // FIXME: should only count parameters that are lowered to integers.
17793             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17794           }
17795
17796         if (InRegCount > 2) {
17797           report_fatal_error("Nest register in use - reduce number of inreg"
17798                              " parameters!");
17799         }
17800       }
17801       break;
17802     }
17803     case CallingConv::X86_FastCall:
17804     case CallingConv::X86_ThisCall:
17805     case CallingConv::Fast:
17806       // Pass 'nest' parameter in EAX.
17807       // Must be kept in sync with X86CallingConv.td
17808       NestReg = X86::EAX;
17809       break;
17810     }
17811
17812     SDValue OutChains[4];
17813     SDValue Addr, Disp;
17814
17815     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17816                        DAG.getConstant(10, dl, MVT::i32));
17817     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17818
17819     // This is storing the opcode for MOV32ri.
17820     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17821     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17822     OutChains[0] = DAG.getStore(Root, dl,
17823                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17824                                 Trmp, MachinePointerInfo(TrmpAddr),
17825                                 false, false, 0);
17826
17827     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17828                        DAG.getConstant(1, dl, MVT::i32));
17829     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17830                                 MachinePointerInfo(TrmpAddr, 1),
17831                                 false, false, 1);
17832
17833     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17834     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17835                        DAG.getConstant(5, dl, MVT::i32));
17836     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17837                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17838                                 false, false, 1);
17839
17840     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17841                        DAG.getConstant(6, dl, MVT::i32));
17842     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17843                                 MachinePointerInfo(TrmpAddr, 6),
17844                                 false, false, 1);
17845
17846     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17847   }
17848 }
17849
17850 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17851                                             SelectionDAG &DAG) const {
17852   /*
17853    The rounding mode is in bits 11:10 of FPSR, and has the following
17854    settings:
17855      00 Round to nearest
17856      01 Round to -inf
17857      10 Round to +inf
17858      11 Round to 0
17859
17860   FLT_ROUNDS, on the other hand, expects the following:
17861     -1 Undefined
17862      0 Round to 0
17863      1 Round to nearest
17864      2 Round to +inf
17865      3 Round to -inf
17866
17867   To perform the conversion, we do:
17868     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17869   */
17870
17871   MachineFunction &MF = DAG.getMachineFunction();
17872   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17873   unsigned StackAlignment = TFI.getStackAlignment();
17874   MVT VT = Op.getSimpleValueType();
17875   SDLoc DL(Op);
17876
17877   // Save FP Control Word to stack slot
17878   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17879   SDValue StackSlot =
17880       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17881
17882   MachineMemOperand *MMO =
17883       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17884                               MachineMemOperand::MOStore, 2, 2);
17885
17886   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17887   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17888                                           DAG.getVTList(MVT::Other),
17889                                           Ops, MVT::i16, MMO);
17890
17891   // Load FP Control Word from stack slot
17892   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17893                             MachinePointerInfo(), false, false, false, 0);
17894
17895   // Transform as necessary
17896   SDValue CWD1 =
17897     DAG.getNode(ISD::SRL, DL, MVT::i16,
17898                 DAG.getNode(ISD::AND, DL, MVT::i16,
17899                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17900                 DAG.getConstant(11, DL, MVT::i8));
17901   SDValue CWD2 =
17902     DAG.getNode(ISD::SRL, DL, MVT::i16,
17903                 DAG.getNode(ISD::AND, DL, MVT::i16,
17904                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17905                 DAG.getConstant(9, DL, MVT::i8));
17906
17907   SDValue RetVal =
17908     DAG.getNode(ISD::AND, DL, MVT::i16,
17909                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17910                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17911                             DAG.getConstant(1, DL, MVT::i16)),
17912                 DAG.getConstant(3, DL, MVT::i16));
17913
17914   return DAG.getNode((VT.getSizeInBits() < 16 ?
17915                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17916 }
17917
17918 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17919 //
17920 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17921 //    to 512-bit vector.
17922 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17923 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17924 //    split the vector, perform operation on it's Lo a Hi part and
17925 //    concatenate the results.
17926 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17927   SDLoc dl(Op);
17928   MVT VT = Op.getSimpleValueType();
17929   MVT EltVT = VT.getVectorElementType();
17930   unsigned NumElems = VT.getVectorNumElements();
17931
17932   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17933     // Extend to 512 bit vector.
17934     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17935               "Unsupported value type for operation");
17936
17937     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17938     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17939                                  DAG.getUNDEF(NewVT),
17940                                  Op.getOperand(0),
17941                                  DAG.getIntPtrConstant(0, dl));
17942     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17943
17944     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17945                        DAG.getIntPtrConstant(0, dl));
17946   }
17947
17948   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17949           "Unsupported element type");
17950
17951   if (16 < NumElems) {
17952     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17953     SDValue Lo, Hi;
17954     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17955     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17956
17957     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17958     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17959
17960     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17961   }
17962
17963   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17964
17965   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17966           "Unsupported value type for operation");
17967
17968   // Use native supported vector instruction vplzcntd.
17969   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17970   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17971   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17972   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17973
17974   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17975 }
17976
17977 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17978                          SelectionDAG &DAG) {
17979   MVT VT = Op.getSimpleValueType();
17980   MVT OpVT = VT;
17981   unsigned NumBits = VT.getSizeInBits();
17982   SDLoc dl(Op);
17983
17984   if (VT.isVector() && Subtarget->hasAVX512())
17985     return LowerVectorCTLZ_AVX512(Op, DAG);
17986
17987   Op = Op.getOperand(0);
17988   if (VT == MVT::i8) {
17989     // Zero extend to i32 since there is not an i8 bsr.
17990     OpVT = MVT::i32;
17991     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17992   }
17993
17994   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17995   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17996   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17997
17998   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17999   SDValue Ops[] = {
18000     Op,
18001     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18002     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18003     Op.getValue(1)
18004   };
18005   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18006
18007   // Finally xor with NumBits-1.
18008   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18009                    DAG.getConstant(NumBits - 1, dl, OpVT));
18010
18011   if (VT == MVT::i8)
18012     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18013   return Op;
18014 }
18015
18016 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18017                                     SelectionDAG &DAG) {
18018   MVT VT = Op.getSimpleValueType();
18019   EVT OpVT = VT;
18020   unsigned NumBits = VT.getSizeInBits();
18021   SDLoc dl(Op);
18022
18023   Op = Op.getOperand(0);
18024   if (VT == MVT::i8) {
18025     // Zero extend to i32 since there is not an i8 bsr.
18026     OpVT = MVT::i32;
18027     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18028   }
18029
18030   // Issue a bsr (scan bits in reverse).
18031   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18032   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18033
18034   // And xor with NumBits-1.
18035   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18036                    DAG.getConstant(NumBits - 1, dl, OpVT));
18037
18038   if (VT == MVT::i8)
18039     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18040   return Op;
18041 }
18042
18043 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18044   MVT VT = Op.getSimpleValueType();
18045   unsigned NumBits = VT.getScalarSizeInBits();
18046   SDLoc dl(Op);
18047
18048   if (VT.isVector()) {
18049     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18050
18051     SDValue N0 = Op.getOperand(0);
18052     SDValue Zero = DAG.getConstant(0, dl, VT);
18053
18054     // lsb(x) = (x & -x)
18055     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18056                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18057
18058     // cttz_undef(x) = (width - 1) - ctlz(lsb)
18059     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18060         TLI.isOperationLegal(ISD::CTLZ, VT)) {
18061       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18062       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18063                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18064     }
18065
18066     // cttz(x) = ctpop(lsb - 1)
18067     SDValue One = DAG.getConstant(1, dl, VT);
18068     return DAG.getNode(ISD::CTPOP, dl, VT,
18069                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18070   }
18071
18072   assert(Op.getOpcode() == ISD::CTTZ &&
18073          "Only scalar CTTZ requires custom lowering");
18074
18075   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18076   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18077   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18078
18079   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18080   SDValue Ops[] = {
18081     Op,
18082     DAG.getConstant(NumBits, dl, VT),
18083     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18084     Op.getValue(1)
18085   };
18086   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18087 }
18088
18089 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18090 // ones, and then concatenate the result back.
18091 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18092   MVT VT = Op.getSimpleValueType();
18093
18094   assert(VT.is256BitVector() && VT.isInteger() &&
18095          "Unsupported value type for operation");
18096
18097   unsigned NumElems = VT.getVectorNumElements();
18098   SDLoc dl(Op);
18099
18100   // Extract the LHS vectors
18101   SDValue LHS = Op.getOperand(0);
18102   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18103   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18104
18105   // Extract the RHS vectors
18106   SDValue RHS = Op.getOperand(1);
18107   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18108   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18109
18110   MVT EltVT = VT.getVectorElementType();
18111   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18112
18113   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18114                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18115                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18116 }
18117
18118 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18119   if (Op.getValueType() == MVT::i1)
18120     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18121                        Op.getOperand(0), Op.getOperand(1));
18122   assert(Op.getSimpleValueType().is256BitVector() &&
18123          Op.getSimpleValueType().isInteger() &&
18124          "Only handle AVX 256-bit vector integer operation");
18125   return Lower256IntArith(Op, DAG);
18126 }
18127
18128 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18129   if (Op.getValueType() == MVT::i1)
18130     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18131                        Op.getOperand(0), Op.getOperand(1));
18132   assert(Op.getSimpleValueType().is256BitVector() &&
18133          Op.getSimpleValueType().isInteger() &&
18134          "Only handle AVX 256-bit vector integer operation");
18135   return Lower256IntArith(Op, DAG);
18136 }
18137
18138 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18139   assert(Op.getSimpleValueType().is256BitVector() &&
18140          Op.getSimpleValueType().isInteger() &&
18141          "Only handle AVX 256-bit vector integer operation");
18142   return Lower256IntArith(Op, DAG);
18143 }
18144
18145 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18146                         SelectionDAG &DAG) {
18147   SDLoc dl(Op);
18148   MVT VT = Op.getSimpleValueType();
18149
18150   if (VT == MVT::i1)
18151     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18152
18153   // Decompose 256-bit ops into smaller 128-bit ops.
18154   if (VT.is256BitVector() && !Subtarget->hasInt256())
18155     return Lower256IntArith(Op, DAG);
18156
18157   SDValue A = Op.getOperand(0);
18158   SDValue B = Op.getOperand(1);
18159
18160   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18161   // pairs, multiply and truncate.
18162   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18163     if (Subtarget->hasInt256()) {
18164       if (VT == MVT::v32i8) {
18165         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18166         SDValue Lo = DAG.getIntPtrConstant(0, dl);
18167         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18168         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18169         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18170         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18171         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18172         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18173                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18174                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18175       }
18176
18177       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18178       return DAG.getNode(
18179           ISD::TRUNCATE, dl, VT,
18180           DAG.getNode(ISD::MUL, dl, ExVT,
18181                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18182                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18183     }
18184
18185     assert(VT == MVT::v16i8 &&
18186            "Pre-AVX2 support only supports v16i8 multiplication");
18187     MVT ExVT = MVT::v8i16;
18188
18189     // Extract the lo parts and sign extend to i16
18190     SDValue ALo, BLo;
18191     if (Subtarget->hasSSE41()) {
18192       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18193       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18194     } else {
18195       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18196                               -1, 4, -1, 5, -1, 6, -1, 7};
18197       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18198       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18199       ALo = DAG.getBitcast(ExVT, ALo);
18200       BLo = DAG.getBitcast(ExVT, BLo);
18201       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18202       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18203     }
18204
18205     // Extract the hi parts and sign extend to i16
18206     SDValue AHi, BHi;
18207     if (Subtarget->hasSSE41()) {
18208       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
18209                               -1, -1, -1, -1, -1, -1, -1, -1};
18210       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18211       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18212       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18213       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18214     } else {
18215       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
18216                               -1, 12, -1, 13, -1, 14, -1, 15};
18217       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18218       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18219       AHi = DAG.getBitcast(ExVT, AHi);
18220       BHi = DAG.getBitcast(ExVT, BHi);
18221       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18222       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18223     }
18224
18225     // Multiply, mask the lower 8bits of the lo/hi results and pack
18226     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18227     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18228     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18229     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18230     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18231   }
18232
18233   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18234   if (VT == MVT::v4i32) {
18235     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18236            "Should not custom lower when pmuldq is available!");
18237
18238     // Extract the odd parts.
18239     static const int UnpackMask[] = { 1, -1, 3, -1 };
18240     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18241     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18242
18243     // Multiply the even parts.
18244     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18245     // Now multiply odd parts.
18246     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18247
18248     Evens = DAG.getBitcast(VT, Evens);
18249     Odds = DAG.getBitcast(VT, Odds);
18250
18251     // Merge the two vectors back together with a shuffle. This expands into 2
18252     // shuffles.
18253     static const int ShufMask[] = { 0, 4, 2, 6 };
18254     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18255   }
18256
18257   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18258          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18259
18260   //  Ahi = psrlqi(a, 32);
18261   //  Bhi = psrlqi(b, 32);
18262   //
18263   //  AloBlo = pmuludq(a, b);
18264   //  AloBhi = pmuludq(a, Bhi);
18265   //  AhiBlo = pmuludq(Ahi, b);
18266
18267   //  AloBhi = psllqi(AloBhi, 32);
18268   //  AhiBlo = psllqi(AhiBlo, 32);
18269   //  return AloBlo + AloBhi + AhiBlo;
18270
18271   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18272   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18273
18274   SDValue AhiBlo = Ahi;
18275   SDValue AloBhi = Bhi;
18276   // Bit cast to 32-bit vectors for MULUDQ
18277   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18278                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18279   A = DAG.getBitcast(MulVT, A);
18280   B = DAG.getBitcast(MulVT, B);
18281   Ahi = DAG.getBitcast(MulVT, Ahi);
18282   Bhi = DAG.getBitcast(MulVT, Bhi);
18283
18284   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18285   // After shifting right const values the result may be all-zero.
18286   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18287     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18288     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18289   }
18290   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18291     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18292     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18293   }
18294
18295   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18296   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18297 }
18298
18299 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18300   assert(Subtarget->isTargetWin64() && "Unexpected target");
18301   EVT VT = Op.getValueType();
18302   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18303          "Unexpected return type for lowering");
18304
18305   RTLIB::Libcall LC;
18306   bool isSigned;
18307   switch (Op->getOpcode()) {
18308   default: llvm_unreachable("Unexpected request for libcall!");
18309   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18310   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18311   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18312   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18313   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18314   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18315   }
18316
18317   SDLoc dl(Op);
18318   SDValue InChain = DAG.getEntryNode();
18319
18320   TargetLowering::ArgListTy Args;
18321   TargetLowering::ArgListEntry Entry;
18322   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18323     EVT ArgVT = Op->getOperand(i).getValueType();
18324     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18325            "Unexpected argument type for lowering");
18326     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18327     Entry.Node = StackPtr;
18328     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18329                            false, false, 16);
18330     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18331     Entry.Ty = PointerType::get(ArgTy,0);
18332     Entry.isSExt = false;
18333     Entry.isZExt = false;
18334     Args.push_back(Entry);
18335   }
18336
18337   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18338                                          getPointerTy(DAG.getDataLayout()));
18339
18340   TargetLowering::CallLoweringInfo CLI(DAG);
18341   CLI.setDebugLoc(dl).setChain(InChain)
18342     .setCallee(getLibcallCallingConv(LC),
18343                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18344                Callee, std::move(Args), 0)
18345     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18346
18347   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18348   return DAG.getBitcast(VT, CallInfo.first);
18349 }
18350
18351 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18352                              SelectionDAG &DAG) {
18353   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18354   MVT VT = Op0.getSimpleValueType();
18355   SDLoc dl(Op);
18356
18357   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18358          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18359
18360   // PMULxD operations multiply each even value (starting at 0) of LHS with
18361   // the related value of RHS and produce a widen result.
18362   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18363   // => <2 x i64> <ae|cg>
18364   //
18365   // In other word, to have all the results, we need to perform two PMULxD:
18366   // 1. one with the even values.
18367   // 2. one with the odd values.
18368   // To achieve #2, with need to place the odd values at an even position.
18369   //
18370   // Place the odd value at an even position (basically, shift all values 1
18371   // step to the left):
18372   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18373   // <a|b|c|d> => <b|undef|d|undef>
18374   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18375   // <e|f|g|h> => <f|undef|h|undef>
18376   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18377
18378   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18379   // ints.
18380   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18381   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18382   unsigned Opcode =
18383       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18384   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18385   // => <2 x i64> <ae|cg>
18386   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18387   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18388   // => <2 x i64> <bf|dh>
18389   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18390
18391   // Shuffle it back into the right order.
18392   SDValue Highs, Lows;
18393   if (VT == MVT::v8i32) {
18394     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18395     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18396     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18397     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18398   } else {
18399     const int HighMask[] = {1, 5, 3, 7};
18400     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18401     const int LowMask[] = {0, 4, 2, 6};
18402     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18403   }
18404
18405   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18406   // unsigned multiply.
18407   if (IsSigned && !Subtarget->hasSSE41()) {
18408     SDValue ShAmt = DAG.getConstant(
18409         31, dl,
18410         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18411     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18412                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18413     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18414                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18415
18416     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18417     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18418   }
18419
18420   // The first result of MUL_LOHI is actually the low value, followed by the
18421   // high value.
18422   SDValue Ops[] = {Lows, Highs};
18423   return DAG.getMergeValues(Ops, dl);
18424 }
18425
18426 // Return true if the required (according to Opcode) shift-imm form is natively
18427 // supported by the Subtarget
18428 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18429                                         unsigned Opcode) {
18430   if (VT.getScalarSizeInBits() < 16)
18431     return false;
18432
18433   if (VT.is512BitVector() &&
18434       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18435     return true;
18436
18437   bool LShift = VT.is128BitVector() ||
18438     (VT.is256BitVector() && Subtarget->hasInt256());
18439
18440   bool AShift = LShift && (Subtarget->hasVLX() ||
18441     (VT != MVT::v2i64 && VT != MVT::v4i64));
18442   return (Opcode == ISD::SRA) ? AShift : LShift;
18443 }
18444
18445 // The shift amount is a variable, but it is the same for all vector lanes.
18446 // These instructions are defined together with shift-immediate.
18447 static
18448 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18449                                       unsigned Opcode) {
18450   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18451 }
18452
18453 // Return true if the required (according to Opcode) variable-shift form is
18454 // natively supported by the Subtarget
18455 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18456                                     unsigned Opcode) {
18457
18458   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18459     return false;
18460
18461   // vXi16 supported only on AVX-512, BWI
18462   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18463     return false;
18464
18465   if (VT.is512BitVector() || Subtarget->hasVLX())
18466     return true;
18467
18468   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18469   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18470   return (Opcode == ISD::SRA) ? AShift : LShift;
18471 }
18472
18473 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18474                                          const X86Subtarget *Subtarget) {
18475   MVT VT = Op.getSimpleValueType();
18476   SDLoc dl(Op);
18477   SDValue R = Op.getOperand(0);
18478   SDValue Amt = Op.getOperand(1);
18479
18480   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18481     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18482
18483   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18484     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18485     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18486     SDValue Ex = DAG.getBitcast(ExVT, R);
18487
18488     if (ShiftAmt >= 32) {
18489       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18490       SDValue Upper =
18491           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18492       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18493                                                  ShiftAmt - 32, DAG);
18494       if (VT == MVT::v2i64)
18495         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18496       if (VT == MVT::v4i64)
18497         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18498                                   {9, 1, 11, 3, 13, 5, 15, 7});
18499     } else {
18500       // SRA upper i32, SHL whole i64 and select lower i32.
18501       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18502                                                  ShiftAmt, DAG);
18503       SDValue Lower =
18504           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18505       Lower = DAG.getBitcast(ExVT, Lower);
18506       if (VT == MVT::v2i64)
18507         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18508       if (VT == MVT::v4i64)
18509         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18510                                   {8, 1, 10, 3, 12, 5, 14, 7});
18511     }
18512     return DAG.getBitcast(VT, Ex);
18513   };
18514
18515   // Optimize shl/srl/sra with constant shift amount.
18516   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18517     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18518       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18519
18520       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18521         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18522
18523       // i64 SRA needs to be performed as partial shifts.
18524       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18525           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18526         return ArithmeticShiftRight64(ShiftAmt);
18527
18528       if (VT == MVT::v16i8 ||
18529           (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18530           VT == MVT::v64i8) {
18531         unsigned NumElts = VT.getVectorNumElements();
18532         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18533
18534         // Simple i8 add case
18535         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18536           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18537
18538         // ashr(R, 7)  === cmp_slt(R, 0)
18539         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18540           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18541           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18542         }
18543
18544         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18545         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18546           return SDValue();
18547
18548         if (Op.getOpcode() == ISD::SHL) {
18549           // Make a large shift.
18550           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18551                                                    R, ShiftAmt, DAG);
18552           SHL = DAG.getBitcast(VT, SHL);
18553           // Zero out the rightmost bits.
18554           return DAG.getNode(ISD::AND, dl, VT, SHL,
18555                              DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18556         }
18557         if (Op.getOpcode() == ISD::SRL) {
18558           // Make a large shift.
18559           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18560                                                    R, ShiftAmt, DAG);
18561           SRL = DAG.getBitcast(VT, SRL);
18562           // Zero out the leftmost bits.
18563           return DAG.getNode(ISD::AND, dl, VT, SRL,
18564                              DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18565         }
18566         if (Op.getOpcode() == ISD::SRA) {
18567           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18568           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18569
18570           SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18571           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18572           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18573           return Res;
18574         }
18575         llvm_unreachable("Unknown shift opcode.");
18576       }
18577     }
18578   }
18579
18580   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18581   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18582       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18583
18584     // Peek through any splat that was introduced for i64 shift vectorization.
18585     int SplatIndex = -1;
18586     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18587       if (SVN->isSplat()) {
18588         SplatIndex = SVN->getSplatIndex();
18589         Amt = Amt.getOperand(0);
18590         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18591                "Splat shuffle referencing second operand");
18592       }
18593
18594     if (Amt.getOpcode() != ISD::BITCAST ||
18595         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18596       return SDValue();
18597
18598     Amt = Amt.getOperand(0);
18599     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18600                      VT.getVectorNumElements();
18601     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18602     uint64_t ShiftAmt = 0;
18603     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18604     for (unsigned i = 0; i != Ratio; ++i) {
18605       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18606       if (!C)
18607         return SDValue();
18608       // 6 == Log2(64)
18609       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18610     }
18611
18612     // Check remaining shift amounts (if not a splat).
18613     if (SplatIndex < 0) {
18614       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18615         uint64_t ShAmt = 0;
18616         for (unsigned j = 0; j != Ratio; ++j) {
18617           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18618           if (!C)
18619             return SDValue();
18620           // 6 == Log2(64)
18621           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18622         }
18623         if (ShAmt != ShiftAmt)
18624           return SDValue();
18625       }
18626     }
18627
18628     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18629       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18630
18631     if (Op.getOpcode() == ISD::SRA)
18632       return ArithmeticShiftRight64(ShiftAmt);
18633   }
18634
18635   return SDValue();
18636 }
18637
18638 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18639                                         const X86Subtarget* Subtarget) {
18640   MVT VT = Op.getSimpleValueType();
18641   SDLoc dl(Op);
18642   SDValue R = Op.getOperand(0);
18643   SDValue Amt = Op.getOperand(1);
18644
18645   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18646     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18647
18648   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18649     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18650
18651   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18652     SDValue BaseShAmt;
18653     MVT EltVT = VT.getVectorElementType();
18654
18655     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18656       // Check if this build_vector node is doing a splat.
18657       // If so, then set BaseShAmt equal to the splat value.
18658       BaseShAmt = BV->getSplatValue();
18659       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18660         BaseShAmt = SDValue();
18661     } else {
18662       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18663         Amt = Amt.getOperand(0);
18664
18665       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18666       if (SVN && SVN->isSplat()) {
18667         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18668         SDValue InVec = Amt.getOperand(0);
18669         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18670           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18671                  "Unexpected shuffle index found!");
18672           BaseShAmt = InVec.getOperand(SplatIdx);
18673         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18674            if (ConstantSDNode *C =
18675                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18676              if (C->getZExtValue() == SplatIdx)
18677                BaseShAmt = InVec.getOperand(1);
18678            }
18679         }
18680
18681         if (!BaseShAmt)
18682           // Avoid introducing an extract element from a shuffle.
18683           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18684                                   DAG.getIntPtrConstant(SplatIdx, dl));
18685       }
18686     }
18687
18688     if (BaseShAmt.getNode()) {
18689       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18690       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18691         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18692       else if (EltVT.bitsLT(MVT::i32))
18693         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18694
18695       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18696     }
18697   }
18698
18699   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18700   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18701       Amt.getOpcode() == ISD::BITCAST &&
18702       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18703     Amt = Amt.getOperand(0);
18704     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18705                      VT.getVectorNumElements();
18706     std::vector<SDValue> Vals(Ratio);
18707     for (unsigned i = 0; i != Ratio; ++i)
18708       Vals[i] = Amt.getOperand(i);
18709     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18710       for (unsigned j = 0; j != Ratio; ++j)
18711         if (Vals[j] != Amt.getOperand(i + j))
18712           return SDValue();
18713     }
18714
18715     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18716       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18717   }
18718   return SDValue();
18719 }
18720
18721 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18722                           SelectionDAG &DAG) {
18723   MVT VT = Op.getSimpleValueType();
18724   SDLoc dl(Op);
18725   SDValue R = Op.getOperand(0);
18726   SDValue Amt = Op.getOperand(1);
18727
18728   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18729   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18730
18731   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18732     return V;
18733
18734   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18735     return V;
18736
18737   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18738     return Op;
18739
18740   // XOP has 128-bit variable logical/arithmetic shifts.
18741   // +ve/-ve Amt = shift left/right.
18742   if (Subtarget->hasXOP() &&
18743       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18744        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18745     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18746       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18747       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18748     }
18749     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18750       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18751     if (Op.getOpcode() == ISD::SRA)
18752       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18753   }
18754
18755   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18756   // shifts per-lane and then shuffle the partial results back together.
18757   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18758     // Splat the shift amounts so the scalar shifts above will catch it.
18759     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18760     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18761     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18762     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18763     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18764   }
18765
18766   // i64 vector arithmetic shift can be emulated with the transform:
18767   // M = lshr(SIGN_BIT, Amt)
18768   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18769   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18770       Op.getOpcode() == ISD::SRA) {
18771     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18772     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18773     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18774     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18775     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18776     return R;
18777   }
18778
18779   // If possible, lower this packed shift into a vector multiply instead of
18780   // expanding it into a sequence of scalar shifts.
18781   // Do this only if the vector shift count is a constant build_vector.
18782   if (Op.getOpcode() == ISD::SHL &&
18783       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18784        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18785       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18786     SmallVector<SDValue, 8> Elts;
18787     MVT SVT = VT.getVectorElementType();
18788     unsigned SVTBits = SVT.getSizeInBits();
18789     APInt One(SVTBits, 1);
18790     unsigned NumElems = VT.getVectorNumElements();
18791
18792     for (unsigned i=0; i !=NumElems; ++i) {
18793       SDValue Op = Amt->getOperand(i);
18794       if (Op->getOpcode() == ISD::UNDEF) {
18795         Elts.push_back(Op);
18796         continue;
18797       }
18798
18799       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18800       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18801       uint64_t ShAmt = C.getZExtValue();
18802       if (ShAmt >= SVTBits) {
18803         Elts.push_back(DAG.getUNDEF(SVT));
18804         continue;
18805       }
18806       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18807     }
18808     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18809     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18810   }
18811
18812   // Lower SHL with variable shift amount.
18813   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18814     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18815
18816     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18817                      DAG.getConstant(0x3f800000U, dl, VT));
18818     Op = DAG.getBitcast(MVT::v4f32, Op);
18819     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18820     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18821   }
18822
18823   // If possible, lower this shift as a sequence of two shifts by
18824   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18825   // Example:
18826   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18827   //
18828   // Could be rewritten as:
18829   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18830   //
18831   // The advantage is that the two shifts from the example would be
18832   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18833   // the vector shift into four scalar shifts plus four pairs of vector
18834   // insert/extract.
18835   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18836       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18837     unsigned TargetOpcode = X86ISD::MOVSS;
18838     bool CanBeSimplified;
18839     // The splat value for the first packed shift (the 'X' from the example).
18840     SDValue Amt1 = Amt->getOperand(0);
18841     // The splat value for the second packed shift (the 'Y' from the example).
18842     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18843                                         Amt->getOperand(2);
18844
18845     // See if it is possible to replace this node with a sequence of
18846     // two shifts followed by a MOVSS/MOVSD
18847     if (VT == MVT::v4i32) {
18848       // Check if it is legal to use a MOVSS.
18849       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18850                         Amt2 == Amt->getOperand(3);
18851       if (!CanBeSimplified) {
18852         // Otherwise, check if we can still simplify this node using a MOVSD.
18853         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18854                           Amt->getOperand(2) == Amt->getOperand(3);
18855         TargetOpcode = X86ISD::MOVSD;
18856         Amt2 = Amt->getOperand(2);
18857       }
18858     } else {
18859       // Do similar checks for the case where the machine value type
18860       // is MVT::v8i16.
18861       CanBeSimplified = Amt1 == Amt->getOperand(1);
18862       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18863         CanBeSimplified = Amt2 == Amt->getOperand(i);
18864
18865       if (!CanBeSimplified) {
18866         TargetOpcode = X86ISD::MOVSD;
18867         CanBeSimplified = true;
18868         Amt2 = Amt->getOperand(4);
18869         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18870           CanBeSimplified = Amt1 == Amt->getOperand(i);
18871         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18872           CanBeSimplified = Amt2 == Amt->getOperand(j);
18873       }
18874     }
18875
18876     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18877         isa<ConstantSDNode>(Amt2)) {
18878       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18879       MVT CastVT = MVT::v4i32;
18880       SDValue Splat1 =
18881         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18882       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18883       SDValue Splat2 =
18884         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18885       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18886       if (TargetOpcode == X86ISD::MOVSD)
18887         CastVT = MVT::v2i64;
18888       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18889       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18890       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18891                                             BitCast1, DAG);
18892       return DAG.getBitcast(VT, Result);
18893     }
18894   }
18895
18896   // v4i32 Non Uniform Shifts.
18897   // If the shift amount is constant we can shift each lane using the SSE2
18898   // immediate shifts, else we need to zero-extend each lane to the lower i64
18899   // and shift using the SSE2 variable shifts.
18900   // The separate results can then be blended together.
18901   if (VT == MVT::v4i32) {
18902     unsigned Opc = Op.getOpcode();
18903     SDValue Amt0, Amt1, Amt2, Amt3;
18904     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18905       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18906       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18907       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18908       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18909     } else {
18910       // ISD::SHL is handled above but we include it here for completeness.
18911       switch (Opc) {
18912       default:
18913         llvm_unreachable("Unknown target vector shift node");
18914       case ISD::SHL:
18915         Opc = X86ISD::VSHL;
18916         break;
18917       case ISD::SRL:
18918         Opc = X86ISD::VSRL;
18919         break;
18920       case ISD::SRA:
18921         Opc = X86ISD::VSRA;
18922         break;
18923       }
18924       // The SSE2 shifts use the lower i64 as the same shift amount for
18925       // all lanes and the upper i64 is ignored. These shuffle masks
18926       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18927       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18928       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18929       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18930       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18931       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18932     }
18933
18934     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18935     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18936     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18937     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18938     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18939     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18940     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18941   }
18942
18943   if (VT == MVT::v16i8 ||
18944       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18945     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18946     unsigned ShiftOpcode = Op->getOpcode();
18947
18948     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18949       // On SSE41 targets we make use of the fact that VSELECT lowers
18950       // to PBLENDVB which selects bytes based just on the sign bit.
18951       if (Subtarget->hasSSE41()) {
18952         V0 = DAG.getBitcast(VT, V0);
18953         V1 = DAG.getBitcast(VT, V1);
18954         Sel = DAG.getBitcast(VT, Sel);
18955         return DAG.getBitcast(SelVT,
18956                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18957       }
18958       // On pre-SSE41 targets we test for the sign bit by comparing to
18959       // zero - a negative value will set all bits of the lanes to true
18960       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18961       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18962       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18963       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18964     };
18965
18966     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18967     // We can safely do this using i16 shifts as we're only interested in
18968     // the 3 lower bits of each byte.
18969     Amt = DAG.getBitcast(ExtVT, Amt);
18970     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18971     Amt = DAG.getBitcast(VT, Amt);
18972
18973     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18974       // r = VSELECT(r, shift(r, 4), a);
18975       SDValue M =
18976           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18977       R = SignBitSelect(VT, Amt, M, R);
18978
18979       // a += a
18980       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18981
18982       // r = VSELECT(r, shift(r, 2), a);
18983       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18984       R = SignBitSelect(VT, Amt, M, R);
18985
18986       // a += a
18987       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18988
18989       // return VSELECT(r, shift(r, 1), a);
18990       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18991       R = SignBitSelect(VT, Amt, M, R);
18992       return R;
18993     }
18994
18995     if (Op->getOpcode() == ISD::SRA) {
18996       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18997       // so we can correctly sign extend. We don't care what happens to the
18998       // lower byte.
18999       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19000       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19001       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19002       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19003       ALo = DAG.getBitcast(ExtVT, ALo);
19004       AHi = DAG.getBitcast(ExtVT, AHi);
19005       RLo = DAG.getBitcast(ExtVT, RLo);
19006       RHi = DAG.getBitcast(ExtVT, RHi);
19007
19008       // r = VSELECT(r, shift(r, 4), a);
19009       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19010                                 DAG.getConstant(4, dl, ExtVT));
19011       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19012                                 DAG.getConstant(4, dl, ExtVT));
19013       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19014       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19015
19016       // a += a
19017       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19018       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19019
19020       // r = VSELECT(r, shift(r, 2), a);
19021       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19022                         DAG.getConstant(2, dl, ExtVT));
19023       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19024                         DAG.getConstant(2, dl, ExtVT));
19025       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19026       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19027
19028       // a += a
19029       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19030       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19031
19032       // r = VSELECT(r, shift(r, 1), a);
19033       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19034                         DAG.getConstant(1, dl, ExtVT));
19035       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19036                         DAG.getConstant(1, dl, ExtVT));
19037       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19038       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19039
19040       // Logical shift the result back to the lower byte, leaving a zero upper
19041       // byte
19042       // meaning that we can safely pack with PACKUSWB.
19043       RLo =
19044           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19045       RHi =
19046           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19047       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19048     }
19049   }
19050
19051   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19052   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19053   // solution better.
19054   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19055     MVT ExtVT = MVT::v8i32;
19056     unsigned ExtOpc =
19057         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19058     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19059     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19060     return DAG.getNode(ISD::TRUNCATE, dl, VT,
19061                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19062   }
19063
19064   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19065     MVT ExtVT = MVT::v8i32;
19066     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19067     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19068     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19069     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19070     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19071     ALo = DAG.getBitcast(ExtVT, ALo);
19072     AHi = DAG.getBitcast(ExtVT, AHi);
19073     RLo = DAG.getBitcast(ExtVT, RLo);
19074     RHi = DAG.getBitcast(ExtVT, RHi);
19075     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19076     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19077     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19078     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19079     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19080   }
19081
19082   if (VT == MVT::v8i16) {
19083     unsigned ShiftOpcode = Op->getOpcode();
19084
19085     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19086       // On SSE41 targets we make use of the fact that VSELECT lowers
19087       // to PBLENDVB which selects bytes based just on the sign bit.
19088       if (Subtarget->hasSSE41()) {
19089         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19090         V0 = DAG.getBitcast(ExtVT, V0);
19091         V1 = DAG.getBitcast(ExtVT, V1);
19092         Sel = DAG.getBitcast(ExtVT, Sel);
19093         return DAG.getBitcast(
19094             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19095       }
19096       // On pre-SSE41 targets we splat the sign bit - a negative value will
19097       // set all bits of the lanes to true and VSELECT uses that in
19098       // its OR(AND(V0,C),AND(V1,~C)) lowering.
19099       SDValue C =
19100           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19101       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19102     };
19103
19104     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19105     if (Subtarget->hasSSE41()) {
19106       // On SSE41 targets we need to replicate the shift mask in both
19107       // bytes for PBLENDVB.
19108       Amt = DAG.getNode(
19109           ISD::OR, dl, VT,
19110           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19111           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19112     } else {
19113       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19114     }
19115
19116     // r = VSELECT(r, shift(r, 8), a);
19117     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19118     R = SignBitSelect(Amt, M, R);
19119
19120     // a += a
19121     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19122
19123     // r = VSELECT(r, shift(r, 4), a);
19124     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19125     R = SignBitSelect(Amt, M, R);
19126
19127     // a += a
19128     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19129
19130     // r = VSELECT(r, shift(r, 2), a);
19131     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19132     R = SignBitSelect(Amt, M, R);
19133
19134     // a += a
19135     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19136
19137     // return VSELECT(r, shift(r, 1), a);
19138     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19139     R = SignBitSelect(Amt, M, R);
19140     return R;
19141   }
19142
19143   // Decompose 256-bit shifts into smaller 128-bit shifts.
19144   if (VT.is256BitVector()) {
19145     unsigned NumElems = VT.getVectorNumElements();
19146     MVT EltVT = VT.getVectorElementType();
19147     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19148
19149     // Extract the two vectors
19150     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19151     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19152
19153     // Recreate the shift amount vectors
19154     SDValue Amt1, Amt2;
19155     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19156       // Constant shift amount
19157       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19158       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19159       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19160
19161       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19162       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19163     } else {
19164       // Variable shift amount
19165       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19166       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19167     }
19168
19169     // Issue new vector shifts for the smaller types
19170     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19171     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19172
19173     // Concatenate the result back
19174     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19175   }
19176
19177   return SDValue();
19178 }
19179
19180 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19181                            SelectionDAG &DAG) {
19182   MVT VT = Op.getSimpleValueType();
19183   SDLoc DL(Op);
19184   SDValue R = Op.getOperand(0);
19185   SDValue Amt = Op.getOperand(1);
19186
19187   assert(VT.isVector() && "Custom lowering only for vector rotates!");
19188   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19189   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19190
19191   // XOP has 128-bit vector variable + immediate rotates.
19192   // +ve/-ve Amt = rotate left/right.
19193
19194   // Split 256-bit integers.
19195   if (VT.is256BitVector())
19196     return Lower256IntArith(Op, DAG);
19197
19198   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19199
19200   // Attempt to rotate by immediate.
19201   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19202     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19203       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19204       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19205       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19206                          DAG.getConstant(RotateAmt, DL, MVT::i8));
19207     }
19208   }
19209
19210   // Use general rotate by variable (per-element).
19211   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19212 }
19213
19214 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19215   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19216   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19217   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19218   // has only one use.
19219   SDNode *N = Op.getNode();
19220   SDValue LHS = N->getOperand(0);
19221   SDValue RHS = N->getOperand(1);
19222   unsigned BaseOp = 0;
19223   unsigned Cond = 0;
19224   SDLoc DL(Op);
19225   switch (Op.getOpcode()) {
19226   default: llvm_unreachable("Unknown ovf instruction!");
19227   case ISD::SADDO:
19228     // A subtract of one will be selected as a INC. Note that INC doesn't
19229     // set CF, so we can't do this for UADDO.
19230     if (isOneConstant(RHS)) {
19231         BaseOp = X86ISD::INC;
19232         Cond = X86::COND_O;
19233         break;
19234       }
19235     BaseOp = X86ISD::ADD;
19236     Cond = X86::COND_O;
19237     break;
19238   case ISD::UADDO:
19239     BaseOp = X86ISD::ADD;
19240     Cond = X86::COND_B;
19241     break;
19242   case ISD::SSUBO:
19243     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19244     // set CF, so we can't do this for USUBO.
19245     if (isOneConstant(RHS)) {
19246         BaseOp = X86ISD::DEC;
19247         Cond = X86::COND_O;
19248         break;
19249       }
19250     BaseOp = X86ISD::SUB;
19251     Cond = X86::COND_O;
19252     break;
19253   case ISD::USUBO:
19254     BaseOp = X86ISD::SUB;
19255     Cond = X86::COND_B;
19256     break;
19257   case ISD::SMULO:
19258     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19259     Cond = X86::COND_O;
19260     break;
19261   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19262     if (N->getValueType(0) == MVT::i8) {
19263       BaseOp = X86ISD::UMUL8;
19264       Cond = X86::COND_O;
19265       break;
19266     }
19267     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19268                                  MVT::i32);
19269     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19270
19271     SDValue SetCC =
19272       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19273                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19274                   SDValue(Sum.getNode(), 2));
19275
19276     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19277   }
19278   }
19279
19280   // Also sets EFLAGS.
19281   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19282   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19283
19284   SDValue SetCC =
19285     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19286                 DAG.getConstant(Cond, DL, MVT::i32),
19287                 SDValue(Sum.getNode(), 1));
19288
19289   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19290 }
19291
19292 /// Returns true if the operand type is exactly twice the native width, and
19293 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19294 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19295 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19296 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19297   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19298
19299   if (OpWidth == 64)
19300     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19301   else if (OpWidth == 128)
19302     return Subtarget->hasCmpxchg16b();
19303   else
19304     return false;
19305 }
19306
19307 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19308   return needsCmpXchgNb(SI->getValueOperand()->getType());
19309 }
19310
19311 // Note: this turns large loads into lock cmpxchg8b/16b.
19312 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19313 TargetLowering::AtomicExpansionKind
19314 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19315   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19316   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19317                                                : AtomicExpansionKind::None;
19318 }
19319
19320 TargetLowering::AtomicExpansionKind
19321 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19322   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19323   Type *MemType = AI->getType();
19324
19325   // If the operand is too big, we must see if cmpxchg8/16b is available
19326   // and default to library calls otherwise.
19327   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19328     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19329                                    : AtomicExpansionKind::None;
19330   }
19331
19332   AtomicRMWInst::BinOp Op = AI->getOperation();
19333   switch (Op) {
19334   default:
19335     llvm_unreachable("Unknown atomic operation");
19336   case AtomicRMWInst::Xchg:
19337   case AtomicRMWInst::Add:
19338   case AtomicRMWInst::Sub:
19339     // It's better to use xadd, xsub or xchg for these in all cases.
19340     return AtomicExpansionKind::None;
19341   case AtomicRMWInst::Or:
19342   case AtomicRMWInst::And:
19343   case AtomicRMWInst::Xor:
19344     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19345     // prefix to a normal instruction for these operations.
19346     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19347                             : AtomicExpansionKind::None;
19348   case AtomicRMWInst::Nand:
19349   case AtomicRMWInst::Max:
19350   case AtomicRMWInst::Min:
19351   case AtomicRMWInst::UMax:
19352   case AtomicRMWInst::UMin:
19353     // These always require a non-trivial set of data operations on x86. We must
19354     // use a cmpxchg loop.
19355     return AtomicExpansionKind::CmpXChg;
19356   }
19357 }
19358
19359 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19360   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19361   // no-sse2). There isn't any reason to disable it if the target processor
19362   // supports it.
19363   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19364 }
19365
19366 LoadInst *
19367 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19368   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19369   Type *MemType = AI->getType();
19370   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19371   // there is no benefit in turning such RMWs into loads, and it is actually
19372   // harmful as it introduces a mfence.
19373   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19374     return nullptr;
19375
19376   auto Builder = IRBuilder<>(AI);
19377   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19378   auto SynchScope = AI->getSynchScope();
19379   // We must restrict the ordering to avoid generating loads with Release or
19380   // ReleaseAcquire orderings.
19381   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19382   auto Ptr = AI->getPointerOperand();
19383
19384   // Before the load we need a fence. Here is an example lifted from
19385   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19386   // is required:
19387   // Thread 0:
19388   //   x.store(1, relaxed);
19389   //   r1 = y.fetch_add(0, release);
19390   // Thread 1:
19391   //   y.fetch_add(42, acquire);
19392   //   r2 = x.load(relaxed);
19393   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19394   // lowered to just a load without a fence. A mfence flushes the store buffer,
19395   // making the optimization clearly correct.
19396   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19397   // otherwise, we might be able to be more aggressive on relaxed idempotent
19398   // rmw. In practice, they do not look useful, so we don't try to be
19399   // especially clever.
19400   if (SynchScope == SingleThread)
19401     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19402     // the IR level, so we must wrap it in an intrinsic.
19403     return nullptr;
19404
19405   if (!hasMFENCE(*Subtarget))
19406     // FIXME: it might make sense to use a locked operation here but on a
19407     // different cache-line to prevent cache-line bouncing. In practice it
19408     // is probably a small win, and x86 processors without mfence are rare
19409     // enough that we do not bother.
19410     return nullptr;
19411
19412   Function *MFence =
19413       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19414   Builder.CreateCall(MFence, {});
19415
19416   // Finally we can emit the atomic load.
19417   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19418           AI->getType()->getPrimitiveSizeInBits());
19419   Loaded->setAtomic(Order, SynchScope);
19420   AI->replaceAllUsesWith(Loaded);
19421   AI->eraseFromParent();
19422   return Loaded;
19423 }
19424
19425 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19426                                  SelectionDAG &DAG) {
19427   SDLoc dl(Op);
19428   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19429     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19430   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19431     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19432
19433   // The only fence that needs an instruction is a sequentially-consistent
19434   // cross-thread fence.
19435   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19436     if (hasMFENCE(*Subtarget))
19437       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19438
19439     SDValue Chain = Op.getOperand(0);
19440     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19441     SDValue Ops[] = {
19442       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19443       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19444       DAG.getRegister(0, MVT::i32),            // Index
19445       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19446       DAG.getRegister(0, MVT::i32),            // Segment.
19447       Zero,
19448       Chain
19449     };
19450     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19451     return SDValue(Res, 0);
19452   }
19453
19454   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19455   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19456 }
19457
19458 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19459                              SelectionDAG &DAG) {
19460   MVT T = Op.getSimpleValueType();
19461   SDLoc DL(Op);
19462   unsigned Reg = 0;
19463   unsigned size = 0;
19464   switch(T.SimpleTy) {
19465   default: llvm_unreachable("Invalid value type!");
19466   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19467   case MVT::i16: Reg = X86::AX;  size = 2; break;
19468   case MVT::i32: Reg = X86::EAX; size = 4; break;
19469   case MVT::i64:
19470     assert(Subtarget->is64Bit() && "Node not type legal!");
19471     Reg = X86::RAX; size = 8;
19472     break;
19473   }
19474   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19475                                   Op.getOperand(2), SDValue());
19476   SDValue Ops[] = { cpIn.getValue(0),
19477                     Op.getOperand(1),
19478                     Op.getOperand(3),
19479                     DAG.getTargetConstant(size, DL, MVT::i8),
19480                     cpIn.getValue(1) };
19481   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19482   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19483   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19484                                            Ops, T, MMO);
19485
19486   SDValue cpOut =
19487     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19488   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19489                                       MVT::i32, cpOut.getValue(2));
19490   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19491                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19492                                 EFLAGS);
19493
19494   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19495   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19496   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19497   return SDValue();
19498 }
19499
19500 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19501                             SelectionDAG &DAG) {
19502   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19503   MVT DstVT = Op.getSimpleValueType();
19504
19505   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19506     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19507     if (DstVT != MVT::f64)
19508       // This conversion needs to be expanded.
19509       return SDValue();
19510
19511     SDValue InVec = Op->getOperand(0);
19512     SDLoc dl(Op);
19513     unsigned NumElts = SrcVT.getVectorNumElements();
19514     MVT SVT = SrcVT.getVectorElementType();
19515
19516     // Widen the vector in input in the case of MVT::v2i32.
19517     // Example: from MVT::v2i32 to MVT::v4i32.
19518     SmallVector<SDValue, 16> Elts;
19519     for (unsigned i = 0, e = NumElts; i != e; ++i)
19520       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19521                                  DAG.getIntPtrConstant(i, dl)));
19522
19523     // Explicitly mark the extra elements as Undef.
19524     Elts.append(NumElts, DAG.getUNDEF(SVT));
19525
19526     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19527     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19528     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19529     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19530                        DAG.getIntPtrConstant(0, dl));
19531   }
19532
19533   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19534          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19535   assert((DstVT == MVT::i64 ||
19536           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19537          "Unexpected custom BITCAST");
19538   // i64 <=> MMX conversions are Legal.
19539   if (SrcVT==MVT::i64 && DstVT.isVector())
19540     return Op;
19541   if (DstVT==MVT::i64 && SrcVT.isVector())
19542     return Op;
19543   // MMX <=> MMX conversions are Legal.
19544   if (SrcVT.isVector() && DstVT.isVector())
19545     return Op;
19546   // All other conversions need to be expanded.
19547   return SDValue();
19548 }
19549
19550 /// Compute the horizontal sum of bytes in V for the elements of VT.
19551 ///
19552 /// Requires V to be a byte vector and VT to be an integer vector type with
19553 /// wider elements than V's type. The width of the elements of VT determines
19554 /// how many bytes of V are summed horizontally to produce each element of the
19555 /// result.
19556 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19557                                       const X86Subtarget *Subtarget,
19558                                       SelectionDAG &DAG) {
19559   SDLoc DL(V);
19560   MVT ByteVecVT = V.getSimpleValueType();
19561   MVT EltVT = VT.getVectorElementType();
19562   int NumElts = VT.getVectorNumElements();
19563   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19564          "Expected value to have byte element type.");
19565   assert(EltVT != MVT::i8 &&
19566          "Horizontal byte sum only makes sense for wider elements!");
19567   unsigned VecSize = VT.getSizeInBits();
19568   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19569
19570   // PSADBW instruction horizontally add all bytes and leave the result in i64
19571   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19572   if (EltVT == MVT::i64) {
19573     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19574     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19575     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19576     return DAG.getBitcast(VT, V);
19577   }
19578
19579   if (EltVT == MVT::i32) {
19580     // We unpack the low half and high half into i32s interleaved with zeros so
19581     // that we can use PSADBW to horizontally sum them. The most useful part of
19582     // this is that it lines up the results of two PSADBW instructions to be
19583     // two v2i64 vectors which concatenated are the 4 population counts. We can
19584     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19585     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19586     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19587     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19588
19589     // Do the horizontal sums into two v2i64s.
19590     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19591     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19592     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19593                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19594     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19595                        DAG.getBitcast(ByteVecVT, High), Zeros);
19596
19597     // Merge them together.
19598     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19599     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19600                     DAG.getBitcast(ShortVecVT, Low),
19601                     DAG.getBitcast(ShortVecVT, High));
19602
19603     return DAG.getBitcast(VT, V);
19604   }
19605
19606   // The only element type left is i16.
19607   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19608
19609   // To obtain pop count for each i16 element starting from the pop count for
19610   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19611   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19612   // directly supported.
19613   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19614   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19615   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19616   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19617                   DAG.getBitcast(ByteVecVT, V));
19618   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19619 }
19620
19621 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19622                                         const X86Subtarget *Subtarget,
19623                                         SelectionDAG &DAG) {
19624   MVT VT = Op.getSimpleValueType();
19625   MVT EltVT = VT.getVectorElementType();
19626   unsigned VecSize = VT.getSizeInBits();
19627
19628   // Implement a lookup table in register by using an algorithm based on:
19629   // http://wm.ite.pl/articles/sse-popcount.html
19630   //
19631   // The general idea is that every lower byte nibble in the input vector is an
19632   // index into a in-register pre-computed pop count table. We then split up the
19633   // input vector in two new ones: (1) a vector with only the shifted-right
19634   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19635   // masked out higher ones) for each byte. PSHUB is used separately with both
19636   // to index the in-register table. Next, both are added and the result is a
19637   // i8 vector where each element contains the pop count for input byte.
19638   //
19639   // To obtain the pop count for elements != i8, we follow up with the same
19640   // approach and use additional tricks as described below.
19641   //
19642   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19643                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19644                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19645                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19646
19647   int NumByteElts = VecSize / 8;
19648   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19649   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19650   SmallVector<SDValue, 16> LUTVec;
19651   for (int i = 0; i < NumByteElts; ++i)
19652     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19653   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19654   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19655                                   DAG.getConstant(0x0F, DL, MVT::i8));
19656   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19657
19658   // High nibbles
19659   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19660   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19661   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19662
19663   // Low nibbles
19664   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19665
19666   // The input vector is used as the shuffle mask that index elements into the
19667   // LUT. After counting low and high nibbles, add the vector to obtain the
19668   // final pop count per i8 element.
19669   SDValue HighPopCnt =
19670       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19671   SDValue LowPopCnt =
19672       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19673   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19674
19675   if (EltVT == MVT::i8)
19676     return PopCnt;
19677
19678   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19679 }
19680
19681 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19682                                        const X86Subtarget *Subtarget,
19683                                        SelectionDAG &DAG) {
19684   MVT VT = Op.getSimpleValueType();
19685   assert(VT.is128BitVector() &&
19686          "Only 128-bit vector bitmath lowering supported.");
19687
19688   int VecSize = VT.getSizeInBits();
19689   MVT EltVT = VT.getVectorElementType();
19690   int Len = EltVT.getSizeInBits();
19691
19692   // This is the vectorized version of the "best" algorithm from
19693   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19694   // with a minor tweak to use a series of adds + shifts instead of vector
19695   // multiplications. Implemented for all integer vector types. We only use
19696   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19697   // much faster, even faster than using native popcnt instructions.
19698
19699   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19700     MVT VT = V.getSimpleValueType();
19701     SmallVector<SDValue, 32> Shifters(
19702         VT.getVectorNumElements(),
19703         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19704     return DAG.getNode(OpCode, DL, VT, V,
19705                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19706   };
19707   auto GetMask = [&](SDValue V, APInt Mask) {
19708     MVT VT = V.getSimpleValueType();
19709     SmallVector<SDValue, 32> Masks(
19710         VT.getVectorNumElements(),
19711         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19712     return DAG.getNode(ISD::AND, DL, VT, V,
19713                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19714   };
19715
19716   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19717   // x86, so set the SRL type to have elements at least i16 wide. This is
19718   // correct because all of our SRLs are followed immediately by a mask anyways
19719   // that handles any bits that sneak into the high bits of the byte elements.
19720   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19721
19722   SDValue V = Op;
19723
19724   // v = v - ((v >> 1) & 0x55555555...)
19725   SDValue Srl =
19726       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19727   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19728   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19729
19730   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19731   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19732   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19733   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19734   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19735
19736   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19737   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19738   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19739   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19740
19741   // At this point, V contains the byte-wise population count, and we are
19742   // merely doing a horizontal sum if necessary to get the wider element
19743   // counts.
19744   if (EltVT == MVT::i8)
19745     return V;
19746
19747   return LowerHorizontalByteSum(
19748       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19749       DAG);
19750 }
19751
19752 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19753                                 SelectionDAG &DAG) {
19754   MVT VT = Op.getSimpleValueType();
19755   // FIXME: Need to add AVX-512 support here!
19756   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19757          "Unknown CTPOP type to handle");
19758   SDLoc DL(Op.getNode());
19759   SDValue Op0 = Op.getOperand(0);
19760
19761   if (!Subtarget->hasSSSE3()) {
19762     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19763     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19764     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19765   }
19766
19767   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19768     unsigned NumElems = VT.getVectorNumElements();
19769
19770     // Extract each 128-bit vector, compute pop count and concat the result.
19771     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19772     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19773
19774     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19775                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19776                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19777   }
19778
19779   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19780 }
19781
19782 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19783                           SelectionDAG &DAG) {
19784   assert(Op.getSimpleValueType().isVector() &&
19785          "We only do custom lowering for vector population count.");
19786   return LowerVectorCTPOP(Op, Subtarget, DAG);
19787 }
19788
19789 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19790   SDNode *Node = Op.getNode();
19791   SDLoc dl(Node);
19792   EVT T = Node->getValueType(0);
19793   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19794                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19795   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19796                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19797                        Node->getOperand(0),
19798                        Node->getOperand(1), negOp,
19799                        cast<AtomicSDNode>(Node)->getMemOperand(),
19800                        cast<AtomicSDNode>(Node)->getOrdering(),
19801                        cast<AtomicSDNode>(Node)->getSynchScope());
19802 }
19803
19804 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19805   SDNode *Node = Op.getNode();
19806   SDLoc dl(Node);
19807   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19808
19809   // Convert seq_cst store -> xchg
19810   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19811   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19812   //        (The only way to get a 16-byte store is cmpxchg16b)
19813   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19814   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19815       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19816     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19817                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19818                                  Node->getOperand(0),
19819                                  Node->getOperand(1), Node->getOperand(2),
19820                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19821                                  cast<AtomicSDNode>(Node)->getOrdering(),
19822                                  cast<AtomicSDNode>(Node)->getSynchScope());
19823     return Swap.getValue(1);
19824   }
19825   // Other atomic stores have a simple pattern.
19826   return Op;
19827 }
19828
19829 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19830   MVT VT = Op.getNode()->getSimpleValueType(0);
19831
19832   // Let legalize expand this if it isn't a legal type yet.
19833   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19834     return SDValue();
19835
19836   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19837
19838   unsigned Opc;
19839   bool ExtraOp = false;
19840   switch (Op.getOpcode()) {
19841   default: llvm_unreachable("Invalid code");
19842   case ISD::ADDC: Opc = X86ISD::ADD; break;
19843   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19844   case ISD::SUBC: Opc = X86ISD::SUB; break;
19845   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19846   }
19847
19848   if (!ExtraOp)
19849     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19850                        Op.getOperand(1));
19851   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19852                      Op.getOperand(1), Op.getOperand(2));
19853 }
19854
19855 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19856                             SelectionDAG &DAG) {
19857   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19858
19859   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19860   // which returns the values as { float, float } (in XMM0) or
19861   // { double, double } (which is returned in XMM0, XMM1).
19862   SDLoc dl(Op);
19863   SDValue Arg = Op.getOperand(0);
19864   EVT ArgVT = Arg.getValueType();
19865   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19866
19867   TargetLowering::ArgListTy Args;
19868   TargetLowering::ArgListEntry Entry;
19869
19870   Entry.Node = Arg;
19871   Entry.Ty = ArgTy;
19872   Entry.isSExt = false;
19873   Entry.isZExt = false;
19874   Args.push_back(Entry);
19875
19876   bool isF64 = ArgVT == MVT::f64;
19877   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19878   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19879   // the results are returned via SRet in memory.
19880   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19882   SDValue Callee =
19883       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19884
19885   Type *RetTy = isF64
19886     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19887     : (Type*)VectorType::get(ArgTy, 4);
19888
19889   TargetLowering::CallLoweringInfo CLI(DAG);
19890   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19891     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19892
19893   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19894
19895   if (isF64)
19896     // Returned in xmm0 and xmm1.
19897     return CallResult.first;
19898
19899   // Returned in bits 0:31 and 32:64 xmm0.
19900   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19901                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19902   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19903                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19904   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19905   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19906 }
19907
19908 /// Widen a vector input to a vector of NVT.  The
19909 /// input vector must have the same element type as NVT.
19910 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19911                             bool FillWithZeroes = false) {
19912   // Check if InOp already has the right width.
19913   MVT InVT = InOp.getSimpleValueType();
19914   if (InVT == NVT)
19915     return InOp;
19916
19917   if (InOp.isUndef())
19918     return DAG.getUNDEF(NVT);
19919
19920   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19921          "input and widen element type must match");
19922
19923   unsigned InNumElts = InVT.getVectorNumElements();
19924   unsigned WidenNumElts = NVT.getVectorNumElements();
19925   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
19926          "Unexpected request for vector widening");
19927
19928   EVT EltVT = NVT.getVectorElementType();
19929
19930   SDLoc dl(InOp);
19931   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
19932       InOp.getNumOperands() == 2) {
19933     SDValue N1 = InOp.getOperand(1);
19934     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
19935         N1.isUndef()) {
19936       InOp = InOp.getOperand(0);
19937       InVT = InOp.getSimpleValueType();
19938       InNumElts = InVT.getVectorNumElements();
19939     }
19940   }
19941   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
19942       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
19943     SmallVector<SDValue, 16> Ops;
19944     for (unsigned i = 0; i < InNumElts; ++i)
19945       Ops.push_back(InOp.getOperand(i));
19946
19947     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
19948       DAG.getUNDEF(EltVT);
19949     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
19950       Ops.push_back(FillVal);
19951     return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
19952   }
19953   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
19954     DAG.getUNDEF(NVT);
19955   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
19956                      InOp, DAG.getIntPtrConstant(0, dl));
19957 }
19958
19959 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19960                              SelectionDAG &DAG) {
19961   assert(Subtarget->hasAVX512() &&
19962          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19963
19964   // X86 scatter kills mask register, so its type should be added to
19965   // the list of return values.
19966   // If the "scatter" has 2 return values, it is already handled.
19967   if (Op.getNode()->getNumValues() == 2)
19968     return Op;
19969
19970   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19971   SDValue Src = N->getValue();
19972   MVT VT = Src.getSimpleValueType();
19973   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19974   SDLoc dl(Op);
19975
19976   SDValue NewScatter;
19977   SDValue Index = N->getIndex();
19978   SDValue Mask = N->getMask();
19979   SDValue Chain = N->getChain();
19980   SDValue BasePtr = N->getBasePtr();
19981   MVT MemVT = N->getMemoryVT().getSimpleVT();
19982   MVT IndexVT = Index.getSimpleValueType();
19983   MVT MaskVT = Mask.getSimpleValueType();
19984
19985   if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
19986     // The v2i32 value was promoted to v2i64.
19987     // Now we "redo" the type legalizer's work and widen the original
19988     // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
19989     // with a shuffle.
19990     assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
19991            "Unexpected memory type");
19992     int ShuffleMask[] = {0, 2, -1, -1};
19993     Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
19994                                DAG.getUNDEF(MVT::v4i32), ShuffleMask);
19995     // Now we have 4 elements instead of 2.
19996     // Expand the index.
19997     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
19998     Index = ExtendToType(Index, NewIndexVT, DAG);
19999
20000     // Expand the mask with zeroes
20001     // Mask may be <2 x i64> or <2 x i1> at this moment
20002     assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20003            "Unexpected mask type");
20004     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20005     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20006     VT = MVT::v4i32;
20007   }
20008
20009   unsigned NumElts = VT.getVectorNumElements();
20010   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20011       !Index.getSimpleValueType().is512BitVector()) {
20012     // AVX512F supports only 512-bit vectors. Or data or index should
20013     // be 512 bit wide. If now the both index and data are 256-bit, but
20014     // the vector contains 8 elements, we just sign-extend the index
20015     if (IndexVT == MVT::v8i32)
20016       // Just extend index
20017       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20018     else {
20019       // The minimal number of elts in scatter is 8
20020       NumElts = 8;
20021       // Index
20022       MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20023       // Use original index here, do not modify the index twice
20024       Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20025       if (IndexVT.getScalarType() == MVT::i32)
20026         Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20027
20028       // Mask
20029       // At this point we have promoted mask operand
20030       assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20031       MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20032       // Use the original mask here, do not modify the mask twice
20033       Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20034
20035       // The value that should be stored
20036       MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20037       Src = ExtendToType(Src, NewVT, DAG);
20038     }
20039   }
20040   // If the mask is "wide" at this point - truncate it to i1 vector
20041   MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20042   Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20043
20044   // The mask is killed by scatter, add it to the values
20045   SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20046   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20047   NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20048                                     N->getMemOperand());
20049   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20050   return SDValue(NewScatter.getNode(), 0);
20051 }
20052
20053 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20054                           SelectionDAG &DAG) {
20055
20056   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20057   MVT VT = Op.getSimpleValueType();
20058   SDValue Mask = N->getMask();
20059   SDLoc dl(Op);
20060
20061   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20062       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20063     // This operation is legal for targets with VLX, but without
20064     // VLX the vector should be widened to 512 bit
20065     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20066     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20067     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20068     SDValue Src0 = N->getSrc0();
20069     Src0 = ExtendToType(Src0, WideDataVT, DAG);
20070     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20071     SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20072                                         N->getBasePtr(), Mask, Src0,
20073                                         N->getMemoryVT(), N->getMemOperand(),
20074                                         N->getExtensionType());
20075
20076     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20077                                  NewLoad.getValue(0),
20078                                  DAG.getIntPtrConstant(0, dl));
20079     SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20080     return DAG.getMergeValues(RetOps, dl);
20081   }
20082   return Op;
20083 }
20084
20085 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20086                            SelectionDAG &DAG) {
20087   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20088   SDValue DataToStore = N->getValue();
20089   MVT VT = DataToStore.getSimpleValueType();
20090   SDValue Mask = N->getMask();
20091   SDLoc dl(Op);
20092
20093   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20094       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20095     // This operation is legal for targets with VLX, but without
20096     // VLX the vector should be widened to 512 bit
20097     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20098     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20099     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20100     DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20101     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20102     return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20103                               Mask, N->getMemoryVT(), N->getMemOperand(),
20104                               N->isTruncatingStore());
20105   }
20106   return Op;
20107 }
20108
20109 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20110                             SelectionDAG &DAG) {
20111   assert(Subtarget->hasAVX512() &&
20112          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20113
20114   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20115   SDLoc dl(Op);
20116   MVT VT = Op.getSimpleValueType();
20117   SDValue Index = N->getIndex();
20118   SDValue Mask = N->getMask();
20119   SDValue Src0 = N->getValue();
20120   MVT IndexVT = Index.getSimpleValueType();
20121   MVT MaskVT = Mask.getSimpleValueType();
20122
20123   unsigned NumElts = VT.getVectorNumElements();
20124   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20125
20126   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20127       !Index.getSimpleValueType().is512BitVector()) {
20128     // AVX512F supports only 512-bit vectors. Or data or index should
20129     // be 512 bit wide. If now the both index and data are 256-bit, but
20130     // the vector contains 8 elements, we just sign-extend the index
20131     if (NumElts == 8) {
20132       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20133       SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
20134                         N->getOperand(3), Index };
20135       DAG.UpdateNodeOperands(N, Ops);
20136       return Op;
20137     }
20138
20139     // Minimal number of elements in Gather
20140     NumElts = 8;
20141     // Index
20142     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20143     Index = ExtendToType(Index, NewIndexVT, DAG);
20144     if (IndexVT.getScalarType() == MVT::i32)
20145       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20146
20147     // Mask
20148     MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20149     // At this point we have promoted mask operand
20150     assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20151     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20152     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20153     Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20154
20155     // The pass-thru value
20156     MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20157     Src0 = ExtendToType(Src0, NewVT, DAG);
20158
20159     SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20160     SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20161                                             N->getMemoryVT(), dl, Ops,
20162                                             N->getMemOperand());
20163     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20164                                  NewGather.getValue(0),
20165                                  DAG.getIntPtrConstant(0, dl));
20166     SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20167     return DAG.getMergeValues(RetOps, dl);
20168   }
20169   return Op;
20170 }
20171
20172 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20173                                                     SelectionDAG &DAG) const {
20174   // TODO: Eventually, the lowering of these nodes should be informed by or
20175   // deferred to the GC strategy for the function in which they appear. For
20176   // now, however, they must be lowered to something. Since they are logically
20177   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20178   // require special handling for these nodes), lower them as literal NOOPs for
20179   // the time being.
20180   SmallVector<SDValue, 2> Ops;
20181
20182   Ops.push_back(Op.getOperand(0));
20183   if (Op->getGluedNode())
20184     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20185
20186   SDLoc OpDL(Op);
20187   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20188   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20189
20190   return NOOP;
20191 }
20192
20193 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20194                                                   SelectionDAG &DAG) const {
20195   // TODO: Eventually, the lowering of these nodes should be informed by or
20196   // deferred to the GC strategy for the function in which they appear. For
20197   // now, however, they must be lowered to something. Since they are logically
20198   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20199   // require special handling for these nodes), lower them as literal NOOPs for
20200   // the time being.
20201   SmallVector<SDValue, 2> Ops;
20202
20203   Ops.push_back(Op.getOperand(0));
20204   if (Op->getGluedNode())
20205     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20206
20207   SDLoc OpDL(Op);
20208   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20209   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20210
20211   return NOOP;
20212 }
20213
20214 /// LowerOperation - Provide custom lowering hooks for some operations.
20215 ///
20216 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20217   switch (Op.getOpcode()) {
20218   default: llvm_unreachable("Should not custom lower this!");
20219   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20220   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20221     return LowerCMP_SWAP(Op, Subtarget, DAG);
20222   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
20223   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
20224   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
20225   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
20226   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20227   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
20228   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
20229   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20230   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
20231   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20232   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20233   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
20234   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
20235   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
20236   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
20237   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
20238   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
20239   case ISD::SHL_PARTS:
20240   case ISD::SRA_PARTS:
20241   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
20242   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
20243   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
20244   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
20245   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
20246   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20247   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
20248   case ISD::SIGN_EXTEND_VECTOR_INREG:
20249     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20250   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
20251   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
20252   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
20253   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
20254   case ISD::FABS:
20255   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
20256   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
20257   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
20258   case ISD::SETCC:              return LowerSETCC(Op, DAG);
20259   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
20260   case ISD::SELECT:             return LowerSELECT(Op, DAG);
20261   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
20262   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
20263   case ISD::VASTART:            return LowerVASTART(Op, DAG);
20264   case ISD::VAARG:              return LowerVAARG(Op, DAG);
20265   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
20266   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20267   case ISD::INTRINSIC_VOID:
20268   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20269   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
20270   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
20271   case ISD::FRAME_TO_ARGS_OFFSET:
20272                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20273   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20274   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
20275   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
20276   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
20277   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
20278   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
20279   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
20280   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
20281   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20282   case ISD::CTTZ:
20283   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
20284   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
20285   case ISD::UMUL_LOHI:
20286   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
20287   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
20288   case ISD::SRA:
20289   case ISD::SRL:
20290   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
20291   case ISD::SADDO:
20292   case ISD::UADDO:
20293   case ISD::SSUBO:
20294   case ISD::USUBO:
20295   case ISD::SMULO:
20296   case ISD::UMULO:              return LowerXALUO(Op, DAG);
20297   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20298   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
20299   case ISD::ADDC:
20300   case ISD::ADDE:
20301   case ISD::SUBC:
20302   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20303   case ISD::ADD:                return LowerADD(Op, DAG);
20304   case ISD::SUB:                return LowerSUB(Op, DAG);
20305   case ISD::SMAX:
20306   case ISD::SMIN:
20307   case ISD::UMAX:
20308   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
20309   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
20310   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
20311   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
20312   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
20313   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
20314   case ISD::GC_TRANSITION_START:
20315                                 return LowerGC_TRANSITION_START(Op, DAG);
20316   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
20317   }
20318 }
20319
20320 /// ReplaceNodeResults - Replace a node with an illegal result type
20321 /// with a new node built out of custom code.
20322 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20323                                            SmallVectorImpl<SDValue>&Results,
20324                                            SelectionDAG &DAG) const {
20325   SDLoc dl(N);
20326   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20327   switch (N->getOpcode()) {
20328   default:
20329     llvm_unreachable("Do not know how to custom type legalize this operation!");
20330   case X86ISD::AVG: {
20331     // Legalize types for X86ISD::AVG by expanding vectors.
20332     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20333
20334     auto InVT = N->getValueType(0);
20335     auto InVTSize = InVT.getSizeInBits();
20336     const unsigned RegSize =
20337         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20338     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20339            "512-bit vector requires AVX512");
20340     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20341            "256-bit vector requires AVX2");
20342
20343     auto ElemVT = InVT.getVectorElementType();
20344     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20345                                   RegSize / ElemVT.getSizeInBits());
20346     assert(RegSize % InVT.getSizeInBits() == 0);
20347     unsigned NumConcat = RegSize / InVT.getSizeInBits();
20348
20349     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20350     Ops[0] = N->getOperand(0);
20351     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20352     Ops[0] = N->getOperand(1);
20353     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20354
20355     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20356     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20357                                   DAG.getIntPtrConstant(0, dl)));
20358     return;
20359   }
20360   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20361   case X86ISD::FMINC:
20362   case X86ISD::FMIN:
20363   case X86ISD::FMAXC:
20364   case X86ISD::FMAX: {
20365     EVT VT = N->getValueType(0);
20366     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20367     SDValue UNDEF = DAG.getUNDEF(VT);
20368     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20369                               N->getOperand(0), UNDEF);
20370     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20371                               N->getOperand(1), UNDEF);
20372     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20373     return;
20374   }
20375   case ISD::SIGN_EXTEND_INREG:
20376   case ISD::ADDC:
20377   case ISD::ADDE:
20378   case ISD::SUBC:
20379   case ISD::SUBE:
20380     // We don't want to expand or promote these.
20381     return;
20382   case ISD::SDIV:
20383   case ISD::UDIV:
20384   case ISD::SREM:
20385   case ISD::UREM:
20386   case ISD::SDIVREM:
20387   case ISD::UDIVREM: {
20388     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20389     Results.push_back(V);
20390     return;
20391   }
20392   case ISD::FP_TO_SINT:
20393   case ISD::FP_TO_UINT: {
20394     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20395
20396     std::pair<SDValue,SDValue> Vals =
20397         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20398     SDValue FIST = Vals.first, StackSlot = Vals.second;
20399     if (FIST.getNode()) {
20400       EVT VT = N->getValueType(0);
20401       // Return a load from the stack slot.
20402       if (StackSlot.getNode())
20403         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20404                                       MachinePointerInfo(),
20405                                       false, false, false, 0));
20406       else
20407         Results.push_back(FIST);
20408     }
20409     return;
20410   }
20411   case ISD::UINT_TO_FP: {
20412     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20413     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20414         N->getValueType(0) != MVT::v2f32)
20415       return;
20416     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20417                                  N->getOperand(0));
20418     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20419                                      MVT::f64);
20420     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20421     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20422                              DAG.getBitcast(MVT::v2i64, VBias));
20423     Or = DAG.getBitcast(MVT::v2f64, Or);
20424     // TODO: Are there any fast-math-flags to propagate here?
20425     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20426     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20427     return;
20428   }
20429   case ISD::FP_ROUND: {
20430     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20431         return;
20432     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20433     Results.push_back(V);
20434     return;
20435   }
20436   case ISD::FP_EXTEND: {
20437     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20438     // No other ValueType for FP_EXTEND should reach this point.
20439     assert(N->getValueType(0) == MVT::v2f32 &&
20440            "Do not know how to legalize this Node");
20441     return;
20442   }
20443   case ISD::INTRINSIC_W_CHAIN: {
20444     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20445     switch (IntNo) {
20446     default : llvm_unreachable("Do not know how to custom type "
20447                                "legalize this intrinsic operation!");
20448     case Intrinsic::x86_rdtsc:
20449       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20450                                      Results);
20451     case Intrinsic::x86_rdtscp:
20452       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20453                                      Results);
20454     case Intrinsic::x86_rdpmc:
20455       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20456     }
20457   }
20458   case ISD::INTRINSIC_WO_CHAIN: {
20459     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20460       Results.push_back(V);
20461     return;
20462   }
20463   case ISD::READCYCLECOUNTER: {
20464     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20465                                    Results);
20466   }
20467   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20468     EVT T = N->getValueType(0);
20469     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20470     bool Regs64bit = T == MVT::i128;
20471     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20472     SDValue cpInL, cpInH;
20473     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20474                         DAG.getConstant(0, dl, HalfT));
20475     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20476                         DAG.getConstant(1, dl, HalfT));
20477     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20478                              Regs64bit ? X86::RAX : X86::EAX,
20479                              cpInL, SDValue());
20480     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20481                              Regs64bit ? X86::RDX : X86::EDX,
20482                              cpInH, cpInL.getValue(1));
20483     SDValue swapInL, swapInH;
20484     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20485                           DAG.getConstant(0, dl, HalfT));
20486     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20487                           DAG.getConstant(1, dl, HalfT));
20488     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20489                                Regs64bit ? X86::RBX : X86::EBX,
20490                                swapInL, cpInH.getValue(1));
20491     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20492                                Regs64bit ? X86::RCX : X86::ECX,
20493                                swapInH, swapInL.getValue(1));
20494     SDValue Ops[] = { swapInH.getValue(0),
20495                       N->getOperand(1),
20496                       swapInH.getValue(1) };
20497     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20498     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20499     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20500                                   X86ISD::LCMPXCHG8_DAG;
20501     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20502     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20503                                         Regs64bit ? X86::RAX : X86::EAX,
20504                                         HalfT, Result.getValue(1));
20505     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20506                                         Regs64bit ? X86::RDX : X86::EDX,
20507                                         HalfT, cpOutL.getValue(2));
20508     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20509
20510     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20511                                         MVT::i32, cpOutH.getValue(2));
20512     SDValue Success =
20513         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20514                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20515     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20516
20517     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20518     Results.push_back(Success);
20519     Results.push_back(EFLAGS.getValue(1));
20520     return;
20521   }
20522   case ISD::ATOMIC_SWAP:
20523   case ISD::ATOMIC_LOAD_ADD:
20524   case ISD::ATOMIC_LOAD_SUB:
20525   case ISD::ATOMIC_LOAD_AND:
20526   case ISD::ATOMIC_LOAD_OR:
20527   case ISD::ATOMIC_LOAD_XOR:
20528   case ISD::ATOMIC_LOAD_NAND:
20529   case ISD::ATOMIC_LOAD_MIN:
20530   case ISD::ATOMIC_LOAD_MAX:
20531   case ISD::ATOMIC_LOAD_UMIN:
20532   case ISD::ATOMIC_LOAD_UMAX:
20533   case ISD::ATOMIC_LOAD: {
20534     // Delegate to generic TypeLegalization. Situations we can really handle
20535     // should have already been dealt with by AtomicExpandPass.cpp.
20536     break;
20537   }
20538   case ISD::BITCAST: {
20539     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20540     EVT DstVT = N->getValueType(0);
20541     EVT SrcVT = N->getOperand(0)->getValueType(0);
20542
20543     if (SrcVT != MVT::f64 ||
20544         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20545       return;
20546
20547     unsigned NumElts = DstVT.getVectorNumElements();
20548     EVT SVT = DstVT.getVectorElementType();
20549     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20550     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20551                                    MVT::v2f64, N->getOperand(0));
20552     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20553
20554     if (ExperimentalVectorWideningLegalization) {
20555       // If we are legalizing vectors by widening, we already have the desired
20556       // legal vector type, just return it.
20557       Results.push_back(ToVecInt);
20558       return;
20559     }
20560
20561     SmallVector<SDValue, 8> Elts;
20562     for (unsigned i = 0, e = NumElts; i != e; ++i)
20563       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20564                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20565
20566     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20567   }
20568   }
20569 }
20570
20571 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20572   switch ((X86ISD::NodeType)Opcode) {
20573   case X86ISD::FIRST_NUMBER:       break;
20574   case X86ISD::BSF:                return "X86ISD::BSF";
20575   case X86ISD::BSR:                return "X86ISD::BSR";
20576   case X86ISD::SHLD:               return "X86ISD::SHLD";
20577   case X86ISD::SHRD:               return "X86ISD::SHRD";
20578   case X86ISD::FAND:               return "X86ISD::FAND";
20579   case X86ISD::FANDN:              return "X86ISD::FANDN";
20580   case X86ISD::FOR:                return "X86ISD::FOR";
20581   case X86ISD::FXOR:               return "X86ISD::FXOR";
20582   case X86ISD::FILD:               return "X86ISD::FILD";
20583   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20584   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20585   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20586   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20587   case X86ISD::FLD:                return "X86ISD::FLD";
20588   case X86ISD::FST:                return "X86ISD::FST";
20589   case X86ISD::CALL:               return "X86ISD::CALL";
20590   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20591   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20592   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20593   case X86ISD::BT:                 return "X86ISD::BT";
20594   case X86ISD::CMP:                return "X86ISD::CMP";
20595   case X86ISD::COMI:               return "X86ISD::COMI";
20596   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20597   case X86ISD::CMPM:               return "X86ISD::CMPM";
20598   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20599   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20600   case X86ISD::SETCC:              return "X86ISD::SETCC";
20601   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20602   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20603   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20604   case X86ISD::CMOV:               return "X86ISD::CMOV";
20605   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20606   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20607   case X86ISD::IRET:               return "X86ISD::IRET";
20608   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20609   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20610   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20611   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20612   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20613   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20614   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20615   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20616   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20617   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20618   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20619   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20620   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20621   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20622   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20623   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20624   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20625   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20626   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20627   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20628   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20629   case X86ISD::HADD:               return "X86ISD::HADD";
20630   case X86ISD::HSUB:               return "X86ISD::HSUB";
20631   case X86ISD::FHADD:              return "X86ISD::FHADD";
20632   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20633   case X86ISD::ABS:                return "X86ISD::ABS";
20634   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20635   case X86ISD::FMAX:               return "X86ISD::FMAX";
20636   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20637   case X86ISD::FMIN:               return "X86ISD::FMIN";
20638   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20639   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20640   case X86ISD::FMINC:              return "X86ISD::FMINC";
20641   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20642   case X86ISD::FRCP:               return "X86ISD::FRCP";
20643   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20644   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20645   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20646   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20647   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20648   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20649   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20650   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20651   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20652   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20653   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20654   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20655   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20656   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20657   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20658   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20659   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20660   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20661   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20662   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20663   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20664   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20665   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20666   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20667   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20668   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20669   case X86ISD::CVT2MASK:           return "X86ISD::CVT2MASK";
20670   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20671   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20672   case X86ISD::VSHL:               return "X86ISD::VSHL";
20673   case X86ISD::VSRL:               return "X86ISD::VSRL";
20674   case X86ISD::VSRA:               return "X86ISD::VSRA";
20675   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20676   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20677   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20678   case X86ISD::CMPP:               return "X86ISD::CMPP";
20679   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20680   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20681   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20682   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20683   case X86ISD::ADD:                return "X86ISD::ADD";
20684   case X86ISD::SUB:                return "X86ISD::SUB";
20685   case X86ISD::ADC:                return "X86ISD::ADC";
20686   case X86ISD::SBB:                return "X86ISD::SBB";
20687   case X86ISD::SMUL:               return "X86ISD::SMUL";
20688   case X86ISD::UMUL:               return "X86ISD::UMUL";
20689   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20690   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20691   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20692   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20693   case X86ISD::INC:                return "X86ISD::INC";
20694   case X86ISD::DEC:                return "X86ISD::DEC";
20695   case X86ISD::OR:                 return "X86ISD::OR";
20696   case X86ISD::XOR:                return "X86ISD::XOR";
20697   case X86ISD::AND:                return "X86ISD::AND";
20698   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20699   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20700   case X86ISD::PTEST:              return "X86ISD::PTEST";
20701   case X86ISD::TESTP:              return "X86ISD::TESTP";
20702   case X86ISD::TESTM:              return "X86ISD::TESTM";
20703   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20704   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20705   case X86ISD::KTEST:              return "X86ISD::KTEST";
20706   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20707   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20708   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20709   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20710   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20711   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20712   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20713   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20714   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20715   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20716   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20717   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20718   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20719   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20720   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20721   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20722   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20723   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20724   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20725   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20726   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20727   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20728   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20729   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20730   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20731   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20732   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20733   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20734   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20735   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20736   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20737   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20738   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20739   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20740   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20741   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20742   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20743   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20744   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20745   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20746   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20747   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20748   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20749   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20750   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20751   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20752   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20753   case X86ISD::SAHF:               return "X86ISD::SAHF";
20754   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20755   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20756   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20757   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20758   case X86ISD::VPROT:              return "X86ISD::VPROT";
20759   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20760   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20761   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20762   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20763   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20764   case X86ISD::FMADD:              return "X86ISD::FMADD";
20765   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20766   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20767   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20768   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20769   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20770   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20771   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20772   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20773   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20774   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20775   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20776   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20777   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20778   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20779   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20780   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20781   case X86ISD::XTEST:              return "X86ISD::XTEST";
20782   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20783   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20784   case X86ISD::SELECT:             return "X86ISD::SELECT";
20785   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20786   case X86ISD::RCP28:              return "X86ISD::RCP28";
20787   case X86ISD::EXP2:               return "X86ISD::EXP2";
20788   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20789   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20790   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20791   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20792   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20793   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20794   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20795   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20796   case X86ISD::ADDS:               return "X86ISD::ADDS";
20797   case X86ISD::SUBS:               return "X86ISD::SUBS";
20798   case X86ISD::AVG:                return "X86ISD::AVG";
20799   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20800   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20801   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20802   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20803   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20804   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20805   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
20806   }
20807   return nullptr;
20808 }
20809
20810 // isLegalAddressingMode - Return true if the addressing mode represented
20811 // by AM is legal for this target, for a load/store of the specified type.
20812 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20813                                               const AddrMode &AM, Type *Ty,
20814                                               unsigned AS) const {
20815   // X86 supports extremely general addressing modes.
20816   CodeModel::Model M = getTargetMachine().getCodeModel();
20817   Reloc::Model R = getTargetMachine().getRelocationModel();
20818
20819   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20820   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20821     return false;
20822
20823   if (AM.BaseGV) {
20824     unsigned GVFlags =
20825       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20826
20827     // If a reference to this global requires an extra load, we can't fold it.
20828     if (isGlobalStubReference(GVFlags))
20829       return false;
20830
20831     // If BaseGV requires a register for the PIC base, we cannot also have a
20832     // BaseReg specified.
20833     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20834       return false;
20835
20836     // If lower 4G is not available, then we must use rip-relative addressing.
20837     if ((M != CodeModel::Small || R != Reloc::Static) &&
20838         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20839       return false;
20840   }
20841
20842   switch (AM.Scale) {
20843   case 0:
20844   case 1:
20845   case 2:
20846   case 4:
20847   case 8:
20848     // These scales always work.
20849     break;
20850   case 3:
20851   case 5:
20852   case 9:
20853     // These scales are formed with basereg+scalereg.  Only accept if there is
20854     // no basereg yet.
20855     if (AM.HasBaseReg)
20856       return false;
20857     break;
20858   default:  // Other stuff never works.
20859     return false;
20860   }
20861
20862   return true;
20863 }
20864
20865 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20866   unsigned Bits = Ty->getScalarSizeInBits();
20867
20868   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20869   // particularly cheaper than those without.
20870   if (Bits == 8)
20871     return false;
20872
20873   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20874   // variable shifts just as cheap as scalar ones.
20875   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20876     return false;
20877
20878   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20879   // fully general vector.
20880   return true;
20881 }
20882
20883 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20884   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20885     return false;
20886   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20887   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20888   return NumBits1 > NumBits2;
20889 }
20890
20891 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20892   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20893     return false;
20894
20895   if (!isTypeLegal(EVT::getEVT(Ty1)))
20896     return false;
20897
20898   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20899
20900   // Assuming the caller doesn't have a zeroext or signext return parameter,
20901   // truncation all the way down to i1 is valid.
20902   return true;
20903 }
20904
20905 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20906   return isInt<32>(Imm);
20907 }
20908
20909 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20910   // Can also use sub to handle negated immediates.
20911   return isInt<32>(Imm);
20912 }
20913
20914 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20915   if (!VT1.isInteger() || !VT2.isInteger())
20916     return false;
20917   unsigned NumBits1 = VT1.getSizeInBits();
20918   unsigned NumBits2 = VT2.getSizeInBits();
20919   return NumBits1 > NumBits2;
20920 }
20921
20922 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20923   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20924   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20925 }
20926
20927 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20928   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20929   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20930 }
20931
20932 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20933   EVT VT1 = Val.getValueType();
20934   if (isZExtFree(VT1, VT2))
20935     return true;
20936
20937   if (Val.getOpcode() != ISD::LOAD)
20938     return false;
20939
20940   if (!VT1.isSimple() || !VT1.isInteger() ||
20941       !VT2.isSimple() || !VT2.isInteger())
20942     return false;
20943
20944   switch (VT1.getSimpleVT().SimpleTy) {
20945   default: break;
20946   case MVT::i8:
20947   case MVT::i16:
20948   case MVT::i32:
20949     // X86 has 8, 16, and 32-bit zero-extending loads.
20950     return true;
20951   }
20952
20953   return false;
20954 }
20955
20956 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20957
20958 bool
20959 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20960   if (!Subtarget->hasAnyFMA())
20961     return false;
20962
20963   VT = VT.getScalarType();
20964
20965   if (!VT.isSimple())
20966     return false;
20967
20968   switch (VT.getSimpleVT().SimpleTy) {
20969   case MVT::f32:
20970   case MVT::f64:
20971     return true;
20972   default:
20973     break;
20974   }
20975
20976   return false;
20977 }
20978
20979 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20980   // i16 instructions are longer (0x66 prefix) and potentially slower.
20981   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20982 }
20983
20984 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20985 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20986 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20987 /// are assumed to be legal.
20988 bool
20989 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20990                                       EVT VT) const {
20991   if (!VT.isSimple())
20992     return false;
20993
20994   // Not for i1 vectors
20995   if (VT.getSimpleVT().getScalarType() == MVT::i1)
20996     return false;
20997
20998   // Very little shuffling can be done for 64-bit vectors right now.
20999   if (VT.getSimpleVT().getSizeInBits() == 64)
21000     return false;
21001
21002   // We only care that the types being shuffled are legal. The lowering can
21003   // handle any possible shuffle mask that results.
21004   return isTypeLegal(VT.getSimpleVT());
21005 }
21006
21007 bool
21008 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21009                                           EVT VT) const {
21010   // Just delegate to the generic legality, clear masks aren't special.
21011   return isShuffleMaskLegal(Mask, VT);
21012 }
21013
21014 //===----------------------------------------------------------------------===//
21015 //                           X86 Scheduler Hooks
21016 //===----------------------------------------------------------------------===//
21017
21018 /// Utility function to emit xbegin specifying the start of an RTM region.
21019 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21020                                      const TargetInstrInfo *TII) {
21021   DebugLoc DL = MI->getDebugLoc();
21022
21023   const BasicBlock *BB = MBB->getBasicBlock();
21024   MachineFunction::iterator I = ++MBB->getIterator();
21025
21026   // For the v = xbegin(), we generate
21027   //
21028   // thisMBB:
21029   //  xbegin sinkMBB
21030   //
21031   // mainMBB:
21032   //  eax = -1
21033   //
21034   // sinkMBB:
21035   //  v = eax
21036
21037   MachineBasicBlock *thisMBB = MBB;
21038   MachineFunction *MF = MBB->getParent();
21039   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21040   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21041   MF->insert(I, mainMBB);
21042   MF->insert(I, sinkMBB);
21043
21044   // Transfer the remainder of BB and its successor edges to sinkMBB.
21045   sinkMBB->splice(sinkMBB->begin(), MBB,
21046                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21047   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21048
21049   // thisMBB:
21050   //  xbegin sinkMBB
21051   //  # fallthrough to mainMBB
21052   //  # abortion to sinkMBB
21053   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21054   thisMBB->addSuccessor(mainMBB);
21055   thisMBB->addSuccessor(sinkMBB);
21056
21057   // mainMBB:
21058   //  EAX = -1
21059   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21060   mainMBB->addSuccessor(sinkMBB);
21061
21062   // sinkMBB:
21063   // EAX is live into the sinkMBB
21064   sinkMBB->addLiveIn(X86::EAX);
21065   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21066           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21067     .addReg(X86::EAX);
21068
21069   MI->eraseFromParent();
21070   return sinkMBB;
21071 }
21072
21073 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21074 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21075 // in the .td file.
21076 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21077                                        const TargetInstrInfo *TII) {
21078   unsigned Opc;
21079   switch (MI->getOpcode()) {
21080   default: llvm_unreachable("illegal opcode!");
21081   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
21082   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21083   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
21084   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21085   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
21086   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21087   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
21088   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21089   }
21090
21091   DebugLoc dl = MI->getDebugLoc();
21092   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21093
21094   unsigned NumArgs = MI->getNumOperands();
21095   for (unsigned i = 1; i < NumArgs; ++i) {
21096     MachineOperand &Op = MI->getOperand(i);
21097     if (!(Op.isReg() && Op.isImplicit()))
21098       MIB.addOperand(Op);
21099   }
21100   if (MI->hasOneMemOperand())
21101     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21102
21103   BuildMI(*BB, MI, dl,
21104     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21105     .addReg(X86::XMM0);
21106
21107   MI->eraseFromParent();
21108   return BB;
21109 }
21110
21111 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21112 // defs in an instruction pattern
21113 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21114                                        const TargetInstrInfo *TII) {
21115   unsigned Opc;
21116   switch (MI->getOpcode()) {
21117   default: llvm_unreachable("illegal opcode!");
21118   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
21119   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21120   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
21121   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21122   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
21123   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21124   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
21125   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21126   }
21127
21128   DebugLoc dl = MI->getDebugLoc();
21129   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21130
21131   unsigned NumArgs = MI->getNumOperands(); // remove the results
21132   for (unsigned i = 1; i < NumArgs; ++i) {
21133     MachineOperand &Op = MI->getOperand(i);
21134     if (!(Op.isReg() && Op.isImplicit()))
21135       MIB.addOperand(Op);
21136   }
21137   if (MI->hasOneMemOperand())
21138     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21139
21140   BuildMI(*BB, MI, dl,
21141     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21142     .addReg(X86::ECX);
21143
21144   MI->eraseFromParent();
21145   return BB;
21146 }
21147
21148 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21149                                      const X86Subtarget *Subtarget) {
21150   DebugLoc dl = MI->getDebugLoc();
21151   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21152
21153   // insert input VAL into EAX
21154   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21155                            .addReg(MI->getOperand(0).getReg());
21156   // insert zero to ECX
21157   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21158                            .addReg(X86::ECX)
21159                            .addReg(X86::ECX);
21160   // insert zero to EDX
21161   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21162                            .addReg(X86::EDX)
21163                            .addReg(X86::EDX);
21164   // insert WRPKRU instruction
21165   BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21166
21167   MI->eraseFromParent(); // The pseudo is gone now.
21168   return BB;
21169 }
21170
21171 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21172                                      const X86Subtarget *Subtarget) {
21173   DebugLoc dl = MI->getDebugLoc();
21174   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21175
21176   // insert zero to ECX
21177   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21178                            .addReg(X86::ECX)
21179                            .addReg(X86::ECX);
21180   // insert RDPKRU instruction
21181   BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21182   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21183                            .addReg(X86::EAX);
21184
21185   MI->eraseFromParent(); // The pseudo is gone now.
21186   return BB;
21187 }
21188
21189 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21190                                       const X86Subtarget *Subtarget) {
21191   DebugLoc dl = MI->getDebugLoc();
21192   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21193   // Address into RAX/EAX, other two args into ECX, EDX.
21194   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21195   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21196   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21197   for (int i = 0; i < X86::AddrNumOperands; ++i)
21198     MIB.addOperand(MI->getOperand(i));
21199
21200   unsigned ValOps = X86::AddrNumOperands;
21201   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21202     .addReg(MI->getOperand(ValOps).getReg());
21203   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21204     .addReg(MI->getOperand(ValOps+1).getReg());
21205
21206   // The instruction doesn't actually take any operands though.
21207   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21208
21209   MI->eraseFromParent(); // The pseudo is gone now.
21210   return BB;
21211 }
21212
21213 MachineBasicBlock *
21214 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21215                                                  MachineBasicBlock *MBB) const {
21216   // Emit va_arg instruction on X86-64.
21217
21218   // Operands to this pseudo-instruction:
21219   // 0  ) Output        : destination address (reg)
21220   // 1-5) Input         : va_list address (addr, i64mem)
21221   // 6  ) ArgSize       : Size (in bytes) of vararg type
21222   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21223   // 8  ) Align         : Alignment of type
21224   // 9  ) EFLAGS (implicit-def)
21225
21226   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21227   static_assert(X86::AddrNumOperands == 5,
21228                 "VAARG_64 assumes 5 address operands");
21229
21230   unsigned DestReg = MI->getOperand(0).getReg();
21231   MachineOperand &Base = MI->getOperand(1);
21232   MachineOperand &Scale = MI->getOperand(2);
21233   MachineOperand &Index = MI->getOperand(3);
21234   MachineOperand &Disp = MI->getOperand(4);
21235   MachineOperand &Segment = MI->getOperand(5);
21236   unsigned ArgSize = MI->getOperand(6).getImm();
21237   unsigned ArgMode = MI->getOperand(7).getImm();
21238   unsigned Align = MI->getOperand(8).getImm();
21239
21240   // Memory Reference
21241   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21242   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21243   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21244
21245   // Machine Information
21246   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21247   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21248   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21249   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21250   DebugLoc DL = MI->getDebugLoc();
21251
21252   // struct va_list {
21253   //   i32   gp_offset
21254   //   i32   fp_offset
21255   //   i64   overflow_area (address)
21256   //   i64   reg_save_area (address)
21257   // }
21258   // sizeof(va_list) = 24
21259   // alignment(va_list) = 8
21260
21261   unsigned TotalNumIntRegs = 6;
21262   unsigned TotalNumXMMRegs = 8;
21263   bool UseGPOffset = (ArgMode == 1);
21264   bool UseFPOffset = (ArgMode == 2);
21265   unsigned MaxOffset = TotalNumIntRegs * 8 +
21266                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21267
21268   /* Align ArgSize to a multiple of 8 */
21269   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21270   bool NeedsAlign = (Align > 8);
21271
21272   MachineBasicBlock *thisMBB = MBB;
21273   MachineBasicBlock *overflowMBB;
21274   MachineBasicBlock *offsetMBB;
21275   MachineBasicBlock *endMBB;
21276
21277   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
21278   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
21279   unsigned OffsetReg = 0;
21280
21281   if (!UseGPOffset && !UseFPOffset) {
21282     // If we only pull from the overflow region, we don't create a branch.
21283     // We don't need to alter control flow.
21284     OffsetDestReg = 0; // unused
21285     OverflowDestReg = DestReg;
21286
21287     offsetMBB = nullptr;
21288     overflowMBB = thisMBB;
21289     endMBB = thisMBB;
21290   } else {
21291     // First emit code to check if gp_offset (or fp_offset) is below the bound.
21292     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21293     // If not, pull from overflow_area. (branch to overflowMBB)
21294     //
21295     //       thisMBB
21296     //         |     .
21297     //         |        .
21298     //     offsetMBB   overflowMBB
21299     //         |        .
21300     //         |     .
21301     //        endMBB
21302
21303     // Registers for the PHI in endMBB
21304     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21305     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21306
21307     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21308     MachineFunction *MF = MBB->getParent();
21309     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21310     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21311     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21312
21313     MachineFunction::iterator MBBIter = ++MBB->getIterator();
21314
21315     // Insert the new basic blocks
21316     MF->insert(MBBIter, offsetMBB);
21317     MF->insert(MBBIter, overflowMBB);
21318     MF->insert(MBBIter, endMBB);
21319
21320     // Transfer the remainder of MBB and its successor edges to endMBB.
21321     endMBB->splice(endMBB->begin(), thisMBB,
21322                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21323     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21324
21325     // Make offsetMBB and overflowMBB successors of thisMBB
21326     thisMBB->addSuccessor(offsetMBB);
21327     thisMBB->addSuccessor(overflowMBB);
21328
21329     // endMBB is a successor of both offsetMBB and overflowMBB
21330     offsetMBB->addSuccessor(endMBB);
21331     overflowMBB->addSuccessor(endMBB);
21332
21333     // Load the offset value into a register
21334     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21335     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21336       .addOperand(Base)
21337       .addOperand(Scale)
21338       .addOperand(Index)
21339       .addDisp(Disp, UseFPOffset ? 4 : 0)
21340       .addOperand(Segment)
21341       .setMemRefs(MMOBegin, MMOEnd);
21342
21343     // Check if there is enough room left to pull this argument.
21344     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21345       .addReg(OffsetReg)
21346       .addImm(MaxOffset + 8 - ArgSizeA8);
21347
21348     // Branch to "overflowMBB" if offset >= max
21349     // Fall through to "offsetMBB" otherwise
21350     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21351       .addMBB(overflowMBB);
21352   }
21353
21354   // In offsetMBB, emit code to use the reg_save_area.
21355   if (offsetMBB) {
21356     assert(OffsetReg != 0);
21357
21358     // Read the reg_save_area address.
21359     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21360     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21361       .addOperand(Base)
21362       .addOperand(Scale)
21363       .addOperand(Index)
21364       .addDisp(Disp, 16)
21365       .addOperand(Segment)
21366       .setMemRefs(MMOBegin, MMOEnd);
21367
21368     // Zero-extend the offset
21369     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21370       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21371         .addImm(0)
21372         .addReg(OffsetReg)
21373         .addImm(X86::sub_32bit);
21374
21375     // Add the offset to the reg_save_area to get the final address.
21376     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21377       .addReg(OffsetReg64)
21378       .addReg(RegSaveReg);
21379
21380     // Compute the offset for the next argument
21381     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21382     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21383       .addReg(OffsetReg)
21384       .addImm(UseFPOffset ? 16 : 8);
21385
21386     // Store it back into the va_list.
21387     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21388       .addOperand(Base)
21389       .addOperand(Scale)
21390       .addOperand(Index)
21391       .addDisp(Disp, UseFPOffset ? 4 : 0)
21392       .addOperand(Segment)
21393       .addReg(NextOffsetReg)
21394       .setMemRefs(MMOBegin, MMOEnd);
21395
21396     // Jump to endMBB
21397     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21398       .addMBB(endMBB);
21399   }
21400
21401   //
21402   // Emit code to use overflow area
21403   //
21404
21405   // Load the overflow_area address into a register.
21406   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21407   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21408     .addOperand(Base)
21409     .addOperand(Scale)
21410     .addOperand(Index)
21411     .addDisp(Disp, 8)
21412     .addOperand(Segment)
21413     .setMemRefs(MMOBegin, MMOEnd);
21414
21415   // If we need to align it, do so. Otherwise, just copy the address
21416   // to OverflowDestReg.
21417   if (NeedsAlign) {
21418     // Align the overflow address
21419     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21420     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21421
21422     // aligned_addr = (addr + (align-1)) & ~(align-1)
21423     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21424       .addReg(OverflowAddrReg)
21425       .addImm(Align-1);
21426
21427     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21428       .addReg(TmpReg)
21429       .addImm(~(uint64_t)(Align-1));
21430   } else {
21431     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21432       .addReg(OverflowAddrReg);
21433   }
21434
21435   // Compute the next overflow address after this argument.
21436   // (the overflow address should be kept 8-byte aligned)
21437   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21438   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21439     .addReg(OverflowDestReg)
21440     .addImm(ArgSizeA8);
21441
21442   // Store the new overflow address.
21443   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21444     .addOperand(Base)
21445     .addOperand(Scale)
21446     .addOperand(Index)
21447     .addDisp(Disp, 8)
21448     .addOperand(Segment)
21449     .addReg(NextAddrReg)
21450     .setMemRefs(MMOBegin, MMOEnd);
21451
21452   // If we branched, emit the PHI to the front of endMBB.
21453   if (offsetMBB) {
21454     BuildMI(*endMBB, endMBB->begin(), DL,
21455             TII->get(X86::PHI), DestReg)
21456       .addReg(OffsetDestReg).addMBB(offsetMBB)
21457       .addReg(OverflowDestReg).addMBB(overflowMBB);
21458   }
21459
21460   // Erase the pseudo instruction
21461   MI->eraseFromParent();
21462
21463   return endMBB;
21464 }
21465
21466 MachineBasicBlock *
21467 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21468                                                  MachineInstr *MI,
21469                                                  MachineBasicBlock *MBB) const {
21470   // Emit code to save XMM registers to the stack. The ABI says that the
21471   // number of registers to save is given in %al, so it's theoretically
21472   // possible to do an indirect jump trick to avoid saving all of them,
21473   // however this code takes a simpler approach and just executes all
21474   // of the stores if %al is non-zero. It's less code, and it's probably
21475   // easier on the hardware branch predictor, and stores aren't all that
21476   // expensive anyway.
21477
21478   // Create the new basic blocks. One block contains all the XMM stores,
21479   // and one block is the final destination regardless of whether any
21480   // stores were performed.
21481   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21482   MachineFunction *F = MBB->getParent();
21483   MachineFunction::iterator MBBIter = ++MBB->getIterator();
21484   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21485   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21486   F->insert(MBBIter, XMMSaveMBB);
21487   F->insert(MBBIter, EndMBB);
21488
21489   // Transfer the remainder of MBB and its successor edges to EndMBB.
21490   EndMBB->splice(EndMBB->begin(), MBB,
21491                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21492   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21493
21494   // The original block will now fall through to the XMM save block.
21495   MBB->addSuccessor(XMMSaveMBB);
21496   // The XMMSaveMBB will fall through to the end block.
21497   XMMSaveMBB->addSuccessor(EndMBB);
21498
21499   // Now add the instructions.
21500   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21501   DebugLoc DL = MI->getDebugLoc();
21502
21503   unsigned CountReg = MI->getOperand(0).getReg();
21504   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21505   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21506
21507   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21508     // If %al is 0, branch around the XMM save block.
21509     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21510     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21511     MBB->addSuccessor(EndMBB);
21512   }
21513
21514   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21515   // that was just emitted, but clearly shouldn't be "saved".
21516   assert((MI->getNumOperands() <= 3 ||
21517           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21518           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21519          && "Expected last argument to be EFLAGS");
21520   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21521   // In the XMM save block, save all the XMM argument registers.
21522   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21523     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21524     MachineMemOperand *MMO = F->getMachineMemOperand(
21525         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21526         MachineMemOperand::MOStore,
21527         /*Size=*/16, /*Align=*/16);
21528     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21529       .addFrameIndex(RegSaveFrameIndex)
21530       .addImm(/*Scale=*/1)
21531       .addReg(/*IndexReg=*/0)
21532       .addImm(/*Disp=*/Offset)
21533       .addReg(/*Segment=*/0)
21534       .addReg(MI->getOperand(i).getReg())
21535       .addMemOperand(MMO);
21536   }
21537
21538   MI->eraseFromParent();   // The pseudo instruction is gone now.
21539
21540   return EndMBB;
21541 }
21542
21543 // The EFLAGS operand of SelectItr might be missing a kill marker
21544 // because there were multiple uses of EFLAGS, and ISel didn't know
21545 // which to mark. Figure out whether SelectItr should have had a
21546 // kill marker, and set it if it should. Returns the correct kill
21547 // marker value.
21548 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21549                                      MachineBasicBlock* BB,
21550                                      const TargetRegisterInfo* TRI) {
21551   // Scan forward through BB for a use/def of EFLAGS.
21552   MachineBasicBlock::iterator miI(std::next(SelectItr));
21553   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21554     const MachineInstr& mi = *miI;
21555     if (mi.readsRegister(X86::EFLAGS))
21556       return false;
21557     if (mi.definesRegister(X86::EFLAGS))
21558       break; // Should have kill-flag - update below.
21559   }
21560
21561   // If we hit the end of the block, check whether EFLAGS is live into a
21562   // successor.
21563   if (miI == BB->end()) {
21564     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21565                                           sEnd = BB->succ_end();
21566          sItr != sEnd; ++sItr) {
21567       MachineBasicBlock* succ = *sItr;
21568       if (succ->isLiveIn(X86::EFLAGS))
21569         return false;
21570     }
21571   }
21572
21573   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21574   // out. SelectMI should have a kill flag on EFLAGS.
21575   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21576   return true;
21577 }
21578
21579 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21580 // together with other CMOV pseudo-opcodes into a single basic-block with
21581 // conditional jump around it.
21582 static bool isCMOVPseudo(MachineInstr *MI) {
21583   switch (MI->getOpcode()) {
21584   case X86::CMOV_FR32:
21585   case X86::CMOV_FR64:
21586   case X86::CMOV_GR8:
21587   case X86::CMOV_GR16:
21588   case X86::CMOV_GR32:
21589   case X86::CMOV_RFP32:
21590   case X86::CMOV_RFP64:
21591   case X86::CMOV_RFP80:
21592   case X86::CMOV_V2F64:
21593   case X86::CMOV_V2I64:
21594   case X86::CMOV_V4F32:
21595   case X86::CMOV_V4F64:
21596   case X86::CMOV_V4I64:
21597   case X86::CMOV_V16F32:
21598   case X86::CMOV_V8F32:
21599   case X86::CMOV_V8F64:
21600   case X86::CMOV_V8I64:
21601   case X86::CMOV_V8I1:
21602   case X86::CMOV_V16I1:
21603   case X86::CMOV_V32I1:
21604   case X86::CMOV_V64I1:
21605     return true;
21606
21607   default:
21608     return false;
21609   }
21610 }
21611
21612 MachineBasicBlock *
21613 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21614                                      MachineBasicBlock *BB) const {
21615   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21616   DebugLoc DL = MI->getDebugLoc();
21617
21618   // To "insert" a SELECT_CC instruction, we actually have to insert the
21619   // diamond control-flow pattern.  The incoming instruction knows the
21620   // destination vreg to set, the condition code register to branch on, the
21621   // true/false values to select between, and a branch opcode to use.
21622   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21623   MachineFunction::iterator It = ++BB->getIterator();
21624
21625   //  thisMBB:
21626   //  ...
21627   //   TrueVal = ...
21628   //   cmpTY ccX, r1, r2
21629   //   bCC copy1MBB
21630   //   fallthrough --> copy0MBB
21631   MachineBasicBlock *thisMBB = BB;
21632   MachineFunction *F = BB->getParent();
21633
21634   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21635   // as described above, by inserting a BB, and then making a PHI at the join
21636   // point to select the true and false operands of the CMOV in the PHI.
21637   //
21638   // The code also handles two different cases of multiple CMOV opcodes
21639   // in a row.
21640   //
21641   // Case 1:
21642   // In this case, there are multiple CMOVs in a row, all which are based on
21643   // the same condition setting (or the exact opposite condition setting).
21644   // In this case we can lower all the CMOVs using a single inserted BB, and
21645   // then make a number of PHIs at the join point to model the CMOVs. The only
21646   // trickiness here, is that in a case like:
21647   //
21648   // t2 = CMOV cond1 t1, f1
21649   // t3 = CMOV cond1 t2, f2
21650   //
21651   // when rewriting this into PHIs, we have to perform some renaming on the
21652   // temps since you cannot have a PHI operand refer to a PHI result earlier
21653   // in the same block.  The "simple" but wrong lowering would be:
21654   //
21655   // t2 = PHI t1(BB1), f1(BB2)
21656   // t3 = PHI t2(BB1), f2(BB2)
21657   //
21658   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21659   // renaming is to note that on the path through BB1, t2 is really just a
21660   // copy of t1, and do that renaming, properly generating:
21661   //
21662   // t2 = PHI t1(BB1), f1(BB2)
21663   // t3 = PHI t1(BB1), f2(BB2)
21664   //
21665   // Case 2, we lower cascaded CMOVs such as
21666   //
21667   //   (CMOV (CMOV F, T, cc1), T, cc2)
21668   //
21669   // to two successives branches.  For that, we look for another CMOV as the
21670   // following instruction.
21671   //
21672   // Without this, we would add a PHI between the two jumps, which ends up
21673   // creating a few copies all around. For instance, for
21674   //
21675   //    (sitofp (zext (fcmp une)))
21676   //
21677   // we would generate:
21678   //
21679   //         ucomiss %xmm1, %xmm0
21680   //         movss  <1.0f>, %xmm0
21681   //         movaps  %xmm0, %xmm1
21682   //         jne     .LBB5_2
21683   //         xorps   %xmm1, %xmm1
21684   // .LBB5_2:
21685   //         jp      .LBB5_4
21686   //         movaps  %xmm1, %xmm0
21687   // .LBB5_4:
21688   //         retq
21689   //
21690   // because this custom-inserter would have generated:
21691   //
21692   //   A
21693   //   | \
21694   //   |  B
21695   //   | /
21696   //   C
21697   //   | \
21698   //   |  D
21699   //   | /
21700   //   E
21701   //
21702   // A: X = ...; Y = ...
21703   // B: empty
21704   // C: Z = PHI [X, A], [Y, B]
21705   // D: empty
21706   // E: PHI [X, C], [Z, D]
21707   //
21708   // If we lower both CMOVs in a single step, we can instead generate:
21709   //
21710   //   A
21711   //   | \
21712   //   |  C
21713   //   | /|
21714   //   |/ |
21715   //   |  |
21716   //   |  D
21717   //   | /
21718   //   E
21719   //
21720   // A: X = ...; Y = ...
21721   // D: empty
21722   // E: PHI [X, A], [X, C], [Y, D]
21723   //
21724   // Which, in our sitofp/fcmp example, gives us something like:
21725   //
21726   //         ucomiss %xmm1, %xmm0
21727   //         movss  <1.0f>, %xmm0
21728   //         jne     .LBB5_4
21729   //         jp      .LBB5_4
21730   //         xorps   %xmm0, %xmm0
21731   // .LBB5_4:
21732   //         retq
21733   //
21734   MachineInstr *CascadedCMOV = nullptr;
21735   MachineInstr *LastCMOV = MI;
21736   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21737   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21738   MachineBasicBlock::iterator NextMIIt =
21739       std::next(MachineBasicBlock::iterator(MI));
21740
21741   // Check for case 1, where there are multiple CMOVs with the same condition
21742   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21743   // number of jumps the most.
21744
21745   if (isCMOVPseudo(MI)) {
21746     // See if we have a string of CMOVS with the same condition.
21747     while (NextMIIt != BB->end() &&
21748            isCMOVPseudo(NextMIIt) &&
21749            (NextMIIt->getOperand(3).getImm() == CC ||
21750             NextMIIt->getOperand(3).getImm() == OppCC)) {
21751       LastCMOV = &*NextMIIt;
21752       ++NextMIIt;
21753     }
21754   }
21755
21756   // This checks for case 2, but only do this if we didn't already find
21757   // case 1, as indicated by LastCMOV == MI.
21758   if (LastCMOV == MI &&
21759       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21760       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21761       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21762     CascadedCMOV = &*NextMIIt;
21763   }
21764
21765   MachineBasicBlock *jcc1MBB = nullptr;
21766
21767   // If we have a cascaded CMOV, we lower it to two successive branches to
21768   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21769   if (CascadedCMOV) {
21770     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21771     F->insert(It, jcc1MBB);
21772     jcc1MBB->addLiveIn(X86::EFLAGS);
21773   }
21774
21775   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21776   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21777   F->insert(It, copy0MBB);
21778   F->insert(It, sinkMBB);
21779
21780   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21781   // live into the sink and copy blocks.
21782   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21783
21784   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21785   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21786       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21787     copy0MBB->addLiveIn(X86::EFLAGS);
21788     sinkMBB->addLiveIn(X86::EFLAGS);
21789   }
21790
21791   // Transfer the remainder of BB and its successor edges to sinkMBB.
21792   sinkMBB->splice(sinkMBB->begin(), BB,
21793                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21794   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21795
21796   // Add the true and fallthrough blocks as its successors.
21797   if (CascadedCMOV) {
21798     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21799     BB->addSuccessor(jcc1MBB);
21800
21801     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21802     // jump to the sinkMBB.
21803     jcc1MBB->addSuccessor(copy0MBB);
21804     jcc1MBB->addSuccessor(sinkMBB);
21805   } else {
21806     BB->addSuccessor(copy0MBB);
21807   }
21808
21809   // The true block target of the first (or only) branch is always sinkMBB.
21810   BB->addSuccessor(sinkMBB);
21811
21812   // Create the conditional branch instruction.
21813   unsigned Opc = X86::GetCondBranchFromCond(CC);
21814   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21815
21816   if (CascadedCMOV) {
21817     unsigned Opc2 = X86::GetCondBranchFromCond(
21818         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21819     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21820   }
21821
21822   //  copy0MBB:
21823   //   %FalseValue = ...
21824   //   # fallthrough to sinkMBB
21825   copy0MBB->addSuccessor(sinkMBB);
21826
21827   //  sinkMBB:
21828   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21829   //  ...
21830   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21831   MachineBasicBlock::iterator MIItEnd =
21832     std::next(MachineBasicBlock::iterator(LastCMOV));
21833   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21834   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21835   MachineInstrBuilder MIB;
21836
21837   // As we are creating the PHIs, we have to be careful if there is more than
21838   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21839   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21840   // That also means that PHI construction must work forward from earlier to
21841   // later, and that the code must maintain a mapping from earlier PHI's
21842   // destination registers, and the registers that went into the PHI.
21843
21844   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21845     unsigned DestReg = MIIt->getOperand(0).getReg();
21846     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21847     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21848
21849     // If this CMOV we are generating is the opposite condition from
21850     // the jump we generated, then we have to swap the operands for the
21851     // PHI that is going to be generated.
21852     if (MIIt->getOperand(3).getImm() == OppCC)
21853         std::swap(Op1Reg, Op2Reg);
21854
21855     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21856       Op1Reg = RegRewriteTable[Op1Reg].first;
21857
21858     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21859       Op2Reg = RegRewriteTable[Op2Reg].second;
21860
21861     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21862                   TII->get(X86::PHI), DestReg)
21863           .addReg(Op1Reg).addMBB(copy0MBB)
21864           .addReg(Op2Reg).addMBB(thisMBB);
21865
21866     // Add this PHI to the rewrite table.
21867     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21868   }
21869
21870   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21871   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21872   if (CascadedCMOV) {
21873     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21874     // Copy the PHI result to the register defined by the second CMOV.
21875     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21876             DL, TII->get(TargetOpcode::COPY),
21877             CascadedCMOV->getOperand(0).getReg())
21878         .addReg(MI->getOperand(0).getReg());
21879     CascadedCMOV->eraseFromParent();
21880   }
21881
21882   // Now remove the CMOV(s).
21883   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21884     (MIIt++)->eraseFromParent();
21885
21886   return sinkMBB;
21887 }
21888
21889 MachineBasicBlock *
21890 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21891                                        MachineBasicBlock *BB) const {
21892   // Combine the following atomic floating-point modification pattern:
21893   //   a.store(reg OP a.load(acquire), release)
21894   // Transform them into:
21895   //   OPss (%gpr), %xmm
21896   //   movss %xmm, (%gpr)
21897   // Or sd equivalent for 64-bit operations.
21898   unsigned MOp, FOp;
21899   switch (MI->getOpcode()) {
21900   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21901   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21902   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21903   }
21904   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21905   DebugLoc DL = MI->getDebugLoc();
21906   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21907   MachineOperand MSrc = MI->getOperand(0);
21908   unsigned VSrc = MI->getOperand(5).getReg();
21909   const MachineOperand &Disp = MI->getOperand(3);
21910   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21911   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21912   if (hasDisp && MSrc.isReg())
21913     MSrc.setIsKill(false);
21914   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21915                                 .addOperand(/*Base=*/MSrc)
21916                                 .addImm(/*Scale=*/1)
21917                                 .addReg(/*Index=*/0)
21918                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21919                                 .addReg(0);
21920   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21921                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21922                           .addReg(VSrc)
21923                           .addOperand(/*Base=*/MSrc)
21924                           .addImm(/*Scale=*/1)
21925                           .addReg(/*Index=*/0)
21926                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21927                           .addReg(/*Segment=*/0);
21928   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21929   MI->eraseFromParent(); // The pseudo instruction is gone now.
21930   return BB;
21931 }
21932
21933 MachineBasicBlock *
21934 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21935                                         MachineBasicBlock *BB) const {
21936   MachineFunction *MF = BB->getParent();
21937   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21938   DebugLoc DL = MI->getDebugLoc();
21939   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21940
21941   assert(MF->shouldSplitStack());
21942
21943   const bool Is64Bit = Subtarget->is64Bit();
21944   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21945
21946   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21947   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21948
21949   // BB:
21950   //  ... [Till the alloca]
21951   // If stacklet is not large enough, jump to mallocMBB
21952   //
21953   // bumpMBB:
21954   //  Allocate by subtracting from RSP
21955   //  Jump to continueMBB
21956   //
21957   // mallocMBB:
21958   //  Allocate by call to runtime
21959   //
21960   // continueMBB:
21961   //  ...
21962   //  [rest of original BB]
21963   //
21964
21965   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21966   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21967   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21968
21969   MachineRegisterInfo &MRI = MF->getRegInfo();
21970   const TargetRegisterClass *AddrRegClass =
21971       getRegClassFor(getPointerTy(MF->getDataLayout()));
21972
21973   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21974     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21975     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21976     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21977     sizeVReg = MI->getOperand(1).getReg(),
21978     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21979
21980   MachineFunction::iterator MBBIter = ++BB->getIterator();
21981
21982   MF->insert(MBBIter, bumpMBB);
21983   MF->insert(MBBIter, mallocMBB);
21984   MF->insert(MBBIter, continueMBB);
21985
21986   continueMBB->splice(continueMBB->begin(), BB,
21987                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21988   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21989
21990   // Add code to the main basic block to check if the stack limit has been hit,
21991   // and if so, jump to mallocMBB otherwise to bumpMBB.
21992   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21993   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21994     .addReg(tmpSPVReg).addReg(sizeVReg);
21995   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21996     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21997     .addReg(SPLimitVReg);
21998   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21999
22000   // bumpMBB simply decreases the stack pointer, since we know the current
22001   // stacklet has enough space.
22002   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22003     .addReg(SPLimitVReg);
22004   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22005     .addReg(SPLimitVReg);
22006   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22007
22008   // Calls into a routine in libgcc to allocate more space from the heap.
22009   const uint32_t *RegMask =
22010       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22011   if (IsLP64) {
22012     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22013       .addReg(sizeVReg);
22014     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22015       .addExternalSymbol("__morestack_allocate_stack_space")
22016       .addRegMask(RegMask)
22017       .addReg(X86::RDI, RegState::Implicit)
22018       .addReg(X86::RAX, RegState::ImplicitDefine);
22019   } else if (Is64Bit) {
22020     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22021       .addReg(sizeVReg);
22022     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22023       .addExternalSymbol("__morestack_allocate_stack_space")
22024       .addRegMask(RegMask)
22025       .addReg(X86::EDI, RegState::Implicit)
22026       .addReg(X86::EAX, RegState::ImplicitDefine);
22027   } else {
22028     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22029       .addImm(12);
22030     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22031     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22032       .addExternalSymbol("__morestack_allocate_stack_space")
22033       .addRegMask(RegMask)
22034       .addReg(X86::EAX, RegState::ImplicitDefine);
22035   }
22036
22037   if (!Is64Bit)
22038     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22039       .addImm(16);
22040
22041   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22042     .addReg(IsLP64 ? X86::RAX : X86::EAX);
22043   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22044
22045   // Set up the CFG correctly.
22046   BB->addSuccessor(bumpMBB);
22047   BB->addSuccessor(mallocMBB);
22048   mallocMBB->addSuccessor(continueMBB);
22049   bumpMBB->addSuccessor(continueMBB);
22050
22051   // Take care of the PHI nodes.
22052   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22053           MI->getOperand(0).getReg())
22054     .addReg(mallocPtrVReg).addMBB(mallocMBB)
22055     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22056
22057   // Delete the original pseudo instruction.
22058   MI->eraseFromParent();
22059
22060   // And we're done.
22061   return continueMBB;
22062 }
22063
22064 MachineBasicBlock *
22065 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22066                                         MachineBasicBlock *BB) const {
22067   assert(!Subtarget->isTargetMachO());
22068   DebugLoc DL = MI->getDebugLoc();
22069   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22070       *BB->getParent(), *BB, MI, DL, false);
22071   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22072   MI->eraseFromParent(); // The pseudo instruction is gone now.
22073   return ResumeBB;
22074 }
22075
22076 MachineBasicBlock *
22077 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22078                                        MachineBasicBlock *BB) const {
22079   MachineFunction *MF = BB->getParent();
22080   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22081   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22082   DebugLoc DL = MI->getDebugLoc();
22083
22084   assert(!isAsynchronousEHPersonality(
22085              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22086          "SEH does not use catchret!");
22087
22088   // Only 32-bit EH needs to worry about manually restoring stack pointers.
22089   if (!Subtarget->is32Bit())
22090     return BB;
22091
22092   // C++ EH creates a new target block to hold the restore code, and wires up
22093   // the new block to the return destination with a normal JMP_4.
22094   MachineBasicBlock *RestoreMBB =
22095       MF->CreateMachineBasicBlock(BB->getBasicBlock());
22096   assert(BB->succ_size() == 1);
22097   MF->insert(std::next(BB->getIterator()), RestoreMBB);
22098   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22099   BB->addSuccessor(RestoreMBB);
22100   MI->getOperand(0).setMBB(RestoreMBB);
22101
22102   auto RestoreMBBI = RestoreMBB->begin();
22103   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22104   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22105   return BB;
22106 }
22107
22108 MachineBasicBlock *
22109 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22110                                        MachineBasicBlock *BB) const {
22111   MachineFunction *MF = BB->getParent();
22112   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22113   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22114   // Only 32-bit SEH requires special handling for catchpad.
22115   if (IsSEH && Subtarget->is32Bit()) {
22116     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22117     DebugLoc DL = MI->getDebugLoc();
22118     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22119   }
22120   MI->eraseFromParent();
22121   return BB;
22122 }
22123
22124 MachineBasicBlock *
22125 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22126                                       MachineBasicBlock *BB) const {
22127   // This is pretty easy.  We're taking the value that we received from
22128   // our load from the relocation, sticking it in either RDI (x86-64)
22129   // or EAX and doing an indirect call.  The return value will then
22130   // be in the normal return register.
22131   MachineFunction *F = BB->getParent();
22132   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22133   DebugLoc DL = MI->getDebugLoc();
22134
22135   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22136   assert(MI->getOperand(3).isGlobal() && "This should be a global");
22137
22138   // Get a register mask for the lowered call.
22139   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22140   // proper register mask.
22141   const uint32_t *RegMask =
22142       Subtarget->is64Bit() ?
22143       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22144       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22145   if (Subtarget->is64Bit()) {
22146     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22147                                       TII->get(X86::MOV64rm), X86::RDI)
22148     .addReg(X86::RIP)
22149     .addImm(0).addReg(0)
22150     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22151                       MI->getOperand(3).getTargetFlags())
22152     .addReg(0);
22153     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22154     addDirectMem(MIB, X86::RDI);
22155     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22156   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22157     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22158                                       TII->get(X86::MOV32rm), X86::EAX)
22159     .addReg(0)
22160     .addImm(0).addReg(0)
22161     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22162                       MI->getOperand(3).getTargetFlags())
22163     .addReg(0);
22164     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22165     addDirectMem(MIB, X86::EAX);
22166     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22167   } else {
22168     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22169                                       TII->get(X86::MOV32rm), X86::EAX)
22170     .addReg(TII->getGlobalBaseReg(F))
22171     .addImm(0).addReg(0)
22172     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22173                       MI->getOperand(3).getTargetFlags())
22174     .addReg(0);
22175     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22176     addDirectMem(MIB, X86::EAX);
22177     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22178   }
22179
22180   MI->eraseFromParent(); // The pseudo instruction is gone now.
22181   return BB;
22182 }
22183
22184 MachineBasicBlock *
22185 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22186                                     MachineBasicBlock *MBB) const {
22187   DebugLoc DL = MI->getDebugLoc();
22188   MachineFunction *MF = MBB->getParent();
22189   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22190   MachineRegisterInfo &MRI = MF->getRegInfo();
22191
22192   const BasicBlock *BB = MBB->getBasicBlock();
22193   MachineFunction::iterator I = ++MBB->getIterator();
22194
22195   // Memory Reference
22196   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22197   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22198
22199   unsigned DstReg;
22200   unsigned MemOpndSlot = 0;
22201
22202   unsigned CurOp = 0;
22203
22204   DstReg = MI->getOperand(CurOp++).getReg();
22205   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22206   assert(RC->hasType(MVT::i32) && "Invalid destination!");
22207   unsigned mainDstReg = MRI.createVirtualRegister(RC);
22208   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22209
22210   MemOpndSlot = CurOp;
22211
22212   MVT PVT = getPointerTy(MF->getDataLayout());
22213   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22214          "Invalid Pointer Size!");
22215
22216   // For v = setjmp(buf), we generate
22217   //
22218   // thisMBB:
22219   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22220   //  SjLjSetup restoreMBB
22221   //
22222   // mainMBB:
22223   //  v_main = 0
22224   //
22225   // sinkMBB:
22226   //  v = phi(main, restore)
22227   //
22228   // restoreMBB:
22229   //  if base pointer being used, load it from frame
22230   //  v_restore = 1
22231
22232   MachineBasicBlock *thisMBB = MBB;
22233   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22234   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22235   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22236   MF->insert(I, mainMBB);
22237   MF->insert(I, sinkMBB);
22238   MF->push_back(restoreMBB);
22239   restoreMBB->setHasAddressTaken();
22240
22241   MachineInstrBuilder MIB;
22242
22243   // Transfer the remainder of BB and its successor edges to sinkMBB.
22244   sinkMBB->splice(sinkMBB->begin(), MBB,
22245                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22246   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22247
22248   // thisMBB:
22249   unsigned PtrStoreOpc = 0;
22250   unsigned LabelReg = 0;
22251   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22252   Reloc::Model RM = MF->getTarget().getRelocationModel();
22253   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22254                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22255
22256   // Prepare IP either in reg or imm.
22257   if (!UseImmLabel) {
22258     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22259     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22260     LabelReg = MRI.createVirtualRegister(PtrRC);
22261     if (Subtarget->is64Bit()) {
22262       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22263               .addReg(X86::RIP)
22264               .addImm(0)
22265               .addReg(0)
22266               .addMBB(restoreMBB)
22267               .addReg(0);
22268     } else {
22269       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22270       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22271               .addReg(XII->getGlobalBaseReg(MF))
22272               .addImm(0)
22273               .addReg(0)
22274               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22275               .addReg(0);
22276     }
22277   } else
22278     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22279   // Store IP
22280   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22281   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22282     if (i == X86::AddrDisp)
22283       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22284     else
22285       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22286   }
22287   if (!UseImmLabel)
22288     MIB.addReg(LabelReg);
22289   else
22290     MIB.addMBB(restoreMBB);
22291   MIB.setMemRefs(MMOBegin, MMOEnd);
22292   // Setup
22293   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22294           .addMBB(restoreMBB);
22295
22296   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22297   MIB.addRegMask(RegInfo->getNoPreservedMask());
22298   thisMBB->addSuccessor(mainMBB);
22299   thisMBB->addSuccessor(restoreMBB);
22300
22301   // mainMBB:
22302   //  EAX = 0
22303   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22304   mainMBB->addSuccessor(sinkMBB);
22305
22306   // sinkMBB:
22307   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22308           TII->get(X86::PHI), DstReg)
22309     .addReg(mainDstReg).addMBB(mainMBB)
22310     .addReg(restoreDstReg).addMBB(restoreMBB);
22311
22312   // restoreMBB:
22313   if (RegInfo->hasBasePointer(*MF)) {
22314     const bool Uses64BitFramePtr =
22315         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22316     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22317     X86FI->setRestoreBasePointer(MF);
22318     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22319     unsigned BasePtr = RegInfo->getBaseRegister();
22320     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22321     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22322                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
22323       .setMIFlag(MachineInstr::FrameSetup);
22324   }
22325   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22326   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22327   restoreMBB->addSuccessor(sinkMBB);
22328
22329   MI->eraseFromParent();
22330   return sinkMBB;
22331 }
22332
22333 MachineBasicBlock *
22334 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22335                                      MachineBasicBlock *MBB) const {
22336   DebugLoc DL = MI->getDebugLoc();
22337   MachineFunction *MF = MBB->getParent();
22338   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22339   MachineRegisterInfo &MRI = MF->getRegInfo();
22340
22341   // Memory Reference
22342   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22343   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22344
22345   MVT PVT = getPointerTy(MF->getDataLayout());
22346   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22347          "Invalid Pointer Size!");
22348
22349   const TargetRegisterClass *RC =
22350     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22351   unsigned Tmp = MRI.createVirtualRegister(RC);
22352   // Since FP is only updated here but NOT referenced, it's treated as GPR.
22353   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22354   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22355   unsigned SP = RegInfo->getStackRegister();
22356
22357   MachineInstrBuilder MIB;
22358
22359   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22360   const int64_t SPOffset = 2 * PVT.getStoreSize();
22361
22362   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22363   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22364
22365   // Reload FP
22366   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22367   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22368     MIB.addOperand(MI->getOperand(i));
22369   MIB.setMemRefs(MMOBegin, MMOEnd);
22370   // Reload IP
22371   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22372   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22373     if (i == X86::AddrDisp)
22374       MIB.addDisp(MI->getOperand(i), LabelOffset);
22375     else
22376       MIB.addOperand(MI->getOperand(i));
22377   }
22378   MIB.setMemRefs(MMOBegin, MMOEnd);
22379   // Reload SP
22380   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22381   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22382     if (i == X86::AddrDisp)
22383       MIB.addDisp(MI->getOperand(i), SPOffset);
22384     else
22385       MIB.addOperand(MI->getOperand(i));
22386   }
22387   MIB.setMemRefs(MMOBegin, MMOEnd);
22388   // Jump
22389   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22390
22391   MI->eraseFromParent();
22392   return MBB;
22393 }
22394
22395 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22396 // accumulator loops. Writing back to the accumulator allows the coalescer
22397 // to remove extra copies in the loop.
22398 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
22399 MachineBasicBlock *
22400 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22401                                  MachineBasicBlock *MBB) const {
22402   MachineOperand &AddendOp = MI->getOperand(3);
22403
22404   // Bail out early if the addend isn't a register - we can't switch these.
22405   if (!AddendOp.isReg())
22406     return MBB;
22407
22408   MachineFunction &MF = *MBB->getParent();
22409   MachineRegisterInfo &MRI = MF.getRegInfo();
22410
22411   // Check whether the addend is defined by a PHI:
22412   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22413   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22414   if (!AddendDef.isPHI())
22415     return MBB;
22416
22417   // Look for the following pattern:
22418   // loop:
22419   //   %addend = phi [%entry, 0], [%loop, %result]
22420   //   ...
22421   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22422
22423   // Replace with:
22424   //   loop:
22425   //   %addend = phi [%entry, 0], [%loop, %result]
22426   //   ...
22427   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22428
22429   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22430     assert(AddendDef.getOperand(i).isReg());
22431     MachineOperand PHISrcOp = AddendDef.getOperand(i);
22432     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22433     if (&PHISrcInst == MI) {
22434       // Found a matching instruction.
22435       unsigned NewFMAOpc = 0;
22436       switch (MI->getOpcode()) {
22437         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22438         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22439         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22440         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22441         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22442         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22443         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22444         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22445         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22446         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22447         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22448         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22449         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22450         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22451         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22452         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22453         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22454         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22455         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22456         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22457
22458         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22459         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22460         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22461         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22462         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22463         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22464         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22465         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22466         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22467         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22468         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22469         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22470         default: llvm_unreachable("Unrecognized FMA variant.");
22471       }
22472
22473       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22474       MachineInstrBuilder MIB =
22475         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22476         .addOperand(MI->getOperand(0))
22477         .addOperand(MI->getOperand(3))
22478         .addOperand(MI->getOperand(2))
22479         .addOperand(MI->getOperand(1));
22480       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22481       MI->eraseFromParent();
22482     }
22483   }
22484
22485   return MBB;
22486 }
22487
22488 MachineBasicBlock *
22489 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22490                                                MachineBasicBlock *BB) const {
22491   switch (MI->getOpcode()) {
22492   default: llvm_unreachable("Unexpected instr type to insert");
22493   case X86::TAILJMPd64:
22494   case X86::TAILJMPr64:
22495   case X86::TAILJMPm64:
22496   case X86::TAILJMPd64_REX:
22497   case X86::TAILJMPr64_REX:
22498   case X86::TAILJMPm64_REX:
22499     llvm_unreachable("TAILJMP64 would not be touched here.");
22500   case X86::TCRETURNdi64:
22501   case X86::TCRETURNri64:
22502   case X86::TCRETURNmi64:
22503     return BB;
22504   case X86::WIN_ALLOCA:
22505     return EmitLoweredWinAlloca(MI, BB);
22506   case X86::CATCHRET:
22507     return EmitLoweredCatchRet(MI, BB);
22508   case X86::CATCHPAD:
22509     return EmitLoweredCatchPad(MI, BB);
22510   case X86::SEG_ALLOCA_32:
22511   case X86::SEG_ALLOCA_64:
22512     return EmitLoweredSegAlloca(MI, BB);
22513   case X86::TLSCall_32:
22514   case X86::TLSCall_64:
22515     return EmitLoweredTLSCall(MI, BB);
22516   case X86::CMOV_FR32:
22517   case X86::CMOV_FR64:
22518   case X86::CMOV_FR128:
22519   case X86::CMOV_GR8:
22520   case X86::CMOV_GR16:
22521   case X86::CMOV_GR32:
22522   case X86::CMOV_RFP32:
22523   case X86::CMOV_RFP64:
22524   case X86::CMOV_RFP80:
22525   case X86::CMOV_V2F64:
22526   case X86::CMOV_V2I64:
22527   case X86::CMOV_V4F32:
22528   case X86::CMOV_V4F64:
22529   case X86::CMOV_V4I64:
22530   case X86::CMOV_V16F32:
22531   case X86::CMOV_V8F32:
22532   case X86::CMOV_V8F64:
22533   case X86::CMOV_V8I64:
22534   case X86::CMOV_V8I1:
22535   case X86::CMOV_V16I1:
22536   case X86::CMOV_V32I1:
22537   case X86::CMOV_V64I1:
22538     return EmitLoweredSelect(MI, BB);
22539
22540   case X86::RDFLAGS32:
22541   case X86::RDFLAGS64: {
22542     DebugLoc DL = MI->getDebugLoc();
22543     MachineFunction *MF = BB->getParent();
22544     MF->getFrameInfo()->setHasOpaqueSPAdjustment(true);
22545     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22546     unsigned PushF =
22547         MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22548     unsigned Pop =
22549         MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22550     BuildMI(*BB, MI, DL, TII->get(PushF));
22551     BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22552
22553     MI->eraseFromParent(); // The pseudo is gone now.
22554     return BB;
22555   }
22556
22557   case X86::WRFLAGS32:
22558   case X86::WRFLAGS64: {
22559     DebugLoc DL = MI->getDebugLoc();
22560     MachineFunction *MF = BB->getParent();
22561     MF->getFrameInfo()->setHasOpaqueSPAdjustment(true);
22562     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22563     unsigned Push =
22564         MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22565     unsigned PopF =
22566         MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22567     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22568     BuildMI(*BB, MI, DL, TII->get(PopF));
22569
22570     MI->eraseFromParent(); // The pseudo is gone now.
22571     return BB;
22572   }
22573
22574   case X86::RELEASE_FADD32mr:
22575   case X86::RELEASE_FADD64mr:
22576     return EmitLoweredAtomicFP(MI, BB);
22577
22578   case X86::FP32_TO_INT16_IN_MEM:
22579   case X86::FP32_TO_INT32_IN_MEM:
22580   case X86::FP32_TO_INT64_IN_MEM:
22581   case X86::FP64_TO_INT16_IN_MEM:
22582   case X86::FP64_TO_INT32_IN_MEM:
22583   case X86::FP64_TO_INT64_IN_MEM:
22584   case X86::FP80_TO_INT16_IN_MEM:
22585   case X86::FP80_TO_INT32_IN_MEM:
22586   case X86::FP80_TO_INT64_IN_MEM: {
22587     MachineFunction *F = BB->getParent();
22588     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22589     DebugLoc DL = MI->getDebugLoc();
22590
22591     // Change the floating point control register to use "round towards zero"
22592     // mode when truncating to an integer value.
22593     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22594     addFrameReference(BuildMI(*BB, MI, DL,
22595                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22596
22597     // Load the old value of the high byte of the control word...
22598     unsigned OldCW =
22599       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22600     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22601                       CWFrameIdx);
22602
22603     // Set the high part to be round to zero...
22604     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22605       .addImm(0xC7F);
22606
22607     // Reload the modified control word now...
22608     addFrameReference(BuildMI(*BB, MI, DL,
22609                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22610
22611     // Restore the memory image of control word to original value
22612     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22613       .addReg(OldCW);
22614
22615     // Get the X86 opcode to use.
22616     unsigned Opc;
22617     switch (MI->getOpcode()) {
22618     default: llvm_unreachable("illegal opcode!");
22619     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22620     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22621     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22622     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22623     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22624     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22625     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22626     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22627     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22628     }
22629
22630     X86AddressMode AM;
22631     MachineOperand &Op = MI->getOperand(0);
22632     if (Op.isReg()) {
22633       AM.BaseType = X86AddressMode::RegBase;
22634       AM.Base.Reg = Op.getReg();
22635     } else {
22636       AM.BaseType = X86AddressMode::FrameIndexBase;
22637       AM.Base.FrameIndex = Op.getIndex();
22638     }
22639     Op = MI->getOperand(1);
22640     if (Op.isImm())
22641       AM.Scale = Op.getImm();
22642     Op = MI->getOperand(2);
22643     if (Op.isImm())
22644       AM.IndexReg = Op.getImm();
22645     Op = MI->getOperand(3);
22646     if (Op.isGlobal()) {
22647       AM.GV = Op.getGlobal();
22648     } else {
22649       AM.Disp = Op.getImm();
22650     }
22651     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22652                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22653
22654     // Reload the original control word now.
22655     addFrameReference(BuildMI(*BB, MI, DL,
22656                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22657
22658     MI->eraseFromParent();   // The pseudo instruction is gone now.
22659     return BB;
22660   }
22661     // String/text processing lowering.
22662   case X86::PCMPISTRM128REG:
22663   case X86::VPCMPISTRM128REG:
22664   case X86::PCMPISTRM128MEM:
22665   case X86::VPCMPISTRM128MEM:
22666   case X86::PCMPESTRM128REG:
22667   case X86::VPCMPESTRM128REG:
22668   case X86::PCMPESTRM128MEM:
22669   case X86::VPCMPESTRM128MEM:
22670     assert(Subtarget->hasSSE42() &&
22671            "Target must have SSE4.2 or AVX features enabled");
22672     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22673
22674   // String/text processing lowering.
22675   case X86::PCMPISTRIREG:
22676   case X86::VPCMPISTRIREG:
22677   case X86::PCMPISTRIMEM:
22678   case X86::VPCMPISTRIMEM:
22679   case X86::PCMPESTRIREG:
22680   case X86::VPCMPESTRIREG:
22681   case X86::PCMPESTRIMEM:
22682   case X86::VPCMPESTRIMEM:
22683     assert(Subtarget->hasSSE42() &&
22684            "Target must have SSE4.2 or AVX features enabled");
22685     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22686
22687   // Thread synchronization.
22688   case X86::MONITOR:
22689     return EmitMonitor(MI, BB, Subtarget);
22690   // PKU feature
22691   case X86::WRPKRU:
22692     return EmitWRPKRU(MI, BB, Subtarget);
22693   case X86::RDPKRU:
22694     return EmitRDPKRU(MI, BB, Subtarget);
22695   // xbegin
22696   case X86::XBEGIN:
22697     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22698
22699   case X86::VASTART_SAVE_XMM_REGS:
22700     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22701
22702   case X86::VAARG_64:
22703     return EmitVAARG64WithCustomInserter(MI, BB);
22704
22705   case X86::EH_SjLj_SetJmp32:
22706   case X86::EH_SjLj_SetJmp64:
22707     return emitEHSjLjSetJmp(MI, BB);
22708
22709   case X86::EH_SjLj_LongJmp32:
22710   case X86::EH_SjLj_LongJmp64:
22711     return emitEHSjLjLongJmp(MI, BB);
22712
22713   case TargetOpcode::STATEPOINT:
22714     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22715     // this point in the process.  We diverge later.
22716     return emitPatchPoint(MI, BB);
22717
22718   case TargetOpcode::STACKMAP:
22719   case TargetOpcode::PATCHPOINT:
22720     return emitPatchPoint(MI, BB);
22721
22722   case X86::VFMADDPDr213r:
22723   case X86::VFMADDPSr213r:
22724   case X86::VFMADDSDr213r:
22725   case X86::VFMADDSSr213r:
22726   case X86::VFMSUBPDr213r:
22727   case X86::VFMSUBPSr213r:
22728   case X86::VFMSUBSDr213r:
22729   case X86::VFMSUBSSr213r:
22730   case X86::VFNMADDPDr213r:
22731   case X86::VFNMADDPSr213r:
22732   case X86::VFNMADDSDr213r:
22733   case X86::VFNMADDSSr213r:
22734   case X86::VFNMSUBPDr213r:
22735   case X86::VFNMSUBPSr213r:
22736   case X86::VFNMSUBSDr213r:
22737   case X86::VFNMSUBSSr213r:
22738   case X86::VFMADDSUBPDr213r:
22739   case X86::VFMADDSUBPSr213r:
22740   case X86::VFMSUBADDPDr213r:
22741   case X86::VFMSUBADDPSr213r:
22742   case X86::VFMADDPDr213rY:
22743   case X86::VFMADDPSr213rY:
22744   case X86::VFMSUBPDr213rY:
22745   case X86::VFMSUBPSr213rY:
22746   case X86::VFNMADDPDr213rY:
22747   case X86::VFNMADDPSr213rY:
22748   case X86::VFNMSUBPDr213rY:
22749   case X86::VFNMSUBPSr213rY:
22750   case X86::VFMADDSUBPDr213rY:
22751   case X86::VFMADDSUBPSr213rY:
22752   case X86::VFMSUBADDPDr213rY:
22753   case X86::VFMSUBADDPSr213rY:
22754     return emitFMA3Instr(MI, BB);
22755   }
22756 }
22757
22758 //===----------------------------------------------------------------------===//
22759 //                           X86 Optimization Hooks
22760 //===----------------------------------------------------------------------===//
22761
22762 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22763                                                       APInt &KnownZero,
22764                                                       APInt &KnownOne,
22765                                                       const SelectionDAG &DAG,
22766                                                       unsigned Depth) const {
22767   unsigned BitWidth = KnownZero.getBitWidth();
22768   unsigned Opc = Op.getOpcode();
22769   assert((Opc >= ISD::BUILTIN_OP_END ||
22770           Opc == ISD::INTRINSIC_WO_CHAIN ||
22771           Opc == ISD::INTRINSIC_W_CHAIN ||
22772           Opc == ISD::INTRINSIC_VOID) &&
22773          "Should use MaskedValueIsZero if you don't know whether Op"
22774          " is a target node!");
22775
22776   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22777   switch (Opc) {
22778   default: break;
22779   case X86ISD::ADD:
22780   case X86ISD::SUB:
22781   case X86ISD::ADC:
22782   case X86ISD::SBB:
22783   case X86ISD::SMUL:
22784   case X86ISD::UMUL:
22785   case X86ISD::INC:
22786   case X86ISD::DEC:
22787   case X86ISD::OR:
22788   case X86ISD::XOR:
22789   case X86ISD::AND:
22790     // These nodes' second result is a boolean.
22791     if (Op.getResNo() == 0)
22792       break;
22793     // Fallthrough
22794   case X86ISD::SETCC:
22795     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22796     break;
22797   case ISD::INTRINSIC_WO_CHAIN: {
22798     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22799     unsigned NumLoBits = 0;
22800     switch (IntId) {
22801     default: break;
22802     case Intrinsic::x86_sse_movmsk_ps:
22803     case Intrinsic::x86_avx_movmsk_ps_256:
22804     case Intrinsic::x86_sse2_movmsk_pd:
22805     case Intrinsic::x86_avx_movmsk_pd_256:
22806     case Intrinsic::x86_mmx_pmovmskb:
22807     case Intrinsic::x86_sse2_pmovmskb_128:
22808     case Intrinsic::x86_avx2_pmovmskb: {
22809       // High bits of movmskp{s|d}, pmovmskb are known zero.
22810       switch (IntId) {
22811         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22812         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22813         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22814         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22815         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22816         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22817         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22818         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22819       }
22820       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22821       break;
22822     }
22823     }
22824     break;
22825   }
22826   }
22827 }
22828
22829 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22830   SDValue Op,
22831   const SelectionDAG &,
22832   unsigned Depth) const {
22833   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22834   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22835     return Op.getValueType().getScalarSizeInBits();
22836
22837   // Fallback case.
22838   return 1;
22839 }
22840
22841 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22842 /// node is a GlobalAddress + offset.
22843 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22844                                        const GlobalValue* &GA,
22845                                        int64_t &Offset) const {
22846   if (N->getOpcode() == X86ISD::Wrapper) {
22847     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22848       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22849       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22850       return true;
22851     }
22852   }
22853   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22854 }
22855
22856 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22857 /// FIXME: This could be expanded to support 512 bit vectors as well.
22858 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22859                                         TargetLowering::DAGCombinerInfo &DCI,
22860                                         const X86Subtarget* Subtarget) {
22861   SDLoc dl(N);
22862   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22863   SDValue V1 = SVOp->getOperand(0);
22864   SDValue V2 = SVOp->getOperand(1);
22865   MVT VT = SVOp->getSimpleValueType(0);
22866   unsigned NumElems = VT.getVectorNumElements();
22867
22868   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22869       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22870     //
22871     //                   0,0,0,...
22872     //                      |
22873     //    V      UNDEF    BUILD_VECTOR    UNDEF
22874     //     \      /           \           /
22875     //  CONCAT_VECTOR         CONCAT_VECTOR
22876     //         \                  /
22877     //          \                /
22878     //          RESULT: V + zero extended
22879     //
22880     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22881         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22882         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22883       return SDValue();
22884
22885     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22886       return SDValue();
22887
22888     // To match the shuffle mask, the first half of the mask should
22889     // be exactly the first vector, and all the rest a splat with the
22890     // first element of the second one.
22891     for (unsigned i = 0; i != NumElems/2; ++i)
22892       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22893           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22894         return SDValue();
22895
22896     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22897     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22898       if (Ld->hasNUsesOfValue(1, 0)) {
22899         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22900         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22901         SDValue ResNode =
22902           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22903                                   Ld->getMemoryVT(),
22904                                   Ld->getPointerInfo(),
22905                                   Ld->getAlignment(),
22906                                   false/*isVolatile*/, true/*ReadMem*/,
22907                                   false/*WriteMem*/);
22908
22909         // Make sure the newly-created LOAD is in the same position as Ld in
22910         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22911         // and update uses of Ld's output chain to use the TokenFactor.
22912         if (Ld->hasAnyUseOfValue(1)) {
22913           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22914                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22915           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22916           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22917                                  SDValue(ResNode.getNode(), 1));
22918         }
22919
22920         return DAG.getBitcast(VT, ResNode);
22921       }
22922     }
22923
22924     // Emit a zeroed vector and insert the desired subvector on its
22925     // first half.
22926     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22927     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22928     return DCI.CombineTo(N, InsV);
22929   }
22930
22931   return SDValue();
22932 }
22933
22934 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22935 /// possible.
22936 ///
22937 /// This is the leaf of the recursive combinine below. When we have found some
22938 /// chain of single-use x86 shuffle instructions and accumulated the combined
22939 /// shuffle mask represented by them, this will try to pattern match that mask
22940 /// into either a single instruction if there is a special purpose instruction
22941 /// for this operation, or into a PSHUFB instruction which is a fully general
22942 /// instruction but should only be used to replace chains over a certain depth.
22943 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22944                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22945                                    TargetLowering::DAGCombinerInfo &DCI,
22946                                    const X86Subtarget *Subtarget) {
22947   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22948
22949   // Find the operand that enters the chain. Note that multiple uses are OK
22950   // here, we're not going to remove the operand we find.
22951   SDValue Input = Op.getOperand(0);
22952   while (Input.getOpcode() == ISD::BITCAST)
22953     Input = Input.getOperand(0);
22954
22955   MVT VT = Input.getSimpleValueType();
22956   MVT RootVT = Root.getSimpleValueType();
22957   SDLoc DL(Root);
22958
22959   if (Mask.size() == 1) {
22960     int Index = Mask[0];
22961     assert((Index >= 0 || Index == SM_SentinelUndef ||
22962             Index == SM_SentinelZero) &&
22963            "Invalid shuffle index found!");
22964
22965     // We may end up with an accumulated mask of size 1 as a result of
22966     // widening of shuffle operands (see function canWidenShuffleElements).
22967     // If the only shuffle index is equal to SM_SentinelZero then propagate
22968     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22969     // mask, and therefore the entire chain of shuffles can be folded away.
22970     if (Index == SM_SentinelZero)
22971       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22972     else
22973       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22974                     /*AddTo*/ true);
22975     return true;
22976   }
22977
22978   // Use the float domain if the operand type is a floating point type.
22979   bool FloatDomain = VT.isFloatingPoint();
22980
22981   // For floating point shuffles, we don't have free copies in the shuffle
22982   // instructions or the ability to load as part of the instruction, so
22983   // canonicalize their shuffles to UNPCK or MOV variants.
22984   //
22985   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22986   // vectors because it can have a load folded into it that UNPCK cannot. This
22987   // doesn't preclude something switching to the shorter encoding post-RA.
22988   //
22989   // FIXME: Should teach these routines about AVX vector widths.
22990   if (FloatDomain && VT.is128BitVector()) {
22991     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22992       bool Lo = Mask.equals({0, 0});
22993       unsigned Shuffle;
22994       MVT ShuffleVT;
22995       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22996       // is no slower than UNPCKLPD but has the option to fold the input operand
22997       // into even an unaligned memory load.
22998       if (Lo && Subtarget->hasSSE3()) {
22999         Shuffle = X86ISD::MOVDDUP;
23000         ShuffleVT = MVT::v2f64;
23001       } else {
23002         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23003         // than the UNPCK variants.
23004         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23005         ShuffleVT = MVT::v4f32;
23006       }
23007       if (Depth == 1 && Root->getOpcode() == Shuffle)
23008         return false; // Nothing to do!
23009       Op = DAG.getBitcast(ShuffleVT, Input);
23010       DCI.AddToWorklist(Op.getNode());
23011       if (Shuffle == X86ISD::MOVDDUP)
23012         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23013       else
23014         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23015       DCI.AddToWorklist(Op.getNode());
23016       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23017                     /*AddTo*/ true);
23018       return true;
23019     }
23020     if (Subtarget->hasSSE3() &&
23021         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23022       bool Lo = Mask.equals({0, 0, 2, 2});
23023       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23024       MVT ShuffleVT = MVT::v4f32;
23025       if (Depth == 1 && Root->getOpcode() == Shuffle)
23026         return false; // Nothing to do!
23027       Op = DAG.getBitcast(ShuffleVT, Input);
23028       DCI.AddToWorklist(Op.getNode());
23029       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23030       DCI.AddToWorklist(Op.getNode());
23031       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23032                     /*AddTo*/ true);
23033       return true;
23034     }
23035     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23036       bool Lo = Mask.equals({0, 0, 1, 1});
23037       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23038       MVT ShuffleVT = MVT::v4f32;
23039       if (Depth == 1 && Root->getOpcode() == Shuffle)
23040         return false; // Nothing to do!
23041       Op = DAG.getBitcast(ShuffleVT, Input);
23042       DCI.AddToWorklist(Op.getNode());
23043       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23044       DCI.AddToWorklist(Op.getNode());
23045       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23046                     /*AddTo*/ true);
23047       return true;
23048     }
23049   }
23050
23051   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23052   // variants as none of these have single-instruction variants that are
23053   // superior to the UNPCK formulation.
23054   if (!FloatDomain && VT.is128BitVector() &&
23055       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23056        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23057        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23058        Mask.equals(
23059            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23060     bool Lo = Mask[0] == 0;
23061     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23062     if (Depth == 1 && Root->getOpcode() == Shuffle)
23063       return false; // Nothing to do!
23064     MVT ShuffleVT;
23065     switch (Mask.size()) {
23066     case 8:
23067       ShuffleVT = MVT::v8i16;
23068       break;
23069     case 16:
23070       ShuffleVT = MVT::v16i8;
23071       break;
23072     default:
23073       llvm_unreachable("Impossible mask size!");
23074     };
23075     Op = DAG.getBitcast(ShuffleVT, Input);
23076     DCI.AddToWorklist(Op.getNode());
23077     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23078     DCI.AddToWorklist(Op.getNode());
23079     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23080                   /*AddTo*/ true);
23081     return true;
23082   }
23083
23084   // Don't try to re-form single instruction chains under any circumstances now
23085   // that we've done encoding canonicalization for them.
23086   if (Depth < 2)
23087     return false;
23088
23089   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23090   // can replace them with a single PSHUFB instruction profitably. Intel's
23091   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23092   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23093   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23094     SmallVector<SDValue, 16> PSHUFBMask;
23095     int NumBytes = VT.getSizeInBits() / 8;
23096     int Ratio = NumBytes / Mask.size();
23097     for (int i = 0; i < NumBytes; ++i) {
23098       if (Mask[i / Ratio] == SM_SentinelUndef) {
23099         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23100         continue;
23101       }
23102       int M = Mask[i / Ratio] != SM_SentinelZero
23103                   ? Ratio * Mask[i / Ratio] + i % Ratio
23104                   : 255;
23105       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23106     }
23107     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23108     Op = DAG.getBitcast(ByteVT, Input);
23109     DCI.AddToWorklist(Op.getNode());
23110     SDValue PSHUFBMaskOp =
23111         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23112     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23113     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23114     DCI.AddToWorklist(Op.getNode());
23115     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23116                   /*AddTo*/ true);
23117     return true;
23118   }
23119
23120   // Failed to find any combines.
23121   return false;
23122 }
23123
23124 /// \brief Fully generic combining of x86 shuffle instructions.
23125 ///
23126 /// This should be the last combine run over the x86 shuffle instructions. Once
23127 /// they have been fully optimized, this will recursively consider all chains
23128 /// of single-use shuffle instructions, build a generic model of the cumulative
23129 /// shuffle operation, and check for simpler instructions which implement this
23130 /// operation. We use this primarily for two purposes:
23131 ///
23132 /// 1) Collapse generic shuffles to specialized single instructions when
23133 ///    equivalent. In most cases, this is just an encoding size win, but
23134 ///    sometimes we will collapse multiple generic shuffles into a single
23135 ///    special-purpose shuffle.
23136 /// 2) Look for sequences of shuffle instructions with 3 or more total
23137 ///    instructions, and replace them with the slightly more expensive SSSE3
23138 ///    PSHUFB instruction if available. We do this as the last combining step
23139 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
23140 ///    a suitable short sequence of other instructions. The PHUFB will either
23141 ///    use a register or have to read from memory and so is slightly (but only
23142 ///    slightly) more expensive than the other shuffle instructions.
23143 ///
23144 /// Because this is inherently a quadratic operation (for each shuffle in
23145 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23146 /// This should never be an issue in practice as the shuffle lowering doesn't
23147 /// produce sequences of more than 8 instructions.
23148 ///
23149 /// FIXME: We will currently miss some cases where the redundant shuffling
23150 /// would simplify under the threshold for PSHUFB formation because of
23151 /// combine-ordering. To fix this, we should do the redundant instruction
23152 /// combining in this recursive walk.
23153 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23154                                           ArrayRef<int> RootMask,
23155                                           int Depth, bool HasPSHUFB,
23156                                           SelectionDAG &DAG,
23157                                           TargetLowering::DAGCombinerInfo &DCI,
23158                                           const X86Subtarget *Subtarget) {
23159   // Bound the depth of our recursive combine because this is ultimately
23160   // quadratic in nature.
23161   if (Depth > 8)
23162     return false;
23163
23164   // Directly rip through bitcasts to find the underlying operand.
23165   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23166     Op = Op.getOperand(0);
23167
23168   MVT VT = Op.getSimpleValueType();
23169   if (!VT.isVector())
23170     return false; // Bail if we hit a non-vector.
23171
23172   assert(Root.getSimpleValueType().isVector() &&
23173          "Shuffles operate on vector types!");
23174   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23175          "Can only combine shuffles of the same vector register size.");
23176
23177   if (!isTargetShuffle(Op.getOpcode()))
23178     return false;
23179   SmallVector<int, 16> OpMask;
23180   bool IsUnary;
23181   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
23182   // We only can combine unary shuffles which we can decode the mask for.
23183   if (!HaveMask || !IsUnary)
23184     return false;
23185
23186   assert(VT.getVectorNumElements() == OpMask.size() &&
23187          "Different mask size from vector size!");
23188   assert(((RootMask.size() > OpMask.size() &&
23189            RootMask.size() % OpMask.size() == 0) ||
23190           (OpMask.size() > RootMask.size() &&
23191            OpMask.size() % RootMask.size() == 0) ||
23192           OpMask.size() == RootMask.size()) &&
23193          "The smaller number of elements must divide the larger.");
23194   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23195   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23196   assert(((RootRatio == 1 && OpRatio == 1) ||
23197           (RootRatio == 1) != (OpRatio == 1)) &&
23198          "Must not have a ratio for both incoming and op masks!");
23199
23200   SmallVector<int, 16> Mask;
23201   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23202
23203   // Merge this shuffle operation's mask into our accumulated mask. Note that
23204   // this shuffle's mask will be the first applied to the input, followed by the
23205   // root mask to get us all the way to the root value arrangement. The reason
23206   // for this order is that we are recursing up the operation chain.
23207   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23208     int RootIdx = i / RootRatio;
23209     if (RootMask[RootIdx] < 0) {
23210       // This is a zero or undef lane, we're done.
23211       Mask.push_back(RootMask[RootIdx]);
23212       continue;
23213     }
23214
23215     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23216     int OpIdx = RootMaskedIdx / OpRatio;
23217     if (OpMask[OpIdx] < 0) {
23218       // The incoming lanes are zero or undef, it doesn't matter which ones we
23219       // are using.
23220       Mask.push_back(OpMask[OpIdx]);
23221       continue;
23222     }
23223
23224     // Ok, we have non-zero lanes, map them through.
23225     Mask.push_back(OpMask[OpIdx] * OpRatio +
23226                    RootMaskedIdx % OpRatio);
23227   }
23228
23229   // See if we can recurse into the operand to combine more things.
23230   switch (Op.getOpcode()) {
23231   case X86ISD::PSHUFB:
23232     HasPSHUFB = true;
23233   case X86ISD::PSHUFD:
23234   case X86ISD::PSHUFHW:
23235   case X86ISD::PSHUFLW:
23236     if (Op.getOperand(0).hasOneUse() &&
23237         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23238                                       HasPSHUFB, DAG, DCI, Subtarget))
23239       return true;
23240     break;
23241
23242   case X86ISD::UNPCKL:
23243   case X86ISD::UNPCKH:
23244     assert(Op.getOperand(0) == Op.getOperand(1) &&
23245            "We only combine unary shuffles!");
23246     // We can't check for single use, we have to check that this shuffle is the
23247     // only user.
23248     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23249         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23250                                       HasPSHUFB, DAG, DCI, Subtarget))
23251       return true;
23252     break;
23253   }
23254
23255   // Minor canonicalization of the accumulated shuffle mask to make it easier
23256   // to match below. All this does is detect masks with squential pairs of
23257   // elements, and shrink them to the half-width mask. It does this in a loop
23258   // so it will reduce the size of the mask to the minimal width mask which
23259   // performs an equivalent shuffle.
23260   SmallVector<int, 16> WidenedMask;
23261   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23262     Mask = std::move(WidenedMask);
23263     WidenedMask.clear();
23264   }
23265
23266   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23267                                 Subtarget);
23268 }
23269
23270 /// \brief Get the PSHUF-style mask from PSHUF node.
23271 ///
23272 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23273 /// PSHUF-style masks that can be reused with such instructions.
23274 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23275   MVT VT = N.getSimpleValueType();
23276   SmallVector<int, 4> Mask;
23277   bool IsUnary;
23278   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
23279   (void)HaveMask;
23280   assert(HaveMask);
23281
23282   // If we have more than 128-bits, only the low 128-bits of shuffle mask
23283   // matter. Check that the upper masks are repeats and remove them.
23284   if (VT.getSizeInBits() > 128) {
23285     int LaneElts = 128 / VT.getScalarSizeInBits();
23286 #ifndef NDEBUG
23287     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23288       for (int j = 0; j < LaneElts; ++j)
23289         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23290                "Mask doesn't repeat in high 128-bit lanes!");
23291 #endif
23292     Mask.resize(LaneElts);
23293   }
23294
23295   switch (N.getOpcode()) {
23296   case X86ISD::PSHUFD:
23297     return Mask;
23298   case X86ISD::PSHUFLW:
23299     Mask.resize(4);
23300     return Mask;
23301   case X86ISD::PSHUFHW:
23302     Mask.erase(Mask.begin(), Mask.begin() + 4);
23303     for (int &M : Mask)
23304       M -= 4;
23305     return Mask;
23306   default:
23307     llvm_unreachable("No valid shuffle instruction found!");
23308   }
23309 }
23310
23311 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23312 ///
23313 /// We walk up the chain and look for a combinable shuffle, skipping over
23314 /// shuffles that we could hoist this shuffle's transformation past without
23315 /// altering anything.
23316 static SDValue
23317 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23318                              SelectionDAG &DAG,
23319                              TargetLowering::DAGCombinerInfo &DCI) {
23320   assert(N.getOpcode() == X86ISD::PSHUFD &&
23321          "Called with something other than an x86 128-bit half shuffle!");
23322   SDLoc DL(N);
23323
23324   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23325   // of the shuffles in the chain so that we can form a fresh chain to replace
23326   // this one.
23327   SmallVector<SDValue, 8> Chain;
23328   SDValue V = N.getOperand(0);
23329   for (; V.hasOneUse(); V = V.getOperand(0)) {
23330     switch (V.getOpcode()) {
23331     default:
23332       return SDValue(); // Nothing combined!
23333
23334     case ISD::BITCAST:
23335       // Skip bitcasts as we always know the type for the target specific
23336       // instructions.
23337       continue;
23338
23339     case X86ISD::PSHUFD:
23340       // Found another dword shuffle.
23341       break;
23342
23343     case X86ISD::PSHUFLW:
23344       // Check that the low words (being shuffled) are the identity in the
23345       // dword shuffle, and the high words are self-contained.
23346       if (Mask[0] != 0 || Mask[1] != 1 ||
23347           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23348         return SDValue();
23349
23350       Chain.push_back(V);
23351       continue;
23352
23353     case X86ISD::PSHUFHW:
23354       // Check that the high words (being shuffled) are the identity in the
23355       // dword shuffle, and the low words are self-contained.
23356       if (Mask[2] != 2 || Mask[3] != 3 ||
23357           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23358         return SDValue();
23359
23360       Chain.push_back(V);
23361       continue;
23362
23363     case X86ISD::UNPCKL:
23364     case X86ISD::UNPCKH:
23365       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23366       // shuffle into a preceding word shuffle.
23367       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23368           V.getSimpleValueType().getVectorElementType() != MVT::i16)
23369         return SDValue();
23370
23371       // Search for a half-shuffle which we can combine with.
23372       unsigned CombineOp =
23373           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23374       if (V.getOperand(0) != V.getOperand(1) ||
23375           !V->isOnlyUserOf(V.getOperand(0).getNode()))
23376         return SDValue();
23377       Chain.push_back(V);
23378       V = V.getOperand(0);
23379       do {
23380         switch (V.getOpcode()) {
23381         default:
23382           return SDValue(); // Nothing to combine.
23383
23384         case X86ISD::PSHUFLW:
23385         case X86ISD::PSHUFHW:
23386           if (V.getOpcode() == CombineOp)
23387             break;
23388
23389           Chain.push_back(V);
23390
23391           // Fallthrough!
23392         case ISD::BITCAST:
23393           V = V.getOperand(0);
23394           continue;
23395         }
23396         break;
23397       } while (V.hasOneUse());
23398       break;
23399     }
23400     // Break out of the loop if we break out of the switch.
23401     break;
23402   }
23403
23404   if (!V.hasOneUse())
23405     // We fell out of the loop without finding a viable combining instruction.
23406     return SDValue();
23407
23408   // Merge this node's mask and our incoming mask.
23409   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23410   for (int &M : Mask)
23411     M = VMask[M];
23412   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23413                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23414
23415   // Rebuild the chain around this new shuffle.
23416   while (!Chain.empty()) {
23417     SDValue W = Chain.pop_back_val();
23418
23419     if (V.getValueType() != W.getOperand(0).getValueType())
23420       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23421
23422     switch (W.getOpcode()) {
23423     default:
23424       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23425
23426     case X86ISD::UNPCKL:
23427     case X86ISD::UNPCKH:
23428       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23429       break;
23430
23431     case X86ISD::PSHUFD:
23432     case X86ISD::PSHUFLW:
23433     case X86ISD::PSHUFHW:
23434       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23435       break;
23436     }
23437   }
23438   if (V.getValueType() != N.getValueType())
23439     V = DAG.getBitcast(N.getValueType(), V);
23440
23441   // Return the new chain to replace N.
23442   return V;
23443 }
23444
23445 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23446 /// pshufhw.
23447 ///
23448 /// We walk up the chain, skipping shuffles of the other half and looking
23449 /// through shuffles which switch halves trying to find a shuffle of the same
23450 /// pair of dwords.
23451 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23452                                         SelectionDAG &DAG,
23453                                         TargetLowering::DAGCombinerInfo &DCI) {
23454   assert(
23455       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23456       "Called with something other than an x86 128-bit half shuffle!");
23457   SDLoc DL(N);
23458   unsigned CombineOpcode = N.getOpcode();
23459
23460   // Walk up a single-use chain looking for a combinable shuffle.
23461   SDValue V = N.getOperand(0);
23462   for (; V.hasOneUse(); V = V.getOperand(0)) {
23463     switch (V.getOpcode()) {
23464     default:
23465       return false; // Nothing combined!
23466
23467     case ISD::BITCAST:
23468       // Skip bitcasts as we always know the type for the target specific
23469       // instructions.
23470       continue;
23471
23472     case X86ISD::PSHUFLW:
23473     case X86ISD::PSHUFHW:
23474       if (V.getOpcode() == CombineOpcode)
23475         break;
23476
23477       // Other-half shuffles are no-ops.
23478       continue;
23479     }
23480     // Break out of the loop if we break out of the switch.
23481     break;
23482   }
23483
23484   if (!V.hasOneUse())
23485     // We fell out of the loop without finding a viable combining instruction.
23486     return false;
23487
23488   // Combine away the bottom node as its shuffle will be accumulated into
23489   // a preceding shuffle.
23490   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23491
23492   // Record the old value.
23493   SDValue Old = V;
23494
23495   // Merge this node's mask and our incoming mask (adjusted to account for all
23496   // the pshufd instructions encountered).
23497   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23498   for (int &M : Mask)
23499     M = VMask[M];
23500   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23501                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23502
23503   // Check that the shuffles didn't cancel each other out. If not, we need to
23504   // combine to the new one.
23505   if (Old != V)
23506     // Replace the combinable shuffle with the combined one, updating all users
23507     // so that we re-evaluate the chain here.
23508     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23509
23510   return true;
23511 }
23512
23513 /// \brief Try to combine x86 target specific shuffles.
23514 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23515                                            TargetLowering::DAGCombinerInfo &DCI,
23516                                            const X86Subtarget *Subtarget) {
23517   SDLoc DL(N);
23518   MVT VT = N.getSimpleValueType();
23519   SmallVector<int, 4> Mask;
23520
23521   switch (N.getOpcode()) {
23522   case X86ISD::PSHUFD:
23523   case X86ISD::PSHUFLW:
23524   case X86ISD::PSHUFHW:
23525     Mask = getPSHUFShuffleMask(N);
23526     assert(Mask.size() == 4);
23527     break;
23528   case X86ISD::UNPCKL: {
23529     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23530     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23531     // moves upper half elements into the lower half part. For example:
23532     //
23533     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23534     //     undef:v16i8
23535     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23536     //
23537     // will be combined to:
23538     //
23539     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23540
23541     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23542     // happen due to advanced instructions.
23543     if (!VT.is128BitVector())
23544       return SDValue();
23545
23546     auto Op0 = N.getOperand(0);
23547     auto Op1 = N.getOperand(1);
23548     if (Op0.getOpcode() == ISD::UNDEF &&
23549         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23550       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23551
23552       unsigned NumElts = VT.getVectorNumElements();
23553       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23554       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23555                 NumElts / 2);
23556
23557       auto ShufOp = Op1.getOperand(0);
23558       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23559         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23560     }
23561     return SDValue();
23562   }
23563   default:
23564     return SDValue();
23565   }
23566
23567   // Nuke no-op shuffles that show up after combining.
23568   if (isNoopShuffleMask(Mask))
23569     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23570
23571   // Look for simplifications involving one or two shuffle instructions.
23572   SDValue V = N.getOperand(0);
23573   switch (N.getOpcode()) {
23574   default:
23575     break;
23576   case X86ISD::PSHUFLW:
23577   case X86ISD::PSHUFHW:
23578     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23579
23580     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23581       return SDValue(); // We combined away this shuffle, so we're done.
23582
23583     // See if this reduces to a PSHUFD which is no more expensive and can
23584     // combine with more operations. Note that it has to at least flip the
23585     // dwords as otherwise it would have been removed as a no-op.
23586     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23587       int DMask[] = {0, 1, 2, 3};
23588       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23589       DMask[DOffset + 0] = DOffset + 1;
23590       DMask[DOffset + 1] = DOffset + 0;
23591       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23592       V = DAG.getBitcast(DVT, V);
23593       DCI.AddToWorklist(V.getNode());
23594       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23595                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23596       DCI.AddToWorklist(V.getNode());
23597       return DAG.getBitcast(VT, V);
23598     }
23599
23600     // Look for shuffle patterns which can be implemented as a single unpack.
23601     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23602     // only works when we have a PSHUFD followed by two half-shuffles.
23603     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23604         (V.getOpcode() == X86ISD::PSHUFLW ||
23605          V.getOpcode() == X86ISD::PSHUFHW) &&
23606         V.getOpcode() != N.getOpcode() &&
23607         V.hasOneUse()) {
23608       SDValue D = V.getOperand(0);
23609       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23610         D = D.getOperand(0);
23611       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23612         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23613         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23614         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23615         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23616         int WordMask[8];
23617         for (int i = 0; i < 4; ++i) {
23618           WordMask[i + NOffset] = Mask[i] + NOffset;
23619           WordMask[i + VOffset] = VMask[i] + VOffset;
23620         }
23621         // Map the word mask through the DWord mask.
23622         int MappedMask[8];
23623         for (int i = 0; i < 8; ++i)
23624           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23625         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23626             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23627           // We can replace all three shuffles with an unpack.
23628           V = DAG.getBitcast(VT, D.getOperand(0));
23629           DCI.AddToWorklist(V.getNode());
23630           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23631                                                 : X86ISD::UNPCKH,
23632                              DL, VT, V, V);
23633         }
23634       }
23635     }
23636
23637     break;
23638
23639   case X86ISD::PSHUFD:
23640     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23641       return NewN;
23642
23643     break;
23644   }
23645
23646   return SDValue();
23647 }
23648
23649 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23650 ///
23651 /// We combine this directly on the abstract vector shuffle nodes so it is
23652 /// easier to generically match. We also insert dummy vector shuffle nodes for
23653 /// the operands which explicitly discard the lanes which are unused by this
23654 /// operation to try to flow through the rest of the combiner the fact that
23655 /// they're unused.
23656 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23657   SDLoc DL(N);
23658   EVT VT = N->getValueType(0);
23659
23660   // We only handle target-independent shuffles.
23661   // FIXME: It would be easy and harmless to use the target shuffle mask
23662   // extraction tool to support more.
23663   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23664     return SDValue();
23665
23666   auto *SVN = cast<ShuffleVectorSDNode>(N);
23667   SmallVector<int, 8> Mask;
23668   for (int M : SVN->getMask())
23669     Mask.push_back(M);
23670
23671   SDValue V1 = N->getOperand(0);
23672   SDValue V2 = N->getOperand(1);
23673
23674   // We require the first shuffle operand to be the FSUB node, and the second to
23675   // be the FADD node.
23676   if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23677     ShuffleVectorSDNode::commuteMask(Mask);
23678     std::swap(V1, V2);
23679   } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23680     return SDValue();
23681
23682   // If there are other uses of these operations we can't fold them.
23683   if (!V1->hasOneUse() || !V2->hasOneUse())
23684     return SDValue();
23685
23686   // Ensure that both operations have the same operands. Note that we can
23687   // commute the FADD operands.
23688   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23689   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23690       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23691     return SDValue();
23692
23693   // We're looking for blends between FADD and FSUB nodes. We insist on these
23694   // nodes being lined up in a specific expected pattern.
23695   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23696         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23697         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23698     return SDValue();
23699
23700   // Only specific types are legal at this point, assert so we notice if and
23701   // when these change.
23702   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23703           VT == MVT::v4f64) &&
23704          "Unknown vector type encountered!");
23705
23706   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23707 }
23708
23709 /// PerformShuffleCombine - Performs several different shuffle combines.
23710 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23711                                      TargetLowering::DAGCombinerInfo &DCI,
23712                                      const X86Subtarget *Subtarget) {
23713   SDLoc dl(N);
23714   SDValue N0 = N->getOperand(0);
23715   SDValue N1 = N->getOperand(1);
23716   EVT VT = N->getValueType(0);
23717
23718   // Don't create instructions with illegal types after legalize types has run.
23719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23720   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23721     return SDValue();
23722
23723   // If we have legalized the vector types, look for blends of FADD and FSUB
23724   // nodes that we can fuse into an ADDSUB node.
23725   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23726     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23727       return AddSub;
23728
23729   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23730   if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23731       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23732     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23733
23734   // During Type Legalization, when promoting illegal vector types,
23735   // the backend might introduce new shuffle dag nodes and bitcasts.
23736   //
23737   // This code performs the following transformation:
23738   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23739   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23740   //
23741   // We do this only if both the bitcast and the BINOP dag nodes have
23742   // one use. Also, perform this transformation only if the new binary
23743   // operation is legal. This is to avoid introducing dag nodes that
23744   // potentially need to be further expanded (or custom lowered) into a
23745   // less optimal sequence of dag nodes.
23746   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23747       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23748       N0.getOpcode() == ISD::BITCAST) {
23749     SDValue BC0 = N0.getOperand(0);
23750     EVT SVT = BC0.getValueType();
23751     unsigned Opcode = BC0.getOpcode();
23752     unsigned NumElts = VT.getVectorNumElements();
23753
23754     if (BC0.hasOneUse() && SVT.isVector() &&
23755         SVT.getVectorNumElements() * 2 == NumElts &&
23756         TLI.isOperationLegal(Opcode, VT)) {
23757       bool CanFold = false;
23758       switch (Opcode) {
23759       default : break;
23760       case ISD::ADD :
23761       case ISD::FADD :
23762       case ISD::SUB :
23763       case ISD::FSUB :
23764       case ISD::MUL :
23765       case ISD::FMUL :
23766         CanFold = true;
23767       }
23768
23769       unsigned SVTNumElts = SVT.getVectorNumElements();
23770       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23771       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23772         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23773       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23774         CanFold = SVOp->getMaskElt(i) < 0;
23775
23776       if (CanFold) {
23777         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23778         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23779         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23780         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23781       }
23782     }
23783   }
23784
23785   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23786   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23787   // consecutive, non-overlapping, and in the right order.
23788   SmallVector<SDValue, 16> Elts;
23789   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23790     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23791
23792   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23793     return LD;
23794
23795   if (isTargetShuffle(N->getOpcode())) {
23796     SDValue Shuffle =
23797         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23798     if (Shuffle.getNode())
23799       return Shuffle;
23800
23801     // Try recursively combining arbitrary sequences of x86 shuffle
23802     // instructions into higher-order shuffles. We do this after combining
23803     // specific PSHUF instruction sequences into their minimal form so that we
23804     // can evaluate how many specialized shuffle instructions are involved in
23805     // a particular chain.
23806     SmallVector<int, 1> NonceMask; // Just a placeholder.
23807     NonceMask.push_back(0);
23808     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23809                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23810                                       DCI, Subtarget))
23811       return SDValue(); // This routine will use CombineTo to replace N.
23812   }
23813
23814   return SDValue();
23815 }
23816
23817 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23818 /// specific shuffle of a load can be folded into a single element load.
23819 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23820 /// shuffles have been custom lowered so we need to handle those here.
23821 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23822                                          TargetLowering::DAGCombinerInfo &DCI) {
23823   if (DCI.isBeforeLegalizeOps())
23824     return SDValue();
23825
23826   SDValue InVec = N->getOperand(0);
23827   SDValue EltNo = N->getOperand(1);
23828
23829   if (!isa<ConstantSDNode>(EltNo))
23830     return SDValue();
23831
23832   EVT OriginalVT = InVec.getValueType();
23833
23834   if (InVec.getOpcode() == ISD::BITCAST) {
23835     // Don't duplicate a load with other uses.
23836     if (!InVec.hasOneUse())
23837       return SDValue();
23838     EVT BCVT = InVec.getOperand(0).getValueType();
23839     if (!BCVT.isVector() ||
23840         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23841       return SDValue();
23842     InVec = InVec.getOperand(0);
23843   }
23844
23845   EVT CurrentVT = InVec.getValueType();
23846
23847   if (!isTargetShuffle(InVec.getOpcode()))
23848     return SDValue();
23849
23850   // Don't duplicate a load with other uses.
23851   if (!InVec.hasOneUse())
23852     return SDValue();
23853
23854   SmallVector<int, 16> ShuffleMask;
23855   bool UnaryShuffle;
23856   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23857                             ShuffleMask, UnaryShuffle))
23858     return SDValue();
23859
23860   // Select the input vector, guarding against out of range extract vector.
23861   unsigned NumElems = CurrentVT.getVectorNumElements();
23862   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23863   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23864   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23865                                          : InVec.getOperand(1);
23866
23867   // If inputs to shuffle are the same for both ops, then allow 2 uses
23868   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23869                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23870
23871   if (LdNode.getOpcode() == ISD::BITCAST) {
23872     // Don't duplicate a load with other uses.
23873     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23874       return SDValue();
23875
23876     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23877     LdNode = LdNode.getOperand(0);
23878   }
23879
23880   if (!ISD::isNormalLoad(LdNode.getNode()))
23881     return SDValue();
23882
23883   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23884
23885   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23886     return SDValue();
23887
23888   EVT EltVT = N->getValueType(0);
23889   // If there's a bitcast before the shuffle, check if the load type and
23890   // alignment is valid.
23891   unsigned Align = LN0->getAlignment();
23892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23893   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23894       EltVT.getTypeForEVT(*DAG.getContext()));
23895
23896   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23897     return SDValue();
23898
23899   // All checks match so transform back to vector_shuffle so that DAG combiner
23900   // can finish the job
23901   SDLoc dl(N);
23902
23903   // Create shuffle node taking into account the case that its a unary shuffle
23904   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23905                                    : InVec.getOperand(1);
23906   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23907                                  InVec.getOperand(0), Shuffle,
23908                                  &ShuffleMask[0]);
23909   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23910   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23911                      EltNo);
23912 }
23913
23914 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23915                                      const X86Subtarget *Subtarget) {
23916   SDValue N0 = N->getOperand(0);
23917   EVT VT = N->getValueType(0);
23918
23919   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23920   // special and don't usually play with other vector types, it's better to
23921   // handle them early to be sure we emit efficient code by avoiding
23922   // store-load conversions.
23923   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23924       N0.getValueType() == MVT::v2i32 &&
23925       isNullConstant(N0.getOperand(1))) {
23926     SDValue N00 = N0->getOperand(0);
23927     if (N00.getValueType() == MVT::i32)
23928       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23929   }
23930
23931   // Convert a bitcasted integer logic operation that has one bitcasted
23932   // floating-point operand and one constant operand into a floating-point
23933   // logic operation. This may create a load of the constant, but that is
23934   // cheaper than materializing the constant in an integer register and
23935   // transferring it to an SSE register or transferring the SSE operand to
23936   // integer register and back.
23937   unsigned FPOpcode;
23938   switch (N0.getOpcode()) {
23939     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23940     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23941     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23942     default: return SDValue();
23943   }
23944   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23945        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23946       isa<ConstantSDNode>(N0.getOperand(1)) &&
23947       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23948       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23949     SDValue N000 = N0.getOperand(0).getOperand(0);
23950     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23951     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23952   }
23953
23954   return SDValue();
23955 }
23956
23957 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23958 /// generation and convert it from being a bunch of shuffles and extracts
23959 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23960 /// storing the value and loading scalars back, while for x64 we should
23961 /// use 64-bit extracts and shifts.
23962 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23963                                          TargetLowering::DAGCombinerInfo &DCI) {
23964   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23965     return NewOp;
23966
23967   SDValue InputVector = N->getOperand(0);
23968   SDLoc dl(InputVector);
23969   // Detect mmx to i32 conversion through a v2i32 elt extract.
23970   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23971       N->getValueType(0) == MVT::i32 &&
23972       InputVector.getValueType() == MVT::v2i32) {
23973
23974     // The bitcast source is a direct mmx result.
23975     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23976     if (MMXSrc.getValueType() == MVT::x86mmx)
23977       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23978                          N->getValueType(0),
23979                          InputVector.getNode()->getOperand(0));
23980
23981     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23982     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23983         MMXSrc.getValueType() == MVT::i64) {
23984       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23985       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23986           MMXSrcOp.getValueType() == MVT::v1i64 &&
23987           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23988         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23989                            N->getValueType(0), MMXSrcOp.getOperand(0));
23990     }
23991   }
23992
23993   EVT VT = N->getValueType(0);
23994
23995   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
23996       InputVector.getOpcode() == ISD::BITCAST &&
23997       isa<ConstantSDNode>(InputVector.getOperand(0))) {
23998     uint64_t ExtractedElt =
23999         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24000     uint64_t InputValue =
24001         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24002     uint64_t Res = (InputValue >> ExtractedElt) & 1;
24003     return DAG.getConstant(Res, dl, MVT::i1);
24004   }
24005   // Only operate on vectors of 4 elements, where the alternative shuffling
24006   // gets to be more expensive.
24007   if (InputVector.getValueType() != MVT::v4i32)
24008     return SDValue();
24009
24010   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24011   // single use which is a sign-extend or zero-extend, and all elements are
24012   // used.
24013   SmallVector<SDNode *, 4> Uses;
24014   unsigned ExtractedElements = 0;
24015   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24016        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24017     if (UI.getUse().getResNo() != InputVector.getResNo())
24018       return SDValue();
24019
24020     SDNode *Extract = *UI;
24021     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24022       return SDValue();
24023
24024     if (Extract->getValueType(0) != MVT::i32)
24025       return SDValue();
24026     if (!Extract->hasOneUse())
24027       return SDValue();
24028     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24029         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24030       return SDValue();
24031     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24032       return SDValue();
24033
24034     // Record which element was extracted.
24035     ExtractedElements |=
24036       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24037
24038     Uses.push_back(Extract);
24039   }
24040
24041   // If not all the elements were used, this may not be worthwhile.
24042   if (ExtractedElements != 15)
24043     return SDValue();
24044
24045   // Ok, we've now decided to do the transformation.
24046   // If 64-bit shifts are legal, use the extract-shift sequence,
24047   // otherwise bounce the vector off the cache.
24048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24049   SDValue Vals[4];
24050
24051   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24052     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24053     auto &DL = DAG.getDataLayout();
24054     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24055     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24056       DAG.getConstant(0, dl, VecIdxTy));
24057     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24058       DAG.getConstant(1, dl, VecIdxTy));
24059
24060     SDValue ShAmt = DAG.getConstant(
24061         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24062     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24063     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24064       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24065     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24066     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24067       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24068   } else {
24069     // Store the value to a temporary stack slot.
24070     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24071     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24072       MachinePointerInfo(), false, false, 0);
24073
24074     EVT ElementType = InputVector.getValueType().getVectorElementType();
24075     unsigned EltSize = ElementType.getSizeInBits() / 8;
24076
24077     // Replace each use (extract) with a load of the appropriate element.
24078     for (unsigned i = 0; i < 4; ++i) {
24079       uint64_t Offset = EltSize * i;
24080       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24081       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24082
24083       SDValue ScalarAddr =
24084           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24085
24086       // Load the scalar.
24087       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24088                             ScalarAddr, MachinePointerInfo(),
24089                             false, false, false, 0);
24090
24091     }
24092   }
24093
24094   // Replace the extracts
24095   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24096     UE = Uses.end(); UI != UE; ++UI) {
24097     SDNode *Extract = *UI;
24098
24099     SDValue Idx = Extract->getOperand(1);
24100     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24101     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24102   }
24103
24104   // The replacement was made in place; don't return anything.
24105   return SDValue();
24106 }
24107
24108 static SDValue
24109 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24110                                       const X86Subtarget *Subtarget) {
24111   SDLoc dl(N);
24112   SDValue Cond = N->getOperand(0);
24113   SDValue LHS = N->getOperand(1);
24114   SDValue RHS = N->getOperand(2);
24115
24116   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24117     SDValue CondSrc = Cond->getOperand(0);
24118     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24119       Cond = CondSrc->getOperand(0);
24120   }
24121
24122   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24123     return SDValue();
24124
24125   // A vselect where all conditions and data are constants can be optimized into
24126   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24127   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24128       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24129     return SDValue();
24130
24131   unsigned MaskValue = 0;
24132   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24133     return SDValue();
24134
24135   MVT VT = N->getSimpleValueType(0);
24136   unsigned NumElems = VT.getVectorNumElements();
24137   SmallVector<int, 8> ShuffleMask(NumElems, -1);
24138   for (unsigned i = 0; i < NumElems; ++i) {
24139     // Be sure we emit undef where we can.
24140     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24141       ShuffleMask[i] = -1;
24142     else
24143       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24144   }
24145
24146   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24147   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24148     return SDValue();
24149   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24150 }
24151
24152 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24153 /// nodes.
24154 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24155                                     TargetLowering::DAGCombinerInfo &DCI,
24156                                     const X86Subtarget *Subtarget) {
24157   SDLoc DL(N);
24158   SDValue Cond = N->getOperand(0);
24159   // Get the LHS/RHS of the select.
24160   SDValue LHS = N->getOperand(1);
24161   SDValue RHS = N->getOperand(2);
24162   EVT VT = LHS.getValueType();
24163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24164
24165   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24166   // instructions match the semantics of the common C idiom x<y?x:y but not
24167   // x<=y?x:y, because of how they handle negative zero (which can be
24168   // ignored in unsafe-math mode).
24169   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24170   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24171       VT != MVT::f80 && VT != MVT::f128 &&
24172       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24173       (Subtarget->hasSSE2() ||
24174        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24175     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24176
24177     unsigned Opcode = 0;
24178     // Check for x CC y ? x : y.
24179     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24180         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24181       switch (CC) {
24182       default: break;
24183       case ISD::SETULT:
24184         // Converting this to a min would handle NaNs incorrectly, and swapping
24185         // the operands would cause it to handle comparisons between positive
24186         // and negative zero incorrectly.
24187         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24188           if (!DAG.getTarget().Options.UnsafeFPMath &&
24189               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24190             break;
24191           std::swap(LHS, RHS);
24192         }
24193         Opcode = X86ISD::FMIN;
24194         break;
24195       case ISD::SETOLE:
24196         // Converting this to a min would handle comparisons between positive
24197         // and negative zero incorrectly.
24198         if (!DAG.getTarget().Options.UnsafeFPMath &&
24199             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24200           break;
24201         Opcode = X86ISD::FMIN;
24202         break;
24203       case ISD::SETULE:
24204         // Converting this to a min would handle both negative zeros and NaNs
24205         // incorrectly, but we can swap the operands to fix both.
24206         std::swap(LHS, RHS);
24207       case ISD::SETOLT:
24208       case ISD::SETLT:
24209       case ISD::SETLE:
24210         Opcode = X86ISD::FMIN;
24211         break;
24212
24213       case ISD::SETOGE:
24214         // Converting this to a max would handle comparisons between positive
24215         // and negative zero incorrectly.
24216         if (!DAG.getTarget().Options.UnsafeFPMath &&
24217             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24218           break;
24219         Opcode = X86ISD::FMAX;
24220         break;
24221       case ISD::SETUGT:
24222         // Converting this to a max would handle NaNs incorrectly, and swapping
24223         // the operands would cause it to handle comparisons between positive
24224         // and negative zero incorrectly.
24225         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24226           if (!DAG.getTarget().Options.UnsafeFPMath &&
24227               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24228             break;
24229           std::swap(LHS, RHS);
24230         }
24231         Opcode = X86ISD::FMAX;
24232         break;
24233       case ISD::SETUGE:
24234         // Converting this to a max would handle both negative zeros and NaNs
24235         // incorrectly, but we can swap the operands to fix both.
24236         std::swap(LHS, RHS);
24237       case ISD::SETOGT:
24238       case ISD::SETGT:
24239       case ISD::SETGE:
24240         Opcode = X86ISD::FMAX;
24241         break;
24242       }
24243     // Check for x CC y ? y : x -- a min/max with reversed arms.
24244     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24245                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24246       switch (CC) {
24247       default: break;
24248       case ISD::SETOGE:
24249         // Converting this to a min would handle comparisons between positive
24250         // and negative zero incorrectly, and swapping the operands would
24251         // cause it to handle NaNs incorrectly.
24252         if (!DAG.getTarget().Options.UnsafeFPMath &&
24253             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24254           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24255             break;
24256           std::swap(LHS, RHS);
24257         }
24258         Opcode = X86ISD::FMIN;
24259         break;
24260       case ISD::SETUGT:
24261         // Converting this to a min would handle NaNs incorrectly.
24262         if (!DAG.getTarget().Options.UnsafeFPMath &&
24263             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24264           break;
24265         Opcode = X86ISD::FMIN;
24266         break;
24267       case ISD::SETUGE:
24268         // Converting this to a min would handle both negative zeros and NaNs
24269         // incorrectly, but we can swap the operands to fix both.
24270         std::swap(LHS, RHS);
24271       case ISD::SETOGT:
24272       case ISD::SETGT:
24273       case ISD::SETGE:
24274         Opcode = X86ISD::FMIN;
24275         break;
24276
24277       case ISD::SETULT:
24278         // Converting this to a max would handle NaNs incorrectly.
24279         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24280           break;
24281         Opcode = X86ISD::FMAX;
24282         break;
24283       case ISD::SETOLE:
24284         // Converting this to a max would handle comparisons between positive
24285         // and negative zero incorrectly, and swapping the operands would
24286         // cause it to handle NaNs incorrectly.
24287         if (!DAG.getTarget().Options.UnsafeFPMath &&
24288             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24289           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24290             break;
24291           std::swap(LHS, RHS);
24292         }
24293         Opcode = X86ISD::FMAX;
24294         break;
24295       case ISD::SETULE:
24296         // Converting this to a max would handle both negative zeros and NaNs
24297         // incorrectly, but we can swap the operands to fix both.
24298         std::swap(LHS, RHS);
24299       case ISD::SETOLT:
24300       case ISD::SETLT:
24301       case ISD::SETLE:
24302         Opcode = X86ISD::FMAX;
24303         break;
24304       }
24305     }
24306
24307     if (Opcode)
24308       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24309   }
24310
24311   EVT CondVT = Cond.getValueType();
24312   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24313       CondVT.getVectorElementType() == MVT::i1) {
24314     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24315     // lowering on KNL. In this case we convert it to
24316     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24317     // The same situation for all 128 and 256-bit vectors of i8 and i16.
24318     // Since SKX these selects have a proper lowering.
24319     EVT OpVT = LHS.getValueType();
24320     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24321         (OpVT.getVectorElementType() == MVT::i8 ||
24322          OpVT.getVectorElementType() == MVT::i16) &&
24323         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24324       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24325       DCI.AddToWorklist(Cond.getNode());
24326       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24327     }
24328   }
24329   // If this is a select between two integer constants, try to do some
24330   // optimizations.
24331   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24332     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24333       // Don't do this for crazy integer types.
24334       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24335         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24336         // so that TrueC (the true value) is larger than FalseC.
24337         bool NeedsCondInvert = false;
24338
24339         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24340             // Efficiently invertible.
24341             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
24342              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
24343               isa<ConstantSDNode>(Cond.getOperand(1))))) {
24344           NeedsCondInvert = true;
24345           std::swap(TrueC, FalseC);
24346         }
24347
24348         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
24349         if (FalseC->getAPIntValue() == 0 &&
24350             TrueC->getAPIntValue().isPowerOf2()) {
24351           if (NeedsCondInvert) // Invert the condition if needed.
24352             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24353                                DAG.getConstant(1, DL, Cond.getValueType()));
24354
24355           // Zero extend the condition if needed.
24356           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24357
24358           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24359           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24360                              DAG.getConstant(ShAmt, DL, MVT::i8));
24361         }
24362
24363         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24364         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24365           if (NeedsCondInvert) // Invert the condition if needed.
24366             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24367                                DAG.getConstant(1, DL, Cond.getValueType()));
24368
24369           // Zero extend the condition if needed.
24370           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24371                              FalseC->getValueType(0), Cond);
24372           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24373                              SDValue(FalseC, 0));
24374         }
24375
24376         // Optimize cases that will turn into an LEA instruction.  This requires
24377         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24378         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24379           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24380           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24381
24382           bool isFastMultiplier = false;
24383           if (Diff < 10) {
24384             switch ((unsigned char)Diff) {
24385               default: break;
24386               case 1:  // result = add base, cond
24387               case 2:  // result = lea base(    , cond*2)
24388               case 3:  // result = lea base(cond, cond*2)
24389               case 4:  // result = lea base(    , cond*4)
24390               case 5:  // result = lea base(cond, cond*4)
24391               case 8:  // result = lea base(    , cond*8)
24392               case 9:  // result = lea base(cond, cond*8)
24393                 isFastMultiplier = true;
24394                 break;
24395             }
24396           }
24397
24398           if (isFastMultiplier) {
24399             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24400             if (NeedsCondInvert) // Invert the condition if needed.
24401               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24402                                  DAG.getConstant(1, DL, Cond.getValueType()));
24403
24404             // Zero extend the condition if needed.
24405             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24406                                Cond);
24407             // Scale the condition by the difference.
24408             if (Diff != 1)
24409               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24410                                  DAG.getConstant(Diff, DL,
24411                                                  Cond.getValueType()));
24412
24413             // Add the base if non-zero.
24414             if (FalseC->getAPIntValue() != 0)
24415               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24416                                  SDValue(FalseC, 0));
24417             return Cond;
24418           }
24419         }
24420       }
24421   }
24422
24423   // Canonicalize max and min:
24424   // (x > y) ? x : y -> (x >= y) ? x : y
24425   // (x < y) ? x : y -> (x <= y) ? x : y
24426   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24427   // the need for an extra compare
24428   // against zero. e.g.
24429   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24430   // subl   %esi, %edi
24431   // testl  %edi, %edi
24432   // movl   $0, %eax
24433   // cmovgl %edi, %eax
24434   // =>
24435   // xorl   %eax, %eax
24436   // subl   %esi, $edi
24437   // cmovsl %eax, %edi
24438   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24439       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24440       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24441     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24442     switch (CC) {
24443     default: break;
24444     case ISD::SETLT:
24445     case ISD::SETGT: {
24446       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24447       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24448                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
24449       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24450     }
24451     }
24452   }
24453
24454   // Early exit check
24455   if (!TLI.isTypeLegal(VT))
24456     return SDValue();
24457
24458   // Match VSELECTs into subs with unsigned saturation.
24459   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24460       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24461       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24462        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24463     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24464
24465     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24466     // left side invert the predicate to simplify logic below.
24467     SDValue Other;
24468     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24469       Other = RHS;
24470       CC = ISD::getSetCCInverse(CC, true);
24471     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24472       Other = LHS;
24473     }
24474
24475     if (Other.getNode() && Other->getNumOperands() == 2 &&
24476         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24477       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24478       SDValue CondRHS = Cond->getOperand(1);
24479
24480       // Look for a general sub with unsigned saturation first.
24481       // x >= y ? x-y : 0 --> subus x, y
24482       // x >  y ? x-y : 0 --> subus x, y
24483       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24484           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24485         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24486
24487       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24488         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24489           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24490             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24491               // If the RHS is a constant we have to reverse the const
24492               // canonicalization.
24493               // x > C-1 ? x+-C : 0 --> subus x, C
24494               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24495                   CondRHSConst->getAPIntValue() ==
24496                       (-OpRHSConst->getAPIntValue() - 1))
24497                 return DAG.getNode(
24498                     X86ISD::SUBUS, DL, VT, OpLHS,
24499                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24500
24501           // Another special case: If C was a sign bit, the sub has been
24502           // canonicalized into a xor.
24503           // FIXME: Would it be better to use computeKnownBits to determine
24504           //        whether it's safe to decanonicalize the xor?
24505           // x s< 0 ? x^C : 0 --> subus x, C
24506           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24507               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24508               OpRHSConst->getAPIntValue().isSignBit())
24509             // Note that we have to rebuild the RHS constant here to ensure we
24510             // don't rely on particular values of undef lanes.
24511             return DAG.getNode(
24512                 X86ISD::SUBUS, DL, VT, OpLHS,
24513                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24514         }
24515     }
24516   }
24517
24518   // Simplify vector selection if condition value type matches vselect
24519   // operand type
24520   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24521     assert(Cond.getValueType().isVector() &&
24522            "vector select expects a vector selector!");
24523
24524     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24525     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24526
24527     // Try invert the condition if true value is not all 1s and false value
24528     // is not all 0s.
24529     if (!TValIsAllOnes && !FValIsAllZeros &&
24530         // Check if the selector will be produced by CMPP*/PCMP*
24531         Cond.getOpcode() == ISD::SETCC &&
24532         // Check if SETCC has already been promoted
24533         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24534             CondVT) {
24535       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24536       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24537
24538       if (TValIsAllZeros || FValIsAllOnes) {
24539         SDValue CC = Cond.getOperand(2);
24540         ISD::CondCode NewCC =
24541           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24542                                Cond.getOperand(0).getValueType().isInteger());
24543         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24544         std::swap(LHS, RHS);
24545         TValIsAllOnes = FValIsAllOnes;
24546         FValIsAllZeros = TValIsAllZeros;
24547       }
24548     }
24549
24550     if (TValIsAllOnes || FValIsAllZeros) {
24551       SDValue Ret;
24552
24553       if (TValIsAllOnes && FValIsAllZeros)
24554         Ret = Cond;
24555       else if (TValIsAllOnes)
24556         Ret =
24557             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24558       else if (FValIsAllZeros)
24559         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24560                           DAG.getBitcast(CondVT, LHS));
24561
24562       return DAG.getBitcast(VT, Ret);
24563     }
24564   }
24565
24566   // We should generate an X86ISD::BLENDI from a vselect if its argument
24567   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24568   // constants. This specific pattern gets generated when we split a
24569   // selector for a 512 bit vector in a machine without AVX512 (but with
24570   // 256-bit vectors), during legalization:
24571   //
24572   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24573   //
24574   // Iff we find this pattern and the build_vectors are built from
24575   // constants, we translate the vselect into a shuffle_vector that we
24576   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24577   if ((N->getOpcode() == ISD::VSELECT ||
24578        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24579       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24580     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24581     if (Shuffle.getNode())
24582       return Shuffle;
24583   }
24584
24585   // If this is a *dynamic* select (non-constant condition) and we can match
24586   // this node with one of the variable blend instructions, restructure the
24587   // condition so that the blends can use the high bit of each element and use
24588   // SimplifyDemandedBits to simplify the condition operand.
24589   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24590       !DCI.isBeforeLegalize() &&
24591       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24592     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24593
24594     // Don't optimize vector selects that map to mask-registers.
24595     if (BitWidth == 1)
24596       return SDValue();
24597
24598     // We can only handle the cases where VSELECT is directly legal on the
24599     // subtarget. We custom lower VSELECT nodes with constant conditions and
24600     // this makes it hard to see whether a dynamic VSELECT will correctly
24601     // lower, so we both check the operation's status and explicitly handle the
24602     // cases where a *dynamic* blend will fail even though a constant-condition
24603     // blend could be custom lowered.
24604     // FIXME: We should find a better way to handle this class of problems.
24605     // Potentially, we should combine constant-condition vselect nodes
24606     // pre-legalization into shuffles and not mark as many types as custom
24607     // lowered.
24608     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24609       return SDValue();
24610     // FIXME: We don't support i16-element blends currently. We could and
24611     // should support them by making *all* the bits in the condition be set
24612     // rather than just the high bit and using an i8-element blend.
24613     if (VT.getVectorElementType() == MVT::i16)
24614       return SDValue();
24615     // Dynamic blending was only available from SSE4.1 onward.
24616     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24617       return SDValue();
24618     // Byte blends are only available in AVX2
24619     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24620       return SDValue();
24621
24622     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24623     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24624
24625     APInt KnownZero, KnownOne;
24626     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24627                                           DCI.isBeforeLegalizeOps());
24628     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24629         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24630                                  TLO)) {
24631       // If we changed the computation somewhere in the DAG, this change
24632       // will affect all users of Cond.
24633       // Make sure it is fine and update all the nodes so that we do not
24634       // use the generic VSELECT anymore. Otherwise, we may perform
24635       // wrong optimizations as we messed up with the actual expectation
24636       // for the vector boolean values.
24637       if (Cond != TLO.Old) {
24638         // Check all uses of that condition operand to check whether it will be
24639         // consumed by non-BLEND instructions, which may depend on all bits are
24640         // set properly.
24641         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24642              I != E; ++I)
24643           if (I->getOpcode() != ISD::VSELECT)
24644             // TODO: Add other opcodes eventually lowered into BLEND.
24645             return SDValue();
24646
24647         // Update all the users of the condition, before committing the change,
24648         // so that the VSELECT optimizations that expect the correct vector
24649         // boolean value will not be triggered.
24650         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24651              I != E; ++I)
24652           DAG.ReplaceAllUsesOfValueWith(
24653               SDValue(*I, 0),
24654               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24655                           Cond, I->getOperand(1), I->getOperand(2)));
24656         DCI.CommitTargetLoweringOpt(TLO);
24657         return SDValue();
24658       }
24659       // At this point, only Cond is changed. Change the condition
24660       // just for N to keep the opportunity to optimize all other
24661       // users their own way.
24662       DAG.ReplaceAllUsesOfValueWith(
24663           SDValue(N, 0),
24664           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24665                       TLO.New, N->getOperand(1), N->getOperand(2)));
24666       return SDValue();
24667     }
24668   }
24669
24670   return SDValue();
24671 }
24672
24673 // Check whether a boolean test is testing a boolean value generated by
24674 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24675 // code.
24676 //
24677 // Simplify the following patterns:
24678 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24679 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24680 // to (Op EFLAGS Cond)
24681 //
24682 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24683 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24684 // to (Op EFLAGS !Cond)
24685 //
24686 // where Op could be BRCOND or CMOV.
24687 //
24688 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24689   // Quit if not CMP and SUB with its value result used.
24690   if (Cmp.getOpcode() != X86ISD::CMP &&
24691       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24692       return SDValue();
24693
24694   // Quit if not used as a boolean value.
24695   if (CC != X86::COND_E && CC != X86::COND_NE)
24696     return SDValue();
24697
24698   // Check CMP operands. One of them should be 0 or 1 and the other should be
24699   // an SetCC or extended from it.
24700   SDValue Op1 = Cmp.getOperand(0);
24701   SDValue Op2 = Cmp.getOperand(1);
24702
24703   SDValue SetCC;
24704   const ConstantSDNode* C = nullptr;
24705   bool needOppositeCond = (CC == X86::COND_E);
24706   bool checkAgainstTrue = false; // Is it a comparison against 1?
24707
24708   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24709     SetCC = Op2;
24710   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24711     SetCC = Op1;
24712   else // Quit if all operands are not constants.
24713     return SDValue();
24714
24715   if (C->getZExtValue() == 1) {
24716     needOppositeCond = !needOppositeCond;
24717     checkAgainstTrue = true;
24718   } else if (C->getZExtValue() != 0)
24719     // Quit if the constant is neither 0 or 1.
24720     return SDValue();
24721
24722   bool truncatedToBoolWithAnd = false;
24723   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24724   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24725          SetCC.getOpcode() == ISD::TRUNCATE ||
24726          SetCC.getOpcode() == ISD::AND) {
24727     if (SetCC.getOpcode() == ISD::AND) {
24728       int OpIdx = -1;
24729       if (isOneConstant(SetCC.getOperand(0)))
24730         OpIdx = 1;
24731       if (isOneConstant(SetCC.getOperand(1)))
24732         OpIdx = 0;
24733       if (OpIdx == -1)
24734         break;
24735       SetCC = SetCC.getOperand(OpIdx);
24736       truncatedToBoolWithAnd = true;
24737     } else
24738       SetCC = SetCC.getOperand(0);
24739   }
24740
24741   switch (SetCC.getOpcode()) {
24742   case X86ISD::SETCC_CARRY:
24743     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24744     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24745     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24746     // truncated to i1 using 'and'.
24747     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24748       break;
24749     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24750            "Invalid use of SETCC_CARRY!");
24751     // FALL THROUGH
24752   case X86ISD::SETCC:
24753     // Set the condition code or opposite one if necessary.
24754     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24755     if (needOppositeCond)
24756       CC = X86::GetOppositeBranchCondition(CC);
24757     return SetCC.getOperand(1);
24758   case X86ISD::CMOV: {
24759     // Check whether false/true value has canonical one, i.e. 0 or 1.
24760     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24761     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24762     // Quit if true value is not a constant.
24763     if (!TVal)
24764       return SDValue();
24765     // Quit if false value is not a constant.
24766     if (!FVal) {
24767       SDValue Op = SetCC.getOperand(0);
24768       // Skip 'zext' or 'trunc' node.
24769       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24770           Op.getOpcode() == ISD::TRUNCATE)
24771         Op = Op.getOperand(0);
24772       // A special case for rdrand/rdseed, where 0 is set if false cond is
24773       // found.
24774       if ((Op.getOpcode() != X86ISD::RDRAND &&
24775            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24776         return SDValue();
24777     }
24778     // Quit if false value is not the constant 0 or 1.
24779     bool FValIsFalse = true;
24780     if (FVal && FVal->getZExtValue() != 0) {
24781       if (FVal->getZExtValue() != 1)
24782         return SDValue();
24783       // If FVal is 1, opposite cond is needed.
24784       needOppositeCond = !needOppositeCond;
24785       FValIsFalse = false;
24786     }
24787     // Quit if TVal is not the constant opposite of FVal.
24788     if (FValIsFalse && TVal->getZExtValue() != 1)
24789       return SDValue();
24790     if (!FValIsFalse && TVal->getZExtValue() != 0)
24791       return SDValue();
24792     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24793     if (needOppositeCond)
24794       CC = X86::GetOppositeBranchCondition(CC);
24795     return SetCC.getOperand(3);
24796   }
24797   }
24798
24799   return SDValue();
24800 }
24801
24802 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24803 /// Match:
24804 ///   (X86or (X86setcc) (X86setcc))
24805 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24806 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24807                                            X86::CondCode &CC1, SDValue &Flags,
24808                                            bool &isAnd) {
24809   if (Cond->getOpcode() == X86ISD::CMP) {
24810     if (!isNullConstant(Cond->getOperand(1)))
24811       return false;
24812
24813     Cond = Cond->getOperand(0);
24814   }
24815
24816   isAnd = false;
24817
24818   SDValue SetCC0, SetCC1;
24819   switch (Cond->getOpcode()) {
24820   default: return false;
24821   case ISD::AND:
24822   case X86ISD::AND:
24823     isAnd = true;
24824     // fallthru
24825   case ISD::OR:
24826   case X86ISD::OR:
24827     SetCC0 = Cond->getOperand(0);
24828     SetCC1 = Cond->getOperand(1);
24829     break;
24830   };
24831
24832   // Make sure we have SETCC nodes, using the same flags value.
24833   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24834       SetCC1.getOpcode() != X86ISD::SETCC ||
24835       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24836     return false;
24837
24838   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24839   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24840   Flags = SetCC0->getOperand(1);
24841   return true;
24842 }
24843
24844 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24845 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24846                                   TargetLowering::DAGCombinerInfo &DCI,
24847                                   const X86Subtarget *Subtarget) {
24848   SDLoc DL(N);
24849
24850   // If the flag operand isn't dead, don't touch this CMOV.
24851   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24852     return SDValue();
24853
24854   SDValue FalseOp = N->getOperand(0);
24855   SDValue TrueOp = N->getOperand(1);
24856   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24857   SDValue Cond = N->getOperand(3);
24858
24859   if (CC == X86::COND_E || CC == X86::COND_NE) {
24860     switch (Cond.getOpcode()) {
24861     default: break;
24862     case X86ISD::BSR:
24863     case X86ISD::BSF:
24864       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24865       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24866         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24867     }
24868   }
24869
24870   SDValue Flags;
24871
24872   Flags = checkBoolTestSetCCCombine(Cond, CC);
24873   if (Flags.getNode() &&
24874       // Extra check as FCMOV only supports a subset of X86 cond.
24875       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24876     SDValue Ops[] = { FalseOp, TrueOp,
24877                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24878     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24879   }
24880
24881   // If this is a select between two integer constants, try to do some
24882   // optimizations.  Note that the operands are ordered the opposite of SELECT
24883   // operands.
24884   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24885     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24886       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24887       // larger than FalseC (the false value).
24888       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24889         CC = X86::GetOppositeBranchCondition(CC);
24890         std::swap(TrueC, FalseC);
24891         std::swap(TrueOp, FalseOp);
24892       }
24893
24894       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24895       // This is efficient for any integer data type (including i8/i16) and
24896       // shift amount.
24897       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24898         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24899                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24900
24901         // Zero extend the condition if needed.
24902         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24903
24904         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24905         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24906                            DAG.getConstant(ShAmt, DL, MVT::i8));
24907         if (N->getNumValues() == 2)  // Dead flag value?
24908           return DCI.CombineTo(N, Cond, SDValue());
24909         return Cond;
24910       }
24911
24912       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24913       // for any integer data type, including i8/i16.
24914       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24915         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24916                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24917
24918         // Zero extend the condition if needed.
24919         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24920                            FalseC->getValueType(0), Cond);
24921         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24922                            SDValue(FalseC, 0));
24923
24924         if (N->getNumValues() == 2)  // Dead flag value?
24925           return DCI.CombineTo(N, Cond, SDValue());
24926         return Cond;
24927       }
24928
24929       // Optimize cases that will turn into an LEA instruction.  This requires
24930       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24931       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24932         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24933         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24934
24935         bool isFastMultiplier = false;
24936         if (Diff < 10) {
24937           switch ((unsigned char)Diff) {
24938           default: break;
24939           case 1:  // result = add base, cond
24940           case 2:  // result = lea base(    , cond*2)
24941           case 3:  // result = lea base(cond, cond*2)
24942           case 4:  // result = lea base(    , cond*4)
24943           case 5:  // result = lea base(cond, cond*4)
24944           case 8:  // result = lea base(    , cond*8)
24945           case 9:  // result = lea base(cond, cond*8)
24946             isFastMultiplier = true;
24947             break;
24948           }
24949         }
24950
24951         if (isFastMultiplier) {
24952           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24953           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24954                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24955           // Zero extend the condition if needed.
24956           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24957                              Cond);
24958           // Scale the condition by the difference.
24959           if (Diff != 1)
24960             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24961                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24962
24963           // Add the base if non-zero.
24964           if (FalseC->getAPIntValue() != 0)
24965             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24966                                SDValue(FalseC, 0));
24967           if (N->getNumValues() == 2)  // Dead flag value?
24968             return DCI.CombineTo(N, Cond, SDValue());
24969           return Cond;
24970         }
24971       }
24972     }
24973   }
24974
24975   // Handle these cases:
24976   //   (select (x != c), e, c) -> select (x != c), e, x),
24977   //   (select (x == c), c, e) -> select (x == c), x, e)
24978   // where the c is an integer constant, and the "select" is the combination
24979   // of CMOV and CMP.
24980   //
24981   // The rationale for this change is that the conditional-move from a constant
24982   // needs two instructions, however, conditional-move from a register needs
24983   // only one instruction.
24984   //
24985   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24986   //  some instruction-combining opportunities. This opt needs to be
24987   //  postponed as late as possible.
24988   //
24989   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24990     // the DCI.xxxx conditions are provided to postpone the optimization as
24991     // late as possible.
24992
24993     ConstantSDNode *CmpAgainst = nullptr;
24994     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24995         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24996         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24997
24998       if (CC == X86::COND_NE &&
24999           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25000         CC = X86::GetOppositeBranchCondition(CC);
25001         std::swap(TrueOp, FalseOp);
25002       }
25003
25004       if (CC == X86::COND_E &&
25005           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25006         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25007                           DAG.getConstant(CC, DL, MVT::i8), Cond };
25008         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25009       }
25010     }
25011   }
25012
25013   // Fold and/or of setcc's to double CMOV:
25014   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25015   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25016   //
25017   // This combine lets us generate:
25018   //   cmovcc1 (jcc1 if we don't have CMOV)
25019   //   cmovcc2 (same)
25020   // instead of:
25021   //   setcc1
25022   //   setcc2
25023   //   and/or
25024   //   cmovne (jne if we don't have CMOV)
25025   // When we can't use the CMOV instruction, it might increase branch
25026   // mispredicts.
25027   // When we can use CMOV, or when there is no mispredict, this improves
25028   // throughput and reduces register pressure.
25029   //
25030   if (CC == X86::COND_NE) {
25031     SDValue Flags;
25032     X86::CondCode CC0, CC1;
25033     bool isAndSetCC;
25034     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25035       if (isAndSetCC) {
25036         std::swap(FalseOp, TrueOp);
25037         CC0 = X86::GetOppositeBranchCondition(CC0);
25038         CC1 = X86::GetOppositeBranchCondition(CC1);
25039       }
25040
25041       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25042         Flags};
25043       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25044       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25045       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25046       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25047       return CMOV;
25048     }
25049   }
25050
25051   return SDValue();
25052 }
25053
25054 /// PerformMulCombine - Optimize a single multiply with constant into two
25055 /// in order to implement it with two cheaper instructions, e.g.
25056 /// LEA + SHL, LEA + LEA.
25057 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25058                                  TargetLowering::DAGCombinerInfo &DCI) {
25059   // An imul is usually smaller than the alternative sequence.
25060   if (DAG.getMachineFunction().getFunction()->optForMinSize())
25061     return SDValue();
25062
25063   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25064     return SDValue();
25065
25066   EVT VT = N->getValueType(0);
25067   if (VT != MVT::i64 && VT != MVT::i32)
25068     return SDValue();
25069
25070   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25071   if (!C)
25072     return SDValue();
25073   uint64_t MulAmt = C->getZExtValue();
25074   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25075     return SDValue();
25076
25077   uint64_t MulAmt1 = 0;
25078   uint64_t MulAmt2 = 0;
25079   if ((MulAmt % 9) == 0) {
25080     MulAmt1 = 9;
25081     MulAmt2 = MulAmt / 9;
25082   } else if ((MulAmt % 5) == 0) {
25083     MulAmt1 = 5;
25084     MulAmt2 = MulAmt / 5;
25085   } else if ((MulAmt % 3) == 0) {
25086     MulAmt1 = 3;
25087     MulAmt2 = MulAmt / 3;
25088   }
25089
25090   SDLoc DL(N);
25091   SDValue NewMul;
25092   if (MulAmt2 &&
25093       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25094
25095     if (isPowerOf2_64(MulAmt2) &&
25096         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25097       // If second multiplifer is pow2, issue it first. We want the multiply by
25098       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25099       // is an add.
25100       std::swap(MulAmt1, MulAmt2);
25101
25102     if (isPowerOf2_64(MulAmt1))
25103       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25104                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25105     else
25106       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25107                            DAG.getConstant(MulAmt1, DL, VT));
25108
25109     if (isPowerOf2_64(MulAmt2))
25110       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25111                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25112     else
25113       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25114                            DAG.getConstant(MulAmt2, DL, VT));
25115   }
25116
25117   if (!NewMul) {
25118     assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25119            && "Both cases that could cause potential overflows should have "
25120               "already been handled.");
25121     if (isPowerOf2_64(MulAmt - 1))
25122       // (mul x, 2^N + 1) => (add (shl x, N), x)
25123       NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25124                                 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25125                                 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25126                                 MVT::i8)));
25127
25128     else if (isPowerOf2_64(MulAmt + 1))
25129       // (mul x, 2^N - 1) => (sub (shl x, N), x)
25130       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25131                                 N->getOperand(0),
25132                                 DAG.getConstant(Log2_64(MulAmt + 1),
25133                                 DL, MVT::i8)), N->getOperand(0));
25134   }
25135
25136   if (NewMul)
25137     // Do not add new nodes to DAG combiner worklist.
25138     DCI.CombineTo(N, NewMul, false);
25139
25140   return SDValue();
25141 }
25142
25143 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25144   SDValue N0 = N->getOperand(0);
25145   SDValue N1 = N->getOperand(1);
25146   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25147   EVT VT = N0.getValueType();
25148
25149   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25150   // since the result of setcc_c is all zero's or all ones.
25151   if (VT.isInteger() && !VT.isVector() &&
25152       N1C && N0.getOpcode() == ISD::AND &&
25153       N0.getOperand(1).getOpcode() == ISD::Constant) {
25154     SDValue N00 = N0.getOperand(0);
25155     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25156     APInt ShAmt = N1C->getAPIntValue();
25157     Mask = Mask.shl(ShAmt);
25158     bool MaskOK = false;
25159     // We can handle cases concerning bit-widening nodes containing setcc_c if
25160     // we carefully interrogate the mask to make sure we are semantics
25161     // preserving.
25162     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25163     // of the underlying setcc_c operation if the setcc_c was zero extended.
25164     // Consider the following example:
25165     //   zext(setcc_c)                 -> i32 0x0000FFFF
25166     //   c1                            -> i32 0x0000FFFF
25167     //   c2                            -> i32 0x00000001
25168     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25169     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
25170     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25171       MaskOK = true;
25172     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25173                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25174       MaskOK = true;
25175     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25176                 N00.getOpcode() == ISD::ANY_EXTEND) &&
25177                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25178       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25179     }
25180     if (MaskOK && Mask != 0) {
25181       SDLoc DL(N);
25182       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25183     }
25184   }
25185
25186   // Hardware support for vector shifts is sparse which makes us scalarize the
25187   // vector operations in many cases. Also, on sandybridge ADD is faster than
25188   // shl.
25189   // (shl V, 1) -> add V,V
25190   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25191     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25192       assert(N0.getValueType().isVector() && "Invalid vector shift type");
25193       // We shift all of the values by one. In many cases we do not have
25194       // hardware support for this operation. This is better expressed as an ADD
25195       // of two values.
25196       if (N1SplatC->getAPIntValue() == 1)
25197         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25198     }
25199
25200   return SDValue();
25201 }
25202
25203 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25204   SDValue N0 = N->getOperand(0);
25205   SDValue N1 = N->getOperand(1);
25206   EVT VT = N0.getValueType();
25207   unsigned Size = VT.getSizeInBits();
25208
25209   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25210   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25211   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25212   // depending on sign of (SarConst - [56,48,32,24,16])
25213
25214   // sexts in X86 are MOVs. The MOVs have the same code size
25215   // as above SHIFTs (only SHIFT on 1 has lower code size).
25216   // However the MOVs have 2 advantages to a SHIFT:
25217   // 1. MOVs can write to a register that differs from source
25218   // 2. MOVs accept memory operands
25219
25220   if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25221       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25222       N0.getOperand(1).getOpcode() != ISD::Constant)
25223     return SDValue();
25224
25225   SDValue N00 = N0.getOperand(0);
25226   SDValue N01 = N0.getOperand(1);
25227   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25228   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25229   EVT CVT = N1.getValueType();
25230
25231   if (SarConst.isNegative())
25232     return SDValue();
25233
25234   for (MVT SVT : MVT::integer_valuetypes()) {
25235     unsigned ShiftSize = SVT.getSizeInBits();
25236     // skipping types without corresponding sext/zext and
25237     // ShlConst that is not one of [56,48,32,24,16]
25238     if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25239       continue;
25240     SDLoc DL(N);
25241     SDValue NN =
25242         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25243     SarConst = SarConst - (Size - ShiftSize);
25244     if (SarConst == 0)
25245       return NN;
25246     else if (SarConst.isNegative())
25247       return DAG.getNode(ISD::SHL, DL, VT, NN,
25248                          DAG.getConstant(-SarConst, DL, CVT));
25249     else
25250       return DAG.getNode(ISD::SRA, DL, VT, NN,
25251                          DAG.getConstant(SarConst, DL, CVT));
25252   }
25253   return SDValue();
25254 }
25255
25256 /// \brief Returns a vector of 0s if the node in input is a vector logical
25257 /// shift by a constant amount which is known to be bigger than or equal
25258 /// to the vector element size in bits.
25259 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25260                                       const X86Subtarget *Subtarget) {
25261   EVT VT = N->getValueType(0);
25262
25263   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25264       (!Subtarget->hasInt256() ||
25265        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25266     return SDValue();
25267
25268   SDValue Amt = N->getOperand(1);
25269   SDLoc DL(N);
25270   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25271     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25272       APInt ShiftAmt = AmtSplat->getAPIntValue();
25273       unsigned MaxAmount =
25274         VT.getSimpleVT().getVectorElementType().getSizeInBits();
25275
25276       // SSE2/AVX2 logical shifts always return a vector of 0s
25277       // if the shift amount is bigger than or equal to
25278       // the element size. The constant shift amount will be
25279       // encoded as a 8-bit immediate.
25280       if (ShiftAmt.trunc(8).uge(MaxAmount))
25281         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25282     }
25283
25284   return SDValue();
25285 }
25286
25287 /// PerformShiftCombine - Combine shifts.
25288 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25289                                    TargetLowering::DAGCombinerInfo &DCI,
25290                                    const X86Subtarget *Subtarget) {
25291   if (N->getOpcode() == ISD::SHL)
25292     if (SDValue V = PerformSHLCombine(N, DAG))
25293       return V;
25294
25295   if (N->getOpcode() == ISD::SRA)
25296     if (SDValue V = PerformSRACombine(N, DAG))
25297       return V;
25298
25299   // Try to fold this logical shift into a zero vector.
25300   if (N->getOpcode() != ISD::SRA)
25301     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25302       return V;
25303
25304   return SDValue();
25305 }
25306
25307 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
25308 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25309 // and friends.  Likewise for OR -> CMPNEQSS.
25310 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25311                             TargetLowering::DAGCombinerInfo &DCI,
25312                             const X86Subtarget *Subtarget) {
25313   unsigned opcode;
25314
25315   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25316   // we're requiring SSE2 for both.
25317   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25318     SDValue N0 = N->getOperand(0);
25319     SDValue N1 = N->getOperand(1);
25320     SDValue CMP0 = N0->getOperand(1);
25321     SDValue CMP1 = N1->getOperand(1);
25322     SDLoc DL(N);
25323
25324     // The SETCCs should both refer to the same CMP.
25325     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25326       return SDValue();
25327
25328     SDValue CMP00 = CMP0->getOperand(0);
25329     SDValue CMP01 = CMP0->getOperand(1);
25330     EVT     VT    = CMP00.getValueType();
25331
25332     if (VT == MVT::f32 || VT == MVT::f64) {
25333       bool ExpectingFlags = false;
25334       // Check for any users that want flags:
25335       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25336            !ExpectingFlags && UI != UE; ++UI)
25337         switch (UI->getOpcode()) {
25338         default:
25339         case ISD::BR_CC:
25340         case ISD::BRCOND:
25341         case ISD::SELECT:
25342           ExpectingFlags = true;
25343           break;
25344         case ISD::CopyToReg:
25345         case ISD::SIGN_EXTEND:
25346         case ISD::ZERO_EXTEND:
25347         case ISD::ANY_EXTEND:
25348           break;
25349         }
25350
25351       if (!ExpectingFlags) {
25352         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25353         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25354
25355         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25356           X86::CondCode tmp = cc0;
25357           cc0 = cc1;
25358           cc1 = tmp;
25359         }
25360
25361         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
25362             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25363           // FIXME: need symbolic constants for these magic numbers.
25364           // See X86ATTInstPrinter.cpp:printSSECC().
25365           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25366           if (Subtarget->hasAVX512()) {
25367             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25368                                          CMP01,
25369                                          DAG.getConstant(x86cc, DL, MVT::i8));
25370             if (N->getValueType(0) != MVT::i1)
25371               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25372                                  FSetCC);
25373             return FSetCC;
25374           }
25375           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25376                                               CMP00.getValueType(), CMP00, CMP01,
25377                                               DAG.getConstant(x86cc, DL,
25378                                                               MVT::i8));
25379
25380           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25381           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25382
25383           if (is64BitFP && !Subtarget->is64Bit()) {
25384             // On a 32-bit target, we cannot bitcast the 64-bit float to a
25385             // 64-bit integer, since that's not a legal type. Since
25386             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25387             // bits, but can do this little dance to extract the lowest 32 bits
25388             // and work with those going forward.
25389             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25390                                            OnesOrZeroesF);
25391             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25392             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25393                                         Vector32, DAG.getIntPtrConstant(0, DL));
25394             IntVT = MVT::i32;
25395           }
25396
25397           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25398           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25399                                       DAG.getConstant(1, DL, IntVT));
25400           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25401                                               ANDed);
25402           return OneBitOfTruth;
25403         }
25404       }
25405     }
25406   }
25407   return SDValue();
25408 }
25409
25410 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25411 /// so it can be folded inside ANDNP.
25412 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25413   EVT VT = N->getValueType(0);
25414
25415   // Match direct AllOnes for 128 and 256-bit vectors
25416   if (ISD::isBuildVectorAllOnes(N))
25417     return true;
25418
25419   // Look through a bit convert.
25420   if (N->getOpcode() == ISD::BITCAST)
25421     N = N->getOperand(0).getNode();
25422
25423   // Sometimes the operand may come from a insert_subvector building a 256-bit
25424   // allones vector
25425   if (VT.is256BitVector() &&
25426       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25427     SDValue V1 = N->getOperand(0);
25428     SDValue V2 = N->getOperand(1);
25429
25430     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25431         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25432         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25433         ISD::isBuildVectorAllOnes(V2.getNode()))
25434       return true;
25435   }
25436
25437   return false;
25438 }
25439
25440 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25441 // register. In most cases we actually compare or select YMM-sized registers
25442 // and mixing the two types creates horrible code. This method optimizes
25443 // some of the transition sequences.
25444 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25445                                  TargetLowering::DAGCombinerInfo &DCI,
25446                                  const X86Subtarget *Subtarget) {
25447   EVT VT = N->getValueType(0);
25448   if (!VT.is256BitVector())
25449     return SDValue();
25450
25451   assert((N->getOpcode() == ISD::ANY_EXTEND ||
25452           N->getOpcode() == ISD::ZERO_EXTEND ||
25453           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25454
25455   SDValue Narrow = N->getOperand(0);
25456   EVT NarrowVT = Narrow->getValueType(0);
25457   if (!NarrowVT.is128BitVector())
25458     return SDValue();
25459
25460   if (Narrow->getOpcode() != ISD::XOR &&
25461       Narrow->getOpcode() != ISD::AND &&
25462       Narrow->getOpcode() != ISD::OR)
25463     return SDValue();
25464
25465   SDValue N0  = Narrow->getOperand(0);
25466   SDValue N1  = Narrow->getOperand(1);
25467   SDLoc DL(Narrow);
25468
25469   // The Left side has to be a trunc.
25470   if (N0.getOpcode() != ISD::TRUNCATE)
25471     return SDValue();
25472
25473   // The type of the truncated inputs.
25474   EVT WideVT = N0->getOperand(0)->getValueType(0);
25475   if (WideVT != VT)
25476     return SDValue();
25477
25478   // The right side has to be a 'trunc' or a constant vector.
25479   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25480   ConstantSDNode *RHSConstSplat = nullptr;
25481   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25482     RHSConstSplat = RHSBV->getConstantSplatNode();
25483   if (!RHSTrunc && !RHSConstSplat)
25484     return SDValue();
25485
25486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25487
25488   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25489     return SDValue();
25490
25491   // Set N0 and N1 to hold the inputs to the new wide operation.
25492   N0 = N0->getOperand(0);
25493   if (RHSConstSplat) {
25494     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25495                      SDValue(RHSConstSplat, 0));
25496     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25497     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25498   } else if (RHSTrunc) {
25499     N1 = N1->getOperand(0);
25500   }
25501
25502   // Generate the wide operation.
25503   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25504   unsigned Opcode = N->getOpcode();
25505   switch (Opcode) {
25506   case ISD::ANY_EXTEND:
25507     return Op;
25508   case ISD::ZERO_EXTEND: {
25509     unsigned InBits = NarrowVT.getScalarSizeInBits();
25510     APInt Mask = APInt::getAllOnesValue(InBits);
25511     Mask = Mask.zext(VT.getScalarSizeInBits());
25512     return DAG.getNode(ISD::AND, DL, VT,
25513                        Op, DAG.getConstant(Mask, DL, VT));
25514   }
25515   case ISD::SIGN_EXTEND:
25516     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25517                        Op, DAG.getValueType(NarrowVT));
25518   default:
25519     llvm_unreachable("Unexpected opcode");
25520   }
25521 }
25522
25523 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25524                                  TargetLowering::DAGCombinerInfo &DCI,
25525                                  const X86Subtarget *Subtarget) {
25526   SDValue N0 = N->getOperand(0);
25527   SDValue N1 = N->getOperand(1);
25528   SDLoc DL(N);
25529
25530   // A vector zext_in_reg may be represented as a shuffle,
25531   // feeding into a bitcast (this represents anyext) feeding into
25532   // an and with a mask.
25533   // We'd like to try to combine that into a shuffle with zero
25534   // plus a bitcast, removing the and.
25535   if (N0.getOpcode() != ISD::BITCAST ||
25536       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25537     return SDValue();
25538
25539   // The other side of the AND should be a splat of 2^C, where C
25540   // is the number of bits in the source type.
25541   if (N1.getOpcode() == ISD::BITCAST)
25542     N1 = N1.getOperand(0);
25543   if (N1.getOpcode() != ISD::BUILD_VECTOR)
25544     return SDValue();
25545   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25546
25547   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25548   EVT SrcType = Shuffle->getValueType(0);
25549
25550   // We expect a single-source shuffle
25551   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25552     return SDValue();
25553
25554   unsigned SrcSize = SrcType.getScalarSizeInBits();
25555
25556   APInt SplatValue, SplatUndef;
25557   unsigned SplatBitSize;
25558   bool HasAnyUndefs;
25559   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25560                                 SplatBitSize, HasAnyUndefs))
25561     return SDValue();
25562
25563   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25564   // Make sure the splat matches the mask we expect
25565   if (SplatBitSize > ResSize ||
25566       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25567     return SDValue();
25568
25569   // Make sure the input and output size make sense
25570   if (SrcSize >= ResSize || ResSize % SrcSize)
25571     return SDValue();
25572
25573   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25574   // The number of u's between each two values depends on the ratio between
25575   // the source and dest type.
25576   unsigned ZextRatio = ResSize / SrcSize;
25577   bool IsZext = true;
25578   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25579     if (i % ZextRatio) {
25580       if (Shuffle->getMaskElt(i) > 0) {
25581         // Expected undef
25582         IsZext = false;
25583         break;
25584       }
25585     } else {
25586       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25587         // Expected element number
25588         IsZext = false;
25589         break;
25590       }
25591     }
25592   }
25593
25594   if (!IsZext)
25595     return SDValue();
25596
25597   // Ok, perform the transformation - replace the shuffle with
25598   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25599   // (instead of undef) where the k elements come from the zero vector.
25600   SmallVector<int, 8> Mask;
25601   unsigned NumElems = SrcType.getVectorNumElements();
25602   for (unsigned i = 0; i < NumElems; ++i)
25603     if (i % ZextRatio)
25604       Mask.push_back(NumElems);
25605     else
25606       Mask.push_back(i / ZextRatio);
25607
25608   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25609     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25610   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25611 }
25612
25613 /// If both input operands of a logic op are being cast from floating point
25614 /// types, try to convert this into a floating point logic node to avoid
25615 /// unnecessary moves from SSE to integer registers.
25616 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25617                                         const X86Subtarget *Subtarget) {
25618   unsigned FPOpcode = ISD::DELETED_NODE;
25619   if (N->getOpcode() == ISD::AND)
25620     FPOpcode = X86ISD::FAND;
25621   else if (N->getOpcode() == ISD::OR)
25622     FPOpcode = X86ISD::FOR;
25623   else if (N->getOpcode() == ISD::XOR)
25624     FPOpcode = X86ISD::FXOR;
25625
25626   assert(FPOpcode != ISD::DELETED_NODE &&
25627          "Unexpected input node for FP logic conversion");
25628
25629   EVT VT = N->getValueType(0);
25630   SDValue N0 = N->getOperand(0);
25631   SDValue N1 = N->getOperand(1);
25632   SDLoc DL(N);
25633   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25634       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25635        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25636     SDValue N00 = N0.getOperand(0);
25637     SDValue N10 = N1.getOperand(0);
25638     EVT N00Type = N00.getValueType();
25639     EVT N10Type = N10.getValueType();
25640     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25641       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25642       return DAG.getBitcast(VT, FPLogic);
25643     }
25644   }
25645   return SDValue();
25646 }
25647
25648 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25649                                  TargetLowering::DAGCombinerInfo &DCI,
25650                                  const X86Subtarget *Subtarget) {
25651   if (DCI.isBeforeLegalizeOps())
25652     return SDValue();
25653
25654   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25655     return Zext;
25656
25657   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25658     return R;
25659
25660   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25661     return FPLogic;
25662
25663   EVT VT = N->getValueType(0);
25664   SDValue N0 = N->getOperand(0);
25665   SDValue N1 = N->getOperand(1);
25666   SDLoc DL(N);
25667
25668   // Create BEXTR instructions
25669   // BEXTR is ((X >> imm) & (2**size-1))
25670   if (VT == MVT::i32 || VT == MVT::i64) {
25671     // Check for BEXTR.
25672     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25673         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25674       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25675       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25676       if (MaskNode && ShiftNode) {
25677         uint64_t Mask = MaskNode->getZExtValue();
25678         uint64_t Shift = ShiftNode->getZExtValue();
25679         if (isMask_64(Mask)) {
25680           uint64_t MaskSize = countPopulation(Mask);
25681           if (Shift + MaskSize <= VT.getSizeInBits())
25682             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25683                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25684                                                VT));
25685         }
25686       }
25687     } // BEXTR
25688
25689     return SDValue();
25690   }
25691
25692   // Want to form ANDNP nodes:
25693   // 1) In the hopes of then easily combining them with OR and AND nodes
25694   //    to form PBLEND/PSIGN.
25695   // 2) To match ANDN packed intrinsics
25696   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25697     return SDValue();
25698
25699   // Check LHS for vnot
25700   if (N0.getOpcode() == ISD::XOR &&
25701       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25702       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25703     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25704
25705   // Check RHS for vnot
25706   if (N1.getOpcode() == ISD::XOR &&
25707       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25708       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25709     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25710
25711   return SDValue();
25712 }
25713
25714 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25715                                 TargetLowering::DAGCombinerInfo &DCI,
25716                                 const X86Subtarget *Subtarget) {
25717   if (DCI.isBeforeLegalizeOps())
25718     return SDValue();
25719
25720   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25721     return R;
25722
25723   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25724     return FPLogic;
25725
25726   SDValue N0 = N->getOperand(0);
25727   SDValue N1 = N->getOperand(1);
25728   EVT VT = N->getValueType(0);
25729
25730   // look for psign/blend
25731   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25732     if (!Subtarget->hasSSSE3() ||
25733         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25734       return SDValue();
25735
25736     // Canonicalize pandn to RHS
25737     if (N0.getOpcode() == X86ISD::ANDNP)
25738       std::swap(N0, N1);
25739     // or (and (m, y), (pandn m, x))
25740     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25741       SDValue Mask = N1.getOperand(0);
25742       SDValue X    = N1.getOperand(1);
25743       SDValue Y;
25744       if (N0.getOperand(0) == Mask)
25745         Y = N0.getOperand(1);
25746       if (N0.getOperand(1) == Mask)
25747         Y = N0.getOperand(0);
25748
25749       // Check to see if the mask appeared in both the AND and ANDNP and
25750       if (!Y.getNode())
25751         return SDValue();
25752
25753       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25754       // Look through mask bitcast.
25755       if (Mask.getOpcode() == ISD::BITCAST)
25756         Mask = Mask.getOperand(0);
25757       if (X.getOpcode() == ISD::BITCAST)
25758         X = X.getOperand(0);
25759       if (Y.getOpcode() == ISD::BITCAST)
25760         Y = Y.getOperand(0);
25761
25762       EVT MaskVT = Mask.getValueType();
25763
25764       // Validate that the Mask operand is a vector sra node.
25765       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25766       // there is no psrai.b
25767       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25768       unsigned SraAmt = ~0;
25769       if (Mask.getOpcode() == ISD::SRA) {
25770         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25771           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25772             SraAmt = AmtConst->getZExtValue();
25773       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25774         SDValue SraC = Mask.getOperand(1);
25775         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25776       }
25777       if ((SraAmt + 1) != EltBits)
25778         return SDValue();
25779
25780       SDLoc DL(N);
25781
25782       // Now we know we at least have a plendvb with the mask val.  See if
25783       // we can form a psignb/w/d.
25784       // psign = x.type == y.type == mask.type && y = sub(0, x);
25785       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25786           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25787           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25788         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25789                "Unsupported VT for PSIGN");
25790         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25791         return DAG.getBitcast(VT, Mask);
25792       }
25793       // PBLENDVB only available on SSE 4.1
25794       if (!Subtarget->hasSSE41())
25795         return SDValue();
25796
25797       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25798
25799       X = DAG.getBitcast(BlendVT, X);
25800       Y = DAG.getBitcast(BlendVT, Y);
25801       Mask = DAG.getBitcast(BlendVT, Mask);
25802       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25803       return DAG.getBitcast(VT, Mask);
25804     }
25805   }
25806
25807   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25808     return SDValue();
25809
25810   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25811   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25812
25813   // SHLD/SHRD instructions have lower register pressure, but on some
25814   // platforms they have higher latency than the equivalent
25815   // series of shifts/or that would otherwise be generated.
25816   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25817   // have higher latencies and we are not optimizing for size.
25818   if (!OptForSize && Subtarget->isSHLDSlow())
25819     return SDValue();
25820
25821   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25822     std::swap(N0, N1);
25823   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25824     return SDValue();
25825   if (!N0.hasOneUse() || !N1.hasOneUse())
25826     return SDValue();
25827
25828   SDValue ShAmt0 = N0.getOperand(1);
25829   if (ShAmt0.getValueType() != MVT::i8)
25830     return SDValue();
25831   SDValue ShAmt1 = N1.getOperand(1);
25832   if (ShAmt1.getValueType() != MVT::i8)
25833     return SDValue();
25834   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25835     ShAmt0 = ShAmt0.getOperand(0);
25836   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25837     ShAmt1 = ShAmt1.getOperand(0);
25838
25839   SDLoc DL(N);
25840   unsigned Opc = X86ISD::SHLD;
25841   SDValue Op0 = N0.getOperand(0);
25842   SDValue Op1 = N1.getOperand(0);
25843   if (ShAmt0.getOpcode() == ISD::SUB) {
25844     Opc = X86ISD::SHRD;
25845     std::swap(Op0, Op1);
25846     std::swap(ShAmt0, ShAmt1);
25847   }
25848
25849   unsigned Bits = VT.getSizeInBits();
25850   if (ShAmt1.getOpcode() == ISD::SUB) {
25851     SDValue Sum = ShAmt1.getOperand(0);
25852     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25853       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25854       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25855         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25856       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25857         return DAG.getNode(Opc, DL, VT,
25858                            Op0, Op1,
25859                            DAG.getNode(ISD::TRUNCATE, DL,
25860                                        MVT::i8, ShAmt0));
25861     }
25862   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25863     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25864     if (ShAmt0C &&
25865         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25866       return DAG.getNode(Opc, DL, VT,
25867                          N0.getOperand(0), N1.getOperand(0),
25868                          DAG.getNode(ISD::TRUNCATE, DL,
25869                                        MVT::i8, ShAmt0));
25870   }
25871
25872   return SDValue();
25873 }
25874
25875 // Generate NEG and CMOV for integer abs.
25876 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25877   EVT VT = N->getValueType(0);
25878
25879   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25880   // 8-bit integer abs to NEG and CMOV.
25881   if (VT.isInteger() && VT.getSizeInBits() == 8)
25882     return SDValue();
25883
25884   SDValue N0 = N->getOperand(0);
25885   SDValue N1 = N->getOperand(1);
25886   SDLoc DL(N);
25887
25888   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25889   // and change it to SUB and CMOV.
25890   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25891       N0.getOpcode() == ISD::ADD &&
25892       N0.getOperand(1) == N1 &&
25893       N1.getOpcode() == ISD::SRA &&
25894       N1.getOperand(0) == N0.getOperand(0))
25895     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25896       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25897         // Generate SUB & CMOV.
25898         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25899                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25900
25901         SDValue Ops[] = { N0.getOperand(0), Neg,
25902                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25903                           SDValue(Neg.getNode(), 1) };
25904         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25905       }
25906   return SDValue();
25907 }
25908
25909 // Try to turn tests against the signbit in the form of:
25910 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25911 // into:
25912 //   SETGT(X, -1)
25913 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25914   // This is only worth doing if the output type is i8.
25915   if (N->getValueType(0) != MVT::i8)
25916     return SDValue();
25917
25918   SDValue N0 = N->getOperand(0);
25919   SDValue N1 = N->getOperand(1);
25920
25921   // We should be performing an xor against a truncated shift.
25922   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25923     return SDValue();
25924
25925   // Make sure we are performing an xor against one.
25926   if (!isOneConstant(N1))
25927     return SDValue();
25928
25929   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25930   SDValue Shift = N0.getOperand(0);
25931   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25932     return SDValue();
25933
25934   // Make sure we are truncating from one of i16, i32 or i64.
25935   EVT ShiftTy = Shift.getValueType();
25936   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25937     return SDValue();
25938
25939   // Make sure the shift amount extracts the sign bit.
25940   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25941       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25942     return SDValue();
25943
25944   // Create a greater-than comparison against -1.
25945   // N.B. Using SETGE against 0 works but we want a canonical looking
25946   // comparison, using SETGT matches up with what TranslateX86CC.
25947   SDLoc DL(N);
25948   SDValue ShiftOp = Shift.getOperand(0);
25949   EVT ShiftOpTy = ShiftOp.getValueType();
25950   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25951                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25952   return Cond;
25953 }
25954
25955 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25956                                  TargetLowering::DAGCombinerInfo &DCI,
25957                                  const X86Subtarget *Subtarget) {
25958   if (DCI.isBeforeLegalizeOps())
25959     return SDValue();
25960
25961   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25962     return RV;
25963
25964   if (Subtarget->hasCMov())
25965     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25966       return RV;
25967
25968   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25969     return FPLogic;
25970
25971   return SDValue();
25972 }
25973
25974 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
25975 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
25976 /// X86ISD::AVG instruction.
25977 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
25978                                 const X86Subtarget *Subtarget, SDLoc DL) {
25979   if (!VT.isVector() || !VT.isSimple())
25980     return SDValue();
25981   EVT InVT = In.getValueType();
25982   unsigned NumElems = VT.getVectorNumElements();
25983
25984   EVT ScalarVT = VT.getVectorElementType();
25985   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
25986         isPowerOf2_32(NumElems)))
25987     return SDValue();
25988
25989   // InScalarVT is the intermediate type in AVG pattern and it should be greater
25990   // than the original input type (i8/i16).
25991   EVT InScalarVT = InVT.getVectorElementType();
25992   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
25993     return SDValue();
25994
25995   if (Subtarget->hasAVX512()) {
25996     if (VT.getSizeInBits() > 512)
25997       return SDValue();
25998   } else if (Subtarget->hasAVX2()) {
25999     if (VT.getSizeInBits() > 256)
26000       return SDValue();
26001   } else {
26002     if (VT.getSizeInBits() > 128)
26003       return SDValue();
26004   }
26005
26006   // Detect the following pattern:
26007   //
26008   //   %1 = zext <N x i8> %a to <N x i32>
26009   //   %2 = zext <N x i8> %b to <N x i32>
26010   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26011   //   %4 = add nuw nsw <N x i32> %3, %2
26012   //   %5 = lshr <N x i32> %N, <i32 1 x N>
26013   //   %6 = trunc <N x i32> %5 to <N x i8>
26014   //
26015   // In AVX512, the last instruction can also be a trunc store.
26016
26017   if (In.getOpcode() != ISD::SRL)
26018     return SDValue();
26019
26020   // A lambda checking the given SDValue is a constant vector and each element
26021   // is in the range [Min, Max].
26022   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26023     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26024     if (!BV || !BV->isConstant())
26025       return false;
26026     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26027       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26028       if (!C)
26029         return false;
26030       uint64_t Val = C->getZExtValue();
26031       if (Val < Min || Val > Max)
26032         return false;
26033     }
26034     return true;
26035   };
26036
26037   // Check if each element of the vector is left-shifted by one.
26038   auto LHS = In.getOperand(0);
26039   auto RHS = In.getOperand(1);
26040   if (!IsConstVectorInRange(RHS, 1, 1))
26041     return SDValue();
26042   if (LHS.getOpcode() != ISD::ADD)
26043     return SDValue();
26044
26045   // Detect a pattern of a + b + 1 where the order doesn't matter.
26046   SDValue Operands[3];
26047   Operands[0] = LHS.getOperand(0);
26048   Operands[1] = LHS.getOperand(1);
26049
26050   // Take care of the case when one of the operands is a constant vector whose
26051   // element is in the range [1, 256].
26052   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26053       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26054       Operands[0].getOperand(0).getValueType() == VT) {
26055     // The pattern is detected. Subtract one from the constant vector, then
26056     // demote it and emit X86ISD::AVG instruction.
26057     SDValue One = DAG.getConstant(1, DL, InScalarVT);
26058     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26059                                SmallVector<SDValue, 8>(NumElems, One));
26060     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26061     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26062     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26063                        Operands[1]);
26064   }
26065
26066   if (Operands[0].getOpcode() == ISD::ADD)
26067     std::swap(Operands[0], Operands[1]);
26068   else if (Operands[1].getOpcode() != ISD::ADD)
26069     return SDValue();
26070   Operands[2] = Operands[1].getOperand(0);
26071   Operands[1] = Operands[1].getOperand(1);
26072
26073   // Now we have three operands of two additions. Check that one of them is a
26074   // constant vector with ones, and the other two are promoted from i8/i16.
26075   for (int i = 0; i < 3; ++i) {
26076     if (!IsConstVectorInRange(Operands[i], 1, 1))
26077       continue;
26078     std::swap(Operands[i], Operands[2]);
26079
26080     // Check if Operands[0] and Operands[1] are results of type promotion.
26081     for (int j = 0; j < 2; ++j)
26082       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26083           Operands[j].getOperand(0).getValueType() != VT)
26084         return SDValue();
26085
26086     // The pattern is detected, emit X86ISD::AVG instruction.
26087     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26088                        Operands[1].getOperand(0));
26089   }
26090
26091   return SDValue();
26092 }
26093
26094 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26095 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26096                                   TargetLowering::DAGCombinerInfo &DCI,
26097                                   const X86Subtarget *Subtarget) {
26098   LoadSDNode *Ld = cast<LoadSDNode>(N);
26099   EVT RegVT = Ld->getValueType(0);
26100   EVT MemVT = Ld->getMemoryVT();
26101   SDLoc dl(Ld);
26102   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26103
26104   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26105   // into two 16-byte operations.
26106   ISD::LoadExtType Ext = Ld->getExtensionType();
26107   bool Fast;
26108   unsigned AddressSpace = Ld->getAddressSpace();
26109   unsigned Alignment = Ld->getAlignment();
26110   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26111       Ext == ISD::NON_EXTLOAD &&
26112       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26113                              AddressSpace, Alignment, &Fast) && !Fast) {
26114     unsigned NumElems = RegVT.getVectorNumElements();
26115     if (NumElems < 2)
26116       return SDValue();
26117
26118     SDValue Ptr = Ld->getBasePtr();
26119     SDValue Increment =
26120         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26121
26122     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26123                                   NumElems/2);
26124     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26125                                 Ld->getPointerInfo(), Ld->isVolatile(),
26126                                 Ld->isNonTemporal(), Ld->isInvariant(),
26127                                 Alignment);
26128     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26129     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26130                                 Ld->getPointerInfo(), Ld->isVolatile(),
26131                                 Ld->isNonTemporal(), Ld->isInvariant(),
26132                                 std::min(16U, Alignment));
26133     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26134                              Load1.getValue(1),
26135                              Load2.getValue(1));
26136
26137     SDValue NewVec = DAG.getUNDEF(RegVT);
26138     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26139     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26140     return DCI.CombineTo(N, NewVec, TF, true);
26141   }
26142
26143   return SDValue();
26144 }
26145
26146 /// PerformMLOADCombine - Resolve extending loads
26147 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26148                                    TargetLowering::DAGCombinerInfo &DCI,
26149                                    const X86Subtarget *Subtarget) {
26150   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26151   if (Mld->getExtensionType() != ISD::SEXTLOAD)
26152     return SDValue();
26153
26154   EVT VT = Mld->getValueType(0);
26155   unsigned NumElems = VT.getVectorNumElements();
26156   EVT LdVT = Mld->getMemoryVT();
26157   SDLoc dl(Mld);
26158
26159   assert(LdVT != VT && "Cannot extend to the same type");
26160   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26161   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26162   // From, To sizes and ElemCount must be pow of two
26163   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26164     "Unexpected size for extending masked load");
26165
26166   unsigned SizeRatio  = ToSz / FromSz;
26167   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26168
26169   // Create a type on which we perform the shuffle
26170   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26171           LdVT.getScalarType(), NumElems*SizeRatio);
26172   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26173
26174   // Convert Src0 value
26175   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26176   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26177     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26178     for (unsigned i = 0; i != NumElems; ++i)
26179       ShuffleVec[i] = i * SizeRatio;
26180
26181     // Can't shuffle using an illegal type.
26182     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26183            "WideVecVT should be legal");
26184     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26185                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26186   }
26187   // Prepare the new mask
26188   SDValue NewMask;
26189   SDValue Mask = Mld->getMask();
26190   if (Mask.getValueType() == VT) {
26191     // Mask and original value have the same type
26192     NewMask = DAG.getBitcast(WideVecVT, Mask);
26193     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26194     for (unsigned i = 0; i != NumElems; ++i)
26195       ShuffleVec[i] = i * SizeRatio;
26196     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26197       ShuffleVec[i] = NumElems * SizeRatio;
26198     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26199                                    DAG.getConstant(0, dl, WideVecVT),
26200                                    &ShuffleVec[0]);
26201   }
26202   else {
26203     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26204     unsigned WidenNumElts = NumElems*SizeRatio;
26205     unsigned MaskNumElts = VT.getVectorNumElements();
26206     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26207                                      WidenNumElts);
26208
26209     unsigned NumConcat = WidenNumElts / MaskNumElts;
26210     SmallVector<SDValue, 16> Ops(NumConcat);
26211     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26212     Ops[0] = Mask;
26213     for (unsigned i = 1; i != NumConcat; ++i)
26214       Ops[i] = ZeroVal;
26215
26216     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26217   }
26218
26219   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26220                                      Mld->getBasePtr(), NewMask, WideSrc0,
26221                                      Mld->getMemoryVT(), Mld->getMemOperand(),
26222                                      ISD::NON_EXTLOAD);
26223   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26224   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26225 }
26226 /// PerformMSTORECombine - Resolve truncating stores
26227 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26228                                     const X86Subtarget *Subtarget) {
26229   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26230   if (!Mst->isTruncatingStore())
26231     return SDValue();
26232
26233   EVT VT = Mst->getValue().getValueType();
26234   unsigned NumElems = VT.getVectorNumElements();
26235   EVT StVT = Mst->getMemoryVT();
26236   SDLoc dl(Mst);
26237
26238   assert(StVT != VT && "Cannot truncate to the same type");
26239   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26240   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26241
26242   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26243
26244   // The truncating store is legal in some cases. For example
26245   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26246   // are designated for truncate store.
26247   // In this case we don't need any further transformations.
26248   if (TLI.isTruncStoreLegal(VT, StVT))
26249     return SDValue();
26250
26251   // From, To sizes and ElemCount must be pow of two
26252   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26253     "Unexpected size for truncating masked store");
26254   // We are going to use the original vector elt for storing.
26255   // Accumulated smaller vector elements must be a multiple of the store size.
26256   assert (((NumElems * FromSz) % ToSz) == 0 &&
26257           "Unexpected ratio for truncating masked store");
26258
26259   unsigned SizeRatio  = FromSz / ToSz;
26260   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26261
26262   // Create a type on which we perform the shuffle
26263   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26264           StVT.getScalarType(), NumElems*SizeRatio);
26265
26266   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26267
26268   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26269   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26270   for (unsigned i = 0; i != NumElems; ++i)
26271     ShuffleVec[i] = i * SizeRatio;
26272
26273   // Can't shuffle using an illegal type.
26274   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26275          "WideVecVT should be legal");
26276
26277   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26278                                               DAG.getUNDEF(WideVecVT),
26279                                               &ShuffleVec[0]);
26280
26281   SDValue NewMask;
26282   SDValue Mask = Mst->getMask();
26283   if (Mask.getValueType() == VT) {
26284     // Mask and original value have the same type
26285     NewMask = DAG.getBitcast(WideVecVT, Mask);
26286     for (unsigned i = 0; i != NumElems; ++i)
26287       ShuffleVec[i] = i * SizeRatio;
26288     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26289       ShuffleVec[i] = NumElems*SizeRatio;
26290     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26291                                    DAG.getConstant(0, dl, WideVecVT),
26292                                    &ShuffleVec[0]);
26293   }
26294   else {
26295     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26296     unsigned WidenNumElts = NumElems*SizeRatio;
26297     unsigned MaskNumElts = VT.getVectorNumElements();
26298     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26299                                      WidenNumElts);
26300
26301     unsigned NumConcat = WidenNumElts / MaskNumElts;
26302     SmallVector<SDValue, 16> Ops(NumConcat);
26303     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26304     Ops[0] = Mask;
26305     for (unsigned i = 1; i != NumConcat; ++i)
26306       Ops[i] = ZeroVal;
26307
26308     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26309   }
26310
26311   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26312                             Mst->getBasePtr(), NewMask, StVT,
26313                             Mst->getMemOperand(), false);
26314 }
26315 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26316 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26317                                    const X86Subtarget *Subtarget) {
26318   StoreSDNode *St = cast<StoreSDNode>(N);
26319   EVT VT = St->getValue().getValueType();
26320   EVT StVT = St->getMemoryVT();
26321   SDLoc dl(St);
26322   SDValue StoredVal = St->getOperand(1);
26323   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26324
26325   // If we are saving a concatenation of two XMM registers and 32-byte stores
26326   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26327   bool Fast;
26328   unsigned AddressSpace = St->getAddressSpace();
26329   unsigned Alignment = St->getAlignment();
26330   if (VT.is256BitVector() && StVT == VT &&
26331       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26332                              AddressSpace, Alignment, &Fast) && !Fast) {
26333     unsigned NumElems = VT.getVectorNumElements();
26334     if (NumElems < 2)
26335       return SDValue();
26336
26337     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26338     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26339
26340     SDValue Stride =
26341         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26342     SDValue Ptr0 = St->getBasePtr();
26343     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26344
26345     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26346                                 St->getPointerInfo(), St->isVolatile(),
26347                                 St->isNonTemporal(), Alignment);
26348     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26349                                 St->getPointerInfo(), St->isVolatile(),
26350                                 St->isNonTemporal(),
26351                                 std::min(16U, Alignment));
26352     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26353   }
26354
26355   // Optimize trunc store (of multiple scalars) to shuffle and store.
26356   // First, pack all of the elements in one place. Next, store to memory
26357   // in fewer chunks.
26358   if (St->isTruncatingStore() && VT.isVector()) {
26359     // Check if we can detect an AVG pattern from the truncation. If yes,
26360     // replace the trunc store by a normal store with the result of X86ISD::AVG
26361     // instruction.
26362     SDValue Avg =
26363         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26364     if (Avg.getNode())
26365       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26366                           St->getPointerInfo(), St->isVolatile(),
26367                           St->isNonTemporal(), St->getAlignment());
26368
26369     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26370     unsigned NumElems = VT.getVectorNumElements();
26371     assert(StVT != VT && "Cannot truncate to the same type");
26372     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26373     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26374
26375     // The truncating store is legal in some cases. For example
26376     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26377     // are designated for truncate store.
26378     // In this case we don't need any further transformations.
26379     if (TLI.isTruncStoreLegal(VT, StVT))
26380       return SDValue();
26381
26382     // From, To sizes and ElemCount must be pow of two
26383     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26384     // We are going to use the original vector elt for storing.
26385     // Accumulated smaller vector elements must be a multiple of the store size.
26386     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26387
26388     unsigned SizeRatio  = FromSz / ToSz;
26389
26390     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26391
26392     // Create a type on which we perform the shuffle
26393     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26394             StVT.getScalarType(), NumElems*SizeRatio);
26395
26396     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26397
26398     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26399     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26400     for (unsigned i = 0; i != NumElems; ++i)
26401       ShuffleVec[i] = i * SizeRatio;
26402
26403     // Can't shuffle using an illegal type.
26404     if (!TLI.isTypeLegal(WideVecVT))
26405       return SDValue();
26406
26407     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26408                                          DAG.getUNDEF(WideVecVT),
26409                                          &ShuffleVec[0]);
26410     // At this point all of the data is stored at the bottom of the
26411     // register. We now need to save it to mem.
26412
26413     // Find the largest store unit
26414     MVT StoreType = MVT::i8;
26415     for (MVT Tp : MVT::integer_valuetypes()) {
26416       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26417         StoreType = Tp;
26418     }
26419
26420     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26421     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26422         (64 <= NumElems * ToSz))
26423       StoreType = MVT::f64;
26424
26425     // Bitcast the original vector into a vector of store-size units
26426     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26427             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26428     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26429     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26430     SmallVector<SDValue, 8> Chains;
26431     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26432                                         TLI.getPointerTy(DAG.getDataLayout()));
26433     SDValue Ptr = St->getBasePtr();
26434
26435     // Perform one or more big stores into memory.
26436     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26437       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26438                                    StoreType, ShuffWide,
26439                                    DAG.getIntPtrConstant(i, dl));
26440       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26441                                 St->getPointerInfo(), St->isVolatile(),
26442                                 St->isNonTemporal(), St->getAlignment());
26443       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26444       Chains.push_back(Ch);
26445     }
26446
26447     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26448   }
26449
26450   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
26451   // the FP state in cases where an emms may be missing.
26452   // A preferable solution to the general problem is to figure out the right
26453   // places to insert EMMS.  This qualifies as a quick hack.
26454
26455   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26456   if (VT.getSizeInBits() != 64)
26457     return SDValue();
26458
26459   const Function *F = DAG.getMachineFunction().getFunction();
26460   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26461   bool F64IsLegal =
26462       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26463   if ((VT.isVector() ||
26464        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26465       isa<LoadSDNode>(St->getValue()) &&
26466       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26467       St->getChain().hasOneUse() && !St->isVolatile()) {
26468     SDNode* LdVal = St->getValue().getNode();
26469     LoadSDNode *Ld = nullptr;
26470     int TokenFactorIndex = -1;
26471     SmallVector<SDValue, 8> Ops;
26472     SDNode* ChainVal = St->getChain().getNode();
26473     // Must be a store of a load.  We currently handle two cases:  the load
26474     // is a direct child, and it's under an intervening TokenFactor.  It is
26475     // possible to dig deeper under nested TokenFactors.
26476     if (ChainVal == LdVal)
26477       Ld = cast<LoadSDNode>(St->getChain());
26478     else if (St->getValue().hasOneUse() &&
26479              ChainVal->getOpcode() == ISD::TokenFactor) {
26480       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26481         if (ChainVal->getOperand(i).getNode() == LdVal) {
26482           TokenFactorIndex = i;
26483           Ld = cast<LoadSDNode>(St->getValue());
26484         } else
26485           Ops.push_back(ChainVal->getOperand(i));
26486       }
26487     }
26488
26489     if (!Ld || !ISD::isNormalLoad(Ld))
26490       return SDValue();
26491
26492     // If this is not the MMX case, i.e. we are just turning i64 load/store
26493     // into f64 load/store, avoid the transformation if there are multiple
26494     // uses of the loaded value.
26495     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26496       return SDValue();
26497
26498     SDLoc LdDL(Ld);
26499     SDLoc StDL(N);
26500     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26501     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26502     // pair instead.
26503     if (Subtarget->is64Bit() || F64IsLegal) {
26504       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26505       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26506                                   Ld->getPointerInfo(), Ld->isVolatile(),
26507                                   Ld->isNonTemporal(), Ld->isInvariant(),
26508                                   Ld->getAlignment());
26509       SDValue NewChain = NewLd.getValue(1);
26510       if (TokenFactorIndex != -1) {
26511         Ops.push_back(NewChain);
26512         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26513       }
26514       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26515                           St->getPointerInfo(),
26516                           St->isVolatile(), St->isNonTemporal(),
26517                           St->getAlignment());
26518     }
26519
26520     // Otherwise, lower to two pairs of 32-bit loads / stores.
26521     SDValue LoAddr = Ld->getBasePtr();
26522     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26523                                  DAG.getConstant(4, LdDL, MVT::i32));
26524
26525     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26526                                Ld->getPointerInfo(),
26527                                Ld->isVolatile(), Ld->isNonTemporal(),
26528                                Ld->isInvariant(), Ld->getAlignment());
26529     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26530                                Ld->getPointerInfo().getWithOffset(4),
26531                                Ld->isVolatile(), Ld->isNonTemporal(),
26532                                Ld->isInvariant(),
26533                                MinAlign(Ld->getAlignment(), 4));
26534
26535     SDValue NewChain = LoLd.getValue(1);
26536     if (TokenFactorIndex != -1) {
26537       Ops.push_back(LoLd);
26538       Ops.push_back(HiLd);
26539       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26540     }
26541
26542     LoAddr = St->getBasePtr();
26543     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26544                          DAG.getConstant(4, StDL, MVT::i32));
26545
26546     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26547                                 St->getPointerInfo(),
26548                                 St->isVolatile(), St->isNonTemporal(),
26549                                 St->getAlignment());
26550     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26551                                 St->getPointerInfo().getWithOffset(4),
26552                                 St->isVolatile(),
26553                                 St->isNonTemporal(),
26554                                 MinAlign(St->getAlignment(), 4));
26555     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26556   }
26557
26558   // This is similar to the above case, but here we handle a scalar 64-bit
26559   // integer store that is extracted from a vector on a 32-bit target.
26560   // If we have SSE2, then we can treat it like a floating-point double
26561   // to get past legalization. The execution dependencies fixup pass will
26562   // choose the optimal machine instruction for the store if this really is
26563   // an integer or v2f32 rather than an f64.
26564   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26565       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26566     SDValue OldExtract = St->getOperand(1);
26567     SDValue ExtOp0 = OldExtract.getOperand(0);
26568     unsigned VecSize = ExtOp0.getValueSizeInBits();
26569     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26570     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26571     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26572                                      BitCast, OldExtract.getOperand(1));
26573     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26574                         St->getPointerInfo(), St->isVolatile(),
26575                         St->isNonTemporal(), St->getAlignment());
26576   }
26577
26578   return SDValue();
26579 }
26580
26581 /// Return 'true' if this vector operation is "horizontal"
26582 /// and return the operands for the horizontal operation in LHS and RHS.  A
26583 /// horizontal operation performs the binary operation on successive elements
26584 /// of its first operand, then on successive elements of its second operand,
26585 /// returning the resulting values in a vector.  For example, if
26586 ///   A = < float a0, float a1, float a2, float a3 >
26587 /// and
26588 ///   B = < float b0, float b1, float b2, float b3 >
26589 /// then the result of doing a horizontal operation on A and B is
26590 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26591 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26592 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26593 /// set to A, RHS to B, and the routine returns 'true'.
26594 /// Note that the binary operation should have the property that if one of the
26595 /// operands is UNDEF then the result is UNDEF.
26596 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26597   // Look for the following pattern: if
26598   //   A = < float a0, float a1, float a2, float a3 >
26599   //   B = < float b0, float b1, float b2, float b3 >
26600   // and
26601   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26602   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26603   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26604   // which is A horizontal-op B.
26605
26606   // At least one of the operands should be a vector shuffle.
26607   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26608       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26609     return false;
26610
26611   MVT VT = LHS.getSimpleValueType();
26612
26613   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26614          "Unsupported vector type for horizontal add/sub");
26615
26616   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26617   // operate independently on 128-bit lanes.
26618   unsigned NumElts = VT.getVectorNumElements();
26619   unsigned NumLanes = VT.getSizeInBits()/128;
26620   unsigned NumLaneElts = NumElts / NumLanes;
26621   assert((NumLaneElts % 2 == 0) &&
26622          "Vector type should have an even number of elements in each lane");
26623   unsigned HalfLaneElts = NumLaneElts/2;
26624
26625   // View LHS in the form
26626   //   LHS = VECTOR_SHUFFLE A, B, LMask
26627   // If LHS is not a shuffle then pretend it is the shuffle
26628   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26629   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26630   // type VT.
26631   SDValue A, B;
26632   SmallVector<int, 16> LMask(NumElts);
26633   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26634     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26635       A = LHS.getOperand(0);
26636     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26637       B = LHS.getOperand(1);
26638     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26639     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26640   } else {
26641     if (LHS.getOpcode() != ISD::UNDEF)
26642       A = LHS;
26643     for (unsigned i = 0; i != NumElts; ++i)
26644       LMask[i] = i;
26645   }
26646
26647   // Likewise, view RHS in the form
26648   //   RHS = VECTOR_SHUFFLE C, D, RMask
26649   SDValue C, D;
26650   SmallVector<int, 16> RMask(NumElts);
26651   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26652     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26653       C = RHS.getOperand(0);
26654     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26655       D = RHS.getOperand(1);
26656     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26657     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26658   } else {
26659     if (RHS.getOpcode() != ISD::UNDEF)
26660       C = RHS;
26661     for (unsigned i = 0; i != NumElts; ++i)
26662       RMask[i] = i;
26663   }
26664
26665   // Check that the shuffles are both shuffling the same vectors.
26666   if (!(A == C && B == D) && !(A == D && B == C))
26667     return false;
26668
26669   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26670   if (!A.getNode() && !B.getNode())
26671     return false;
26672
26673   // If A and B occur in reverse order in RHS, then "swap" them (which means
26674   // rewriting the mask).
26675   if (A != C)
26676     ShuffleVectorSDNode::commuteMask(RMask);
26677
26678   // At this point LHS and RHS are equivalent to
26679   //   LHS = VECTOR_SHUFFLE A, B, LMask
26680   //   RHS = VECTOR_SHUFFLE A, B, RMask
26681   // Check that the masks correspond to performing a horizontal operation.
26682   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26683     for (unsigned i = 0; i != NumLaneElts; ++i) {
26684       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26685
26686       // Ignore any UNDEF components.
26687       if (LIdx < 0 || RIdx < 0 ||
26688           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26689           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26690         continue;
26691
26692       // Check that successive elements are being operated on.  If not, this is
26693       // not a horizontal operation.
26694       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26695       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26696       if (!(LIdx == Index && RIdx == Index + 1) &&
26697           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26698         return false;
26699     }
26700   }
26701
26702   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26703   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26704   return true;
26705 }
26706
26707 /// Do target-specific dag combines on floating point adds.
26708 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26709                                   const X86Subtarget *Subtarget) {
26710   EVT VT = N->getValueType(0);
26711   SDValue LHS = N->getOperand(0);
26712   SDValue RHS = N->getOperand(1);
26713
26714   // Try to synthesize horizontal adds from adds of shuffles.
26715   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26716        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26717       isHorizontalBinOp(LHS, RHS, true))
26718     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26719   return SDValue();
26720 }
26721
26722 /// Do target-specific dag combines on floating point subs.
26723 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26724                                   const X86Subtarget *Subtarget) {
26725   EVT VT = N->getValueType(0);
26726   SDValue LHS = N->getOperand(0);
26727   SDValue RHS = N->getOperand(1);
26728
26729   // Try to synthesize horizontal subs from subs of shuffles.
26730   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26731        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26732       isHorizontalBinOp(LHS, RHS, false))
26733     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26734   return SDValue();
26735 }
26736
26737 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26738 static SDValue
26739 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26740                                   SmallVector<SDValue, 8> &Regs) {
26741   assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26742                              Regs[0].getValueType() == MVT::v2i64));
26743   EVT OutVT = N->getValueType(0);
26744   EVT OutSVT = OutVT.getVectorElementType();
26745   EVT InVT = Regs[0].getValueType();
26746   EVT InSVT = InVT.getVectorElementType();
26747   SDLoc DL(N);
26748
26749   // First, use mask to unset all bits that won't appear in the result.
26750   assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26751          "OutSVT can only be either i8 or i16.");
26752   SDValue MaskVal =
26753       DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26754   SDValue MaskVec = DAG.getNode(
26755       ISD::BUILD_VECTOR, DL, InVT,
26756       SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26757   for (auto &Reg : Regs)
26758     Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26759
26760   MVT UnpackedVT, PackedVT;
26761   if (OutSVT == MVT::i8) {
26762     UnpackedVT = MVT::v8i16;
26763     PackedVT = MVT::v16i8;
26764   } else {
26765     UnpackedVT = MVT::v4i32;
26766     PackedVT = MVT::v8i16;
26767   }
26768
26769   // In each iteration, truncate the type by a half size.
26770   auto RegNum = Regs.size();
26771   for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26772        j < e; j *= 2, RegNum /= 2) {
26773     for (unsigned i = 0; i < RegNum; i++)
26774       Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26775     for (unsigned i = 0; i < RegNum / 2; i++)
26776       Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26777                             Regs[i * 2 + 1]);
26778   }
26779
26780   // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26781   // then extract a subvector as the result since v8i8 is not a legal type.
26782   if (OutVT == MVT::v8i8) {
26783     Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26784     Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26785                           DAG.getIntPtrConstant(0, DL));
26786     return Regs[0];
26787   } else if (RegNum > 1) {
26788     Regs.resize(RegNum);
26789     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26790   } else
26791     return Regs[0];
26792 }
26793
26794 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26795 static SDValue
26796 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26797                                   SmallVector<SDValue, 8> &Regs) {
26798   assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26799   EVT OutVT = N->getValueType(0);
26800   SDLoc DL(N);
26801
26802   // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26803   SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26804   for (auto &Reg : Regs) {
26805     Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26806     Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26807   }
26808
26809   for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26810     Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26811                           Regs[i * 2 + 1]);
26812
26813   if (Regs.size() > 2) {
26814     Regs.resize(Regs.size() / 2);
26815     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26816   } else
26817     return Regs[0];
26818 }
26819
26820 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26821 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26822 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26823 /// element that is extracted from a vector and then truncated, and it is
26824 /// diffcult to do this optimization based on them.
26825 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26826                                        const X86Subtarget *Subtarget) {
26827   EVT OutVT = N->getValueType(0);
26828   if (!OutVT.isVector())
26829     return SDValue();
26830
26831   SDValue In = N->getOperand(0);
26832   if (!In.getValueType().isSimple())
26833     return SDValue();
26834
26835   EVT InVT = In.getValueType();
26836   unsigned NumElems = OutVT.getVectorNumElements();
26837
26838   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26839   // SSE2, and we need to take care of it specially.
26840   // AVX512 provides vpmovdb.
26841   if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26842     return SDValue();
26843
26844   EVT OutSVT = OutVT.getVectorElementType();
26845   EVT InSVT = InVT.getVectorElementType();
26846   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26847         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26848         NumElems >= 8))
26849     return SDValue();
26850
26851   // SSSE3's pshufb results in less instructions in the cases below.
26852   if (Subtarget->hasSSSE3() && NumElems == 8 &&
26853       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26854        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26855     return SDValue();
26856
26857   SDLoc DL(N);
26858
26859   // Split a long vector into vectors of legal type.
26860   unsigned RegNum = InVT.getSizeInBits() / 128;
26861   SmallVector<SDValue, 8> SubVec(RegNum);
26862   if (InSVT == MVT::i32) {
26863     for (unsigned i = 0; i < RegNum; i++)
26864       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26865                               DAG.getIntPtrConstant(i * 4, DL));
26866   } else {
26867     for (unsigned i = 0; i < RegNum; i++)
26868       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
26869                               DAG.getIntPtrConstant(i * 2, DL));
26870   }
26871
26872   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
26873   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
26874   // truncate 2 x v4i32 to v8i16.
26875   if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
26876     return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
26877   else if (InSVT == MVT::i32)
26878     return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
26879   else
26880     return SDValue();
26881 }
26882
26883 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
26884                                       const X86Subtarget *Subtarget) {
26885   // Try to detect AVG pattern first.
26886   SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
26887                                  Subtarget, SDLoc(N));
26888   if (Avg.getNode())
26889     return Avg;
26890
26891   return combineVectorTruncation(N, DAG, Subtarget);
26892 }
26893
26894 /// Do target-specific dag combines on floating point negations.
26895 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26896                                   const X86Subtarget *Subtarget) {
26897   EVT VT = N->getValueType(0);
26898   EVT SVT = VT.getScalarType();
26899   SDValue Arg = N->getOperand(0);
26900   SDLoc DL(N);
26901
26902   // Let legalize expand this if it isn't a legal type yet.
26903   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26904     return SDValue();
26905
26906   // If we're negating a FMUL node on a target with FMA, then we can avoid the
26907   // use of a constant by performing (-0 - A*B) instead.
26908   // FIXME: Check rounding control flags as well once it becomes available.
26909   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
26910       Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
26911     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
26912     return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26913                        Arg.getOperand(1), Zero);
26914   }
26915
26916   // If we're negating a FMA node, then we can adjust the
26917   // instruction to include the extra negation.
26918   if (Arg.hasOneUse()) {
26919     switch (Arg.getOpcode()) {
26920     case X86ISD::FMADD:
26921       return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26922                          Arg.getOperand(1), Arg.getOperand(2));
26923     case X86ISD::FMSUB:
26924       return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
26925                          Arg.getOperand(1), Arg.getOperand(2));
26926     case X86ISD::FNMADD:
26927       return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
26928                          Arg.getOperand(1), Arg.getOperand(2));
26929     case X86ISD::FNMSUB:
26930       return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
26931                          Arg.getOperand(1), Arg.getOperand(2));
26932     }
26933   }
26934   return SDValue();
26935 }
26936
26937 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
26938                               const X86Subtarget *Subtarget) {
26939   EVT VT = N->getValueType(0);
26940   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
26941     // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
26942     // These logic operations may be executed in the integer domain.
26943     SDLoc dl(N);
26944     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
26945     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
26946
26947     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
26948     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
26949     unsigned IntOpcode = 0;
26950     switch (N->getOpcode()) {
26951       default: llvm_unreachable("Unexpected FP logic op");
26952       case X86ISD::FOR: IntOpcode = ISD::OR; break;
26953       case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
26954       case X86ISD::FAND: IntOpcode = ISD::AND; break;
26955       case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
26956     }
26957     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
26958     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
26959   }
26960   return SDValue();
26961 }
26962 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
26963 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
26964                                  const X86Subtarget *Subtarget) {
26965   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
26966
26967   // F[X]OR(0.0, x) -> x
26968   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26969     if (C->getValueAPF().isPosZero())
26970       return N->getOperand(1);
26971
26972   // F[X]OR(x, 0.0) -> x
26973   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26974     if (C->getValueAPF().isPosZero())
26975       return N->getOperand(0);
26976
26977   return lowerX86FPLogicOp(N, DAG, Subtarget);
26978 }
26979
26980 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
26981 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
26982   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
26983
26984   // Only perform optimizations if UnsafeMath is used.
26985   if (!DAG.getTarget().Options.UnsafeFPMath)
26986     return SDValue();
26987
26988   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
26989   // into FMINC and FMAXC, which are Commutative operations.
26990   unsigned NewOp = 0;
26991   switch (N->getOpcode()) {
26992     default: llvm_unreachable("unknown opcode");
26993     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
26994     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
26995   }
26996
26997   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
26998                      N->getOperand(0), N->getOperand(1));
26999 }
27000
27001 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27002                                             const X86Subtarget *Subtarget) {
27003   if (Subtarget->useSoftFloat())
27004     return SDValue();
27005
27006   // TODO: Check for global or instruction-level "nnan". In that case, we
27007   //       should be able to lower to FMAX/FMIN alone.
27008   // TODO: If an operand is already known to be a NaN or not a NaN, this
27009   //       should be an optional swap and FMAX/FMIN.
27010
27011   EVT VT = N->getValueType(0);
27012   if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27013         (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27014         (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27015     return SDValue();
27016
27017   // This takes at least 3 instructions, so favor a library call when operating
27018   // on a scalar and minimizing code size.
27019   if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27020     return SDValue();
27021
27022   SDValue Op0 = N->getOperand(0);
27023   SDValue Op1 = N->getOperand(1);
27024   SDLoc DL(N);
27025   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27026       DAG.getDataLayout(), *DAG.getContext(), VT);
27027
27028   // There are 4 possibilities involving NaN inputs, and these are the required
27029   // outputs:
27030   //                   Op1
27031   //               Num     NaN
27032   //            ----------------
27033   //       Num  |  Max  |  Op0 |
27034   // Op0        ----------------
27035   //       NaN  |  Op1  |  NaN |
27036   //            ----------------
27037   //
27038   // The SSE FP max/min instructions were not designed for this case, but rather
27039   // to implement:
27040   //   Min = Op1 < Op0 ? Op1 : Op0
27041   //   Max = Op1 > Op0 ? Op1 : Op0
27042   //
27043   // So they always return Op0 if either input is a NaN. However, we can still
27044   // use those instructions for fmaxnum by selecting away a NaN input.
27045
27046   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27047   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27048   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27049   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27050
27051   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27052   // are NaN, the NaN value of Op1 is the result.
27053   auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27054   return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27055 }
27056
27057 /// Do target-specific dag combines on X86ISD::FAND nodes.
27058 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27059                                   const X86Subtarget *Subtarget) {
27060   // FAND(0.0, x) -> 0.0
27061   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27062     if (C->getValueAPF().isPosZero())
27063       return N->getOperand(0);
27064
27065   // FAND(x, 0.0) -> 0.0
27066   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27067     if (C->getValueAPF().isPosZero())
27068       return N->getOperand(1);
27069
27070   return lowerX86FPLogicOp(N, DAG, Subtarget);
27071 }
27072
27073 /// Do target-specific dag combines on X86ISD::FANDN nodes
27074 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27075                                    const X86Subtarget *Subtarget) {
27076   // FANDN(0.0, x) -> x
27077   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27078     if (C->getValueAPF().isPosZero())
27079       return N->getOperand(1);
27080
27081   // FANDN(x, 0.0) -> 0.0
27082   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27083     if (C->getValueAPF().isPosZero())
27084       return N->getOperand(1);
27085
27086   return lowerX86FPLogicOp(N, DAG, Subtarget);
27087 }
27088
27089 static SDValue PerformBTCombine(SDNode *N,
27090                                 SelectionDAG &DAG,
27091                                 TargetLowering::DAGCombinerInfo &DCI) {
27092   // BT ignores high bits in the bit index operand.
27093   SDValue Op1 = N->getOperand(1);
27094   if (Op1.hasOneUse()) {
27095     unsigned BitWidth = Op1.getValueSizeInBits();
27096     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27097     APInt KnownZero, KnownOne;
27098     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27099                                           !DCI.isBeforeLegalizeOps());
27100     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27101     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27102         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27103       DCI.CommitTargetLoweringOpt(TLO);
27104   }
27105   return SDValue();
27106 }
27107
27108 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27109   SDValue Op = N->getOperand(0);
27110   if (Op.getOpcode() == ISD::BITCAST)
27111     Op = Op.getOperand(0);
27112   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27113   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27114       VT.getVectorElementType().getSizeInBits() ==
27115       OpVT.getVectorElementType().getSizeInBits()) {
27116     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27117   }
27118   return SDValue();
27119 }
27120
27121 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27122                                                const X86Subtarget *Subtarget) {
27123   EVT VT = N->getValueType(0);
27124   if (!VT.isVector())
27125     return SDValue();
27126
27127   SDValue N0 = N->getOperand(0);
27128   SDValue N1 = N->getOperand(1);
27129   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27130   SDLoc dl(N);
27131
27132   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27133   // both SSE and AVX2 since there is no sign-extended shift right
27134   // operation on a vector with 64-bit elements.
27135   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27136   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27137   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27138       N0.getOpcode() == ISD::SIGN_EXTEND)) {
27139     SDValue N00 = N0.getOperand(0);
27140
27141     // EXTLOAD has a better solution on AVX2,
27142     // it may be replaced with X86ISD::VSEXT node.
27143     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27144       if (!ISD::isNormalLoad(N00.getNode()))
27145         return SDValue();
27146
27147     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27148         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27149                                   N00, N1);
27150       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27151     }
27152   }
27153   return SDValue();
27154 }
27155
27156 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27157 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27158 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27159 /// eliminate extend, add, and shift instructions.
27160 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27161                                        const X86Subtarget *Subtarget) {
27162   // TODO: This should be valid for other integer types.
27163   EVT VT = Sext->getValueType(0);
27164   if (VT != MVT::i64)
27165     return SDValue();
27166
27167   // We need an 'add nsw' feeding into the 'sext'.
27168   SDValue Add = Sext->getOperand(0);
27169   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27170     return SDValue();
27171
27172   // Having a constant operand to the 'add' ensures that we are not increasing
27173   // the instruction count because the constant is extended for free below.
27174   // A constant operand can also become the displacement field of an LEA.
27175   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27176   if (!AddOp1)
27177     return SDValue();
27178
27179   // Don't make the 'add' bigger if there's no hope of combining it with some
27180   // other 'add' or 'shl' instruction.
27181   // TODO: It may be profitable to generate simpler LEA instructions in place
27182   // of single 'add' instructions, but the cost model for selecting an LEA
27183   // currently has a high threshold.
27184   bool HasLEAPotential = false;
27185   for (auto *User : Sext->uses()) {
27186     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27187       HasLEAPotential = true;
27188       break;
27189     }
27190   }
27191   if (!HasLEAPotential)
27192     return SDValue();
27193
27194   // Everything looks good, so pull the 'sext' ahead of the 'add'.
27195   int64_t AddConstant = AddOp1->getSExtValue();
27196   SDValue AddOp0 = Add.getOperand(0);
27197   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27198   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27199
27200   // The wider add is guaranteed to not wrap because both operands are
27201   // sign-extended.
27202   SDNodeFlags Flags;
27203   Flags.setNoSignedWrap(true);
27204   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27205 }
27206
27207 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27208                                   TargetLowering::DAGCombinerInfo &DCI,
27209                                   const X86Subtarget *Subtarget) {
27210   SDValue N0 = N->getOperand(0);
27211   EVT VT = N->getValueType(0);
27212   EVT SVT = VT.getScalarType();
27213   EVT InVT = N0.getValueType();
27214   EVT InSVT = InVT.getScalarType();
27215   SDLoc DL(N);
27216
27217   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
27218   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
27219   // This exposes the sext to the sdivrem lowering, so that it directly extends
27220   // from AH (which we otherwise need to do contortions to access).
27221   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
27222       InVT == MVT::i8 && VT == MVT::i32) {
27223     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27224     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
27225                             N0.getOperand(0), N0.getOperand(1));
27226     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27227     return R.getValue(1);
27228   }
27229
27230   if (!DCI.isBeforeLegalizeOps()) {
27231     if (InVT == MVT::i1) {
27232       SDValue Zero = DAG.getConstant(0, DL, VT);
27233       SDValue AllOnes =
27234         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27235       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27236     }
27237     return SDValue();
27238   }
27239
27240   if (VT.isVector() && Subtarget->hasSSE2()) {
27241     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27242       EVT InVT = N.getValueType();
27243       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27244                                    Size / InVT.getScalarSizeInBits());
27245       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27246                                     DAG.getUNDEF(InVT));
27247       Opnds[0] = N;
27248       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27249     };
27250
27251     // If target-size is less than 128-bits, extend to a type that would extend
27252     // to 128 bits, extend that and extract the original target vector.
27253     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27254         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27255         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27256       unsigned Scale = 128 / VT.getSizeInBits();
27257       EVT ExVT =
27258           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27259       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27260       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27261       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27262                          DAG.getIntPtrConstant(0, DL));
27263     }
27264
27265     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27266     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27267     if (VT.getSizeInBits() == 128 &&
27268         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27269         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27270       SDValue ExOp = ExtendVecSize(DL, N0, 128);
27271       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27272     }
27273
27274     // On pre-AVX2 targets, split into 128-bit nodes of
27275     // ISD::SIGN_EXTEND_VECTOR_INREG.
27276     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27277         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27278         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27279       unsigned NumVecs = VT.getSizeInBits() / 128;
27280       unsigned NumSubElts = 128 / SVT.getSizeInBits();
27281       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27282       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27283
27284       SmallVector<SDValue, 8> Opnds;
27285       for (unsigned i = 0, Offset = 0; i != NumVecs;
27286            ++i, Offset += NumSubElts) {
27287         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27288                                      DAG.getIntPtrConstant(Offset, DL));
27289         SrcVec = ExtendVecSize(DL, SrcVec, 128);
27290         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27291         Opnds.push_back(SrcVec);
27292       }
27293       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27294     }
27295   }
27296
27297   if (Subtarget->hasAVX() && VT.is256BitVector())
27298     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27299       return R;
27300
27301   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27302     return NewAdd;
27303
27304   return SDValue();
27305 }
27306
27307 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27308                                  const X86Subtarget* Subtarget) {
27309   SDLoc dl(N);
27310   EVT VT = N->getValueType(0);
27311
27312   // Let legalize expand this if it isn't a legal type yet.
27313   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27314     return SDValue();
27315
27316   EVT ScalarVT = VT.getScalarType();
27317   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27318     return SDValue();
27319
27320   SDValue A = N->getOperand(0);
27321   SDValue B = N->getOperand(1);
27322   SDValue C = N->getOperand(2);
27323
27324   bool NegA = (A.getOpcode() == ISD::FNEG);
27325   bool NegB = (B.getOpcode() == ISD::FNEG);
27326   bool NegC = (C.getOpcode() == ISD::FNEG);
27327
27328   // Negative multiplication when NegA xor NegB
27329   bool NegMul = (NegA != NegB);
27330   if (NegA)
27331     A = A.getOperand(0);
27332   if (NegB)
27333     B = B.getOperand(0);
27334   if (NegC)
27335     C = C.getOperand(0);
27336
27337   unsigned Opcode;
27338   if (!NegMul)
27339     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27340   else
27341     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27342
27343   return DAG.getNode(Opcode, dl, VT, A, B, C);
27344 }
27345
27346 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27347                                   TargetLowering::DAGCombinerInfo &DCI,
27348                                   const X86Subtarget *Subtarget) {
27349   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
27350   //           (and (i32 x86isd::setcc_carry), 1)
27351   // This eliminates the zext. This transformation is necessary because
27352   // ISD::SETCC is always legalized to i8.
27353   SDLoc dl(N);
27354   SDValue N0 = N->getOperand(0);
27355   EVT VT = N->getValueType(0);
27356
27357   if (N0.getOpcode() == ISD::AND &&
27358       N0.hasOneUse() &&
27359       N0.getOperand(0).hasOneUse()) {
27360     SDValue N00 = N0.getOperand(0);
27361     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27362       if (!isOneConstant(N0.getOperand(1)))
27363         return SDValue();
27364       return DAG.getNode(ISD::AND, dl, VT,
27365                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27366                                      N00.getOperand(0), N00.getOperand(1)),
27367                          DAG.getConstant(1, dl, VT));
27368     }
27369   }
27370
27371   if (N0.getOpcode() == ISD::TRUNCATE &&
27372       N0.hasOneUse() &&
27373       N0.getOperand(0).hasOneUse()) {
27374     SDValue N00 = N0.getOperand(0);
27375     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27376       return DAG.getNode(ISD::AND, dl, VT,
27377                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27378                                      N00.getOperand(0), N00.getOperand(1)),
27379                          DAG.getConstant(1, dl, VT));
27380     }
27381   }
27382
27383   if (VT.is256BitVector())
27384     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27385       return R;
27386
27387   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
27388   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
27389   // This exposes the zext to the udivrem lowering, so that it directly extends
27390   // from AH (which we otherwise need to do contortions to access).
27391   if (N0.getOpcode() == ISD::UDIVREM &&
27392       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
27393       (VT == MVT::i32 || VT == MVT::i64)) {
27394     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27395     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
27396                             N0.getOperand(0), N0.getOperand(1));
27397     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27398     return R.getValue(1);
27399   }
27400
27401   return SDValue();
27402 }
27403
27404 // Optimize x == -y --> x+y == 0
27405 //          x != -y --> x+y != 0
27406 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27407                                       const X86Subtarget* Subtarget) {
27408   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27409   SDValue LHS = N->getOperand(0);
27410   SDValue RHS = N->getOperand(1);
27411   EVT VT = N->getValueType(0);
27412   SDLoc DL(N);
27413
27414   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27415     if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27416       SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27417                                  LHS.getOperand(1));
27418       return DAG.getSetCC(DL, N->getValueType(0), addV,
27419                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27420     }
27421   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27422     if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27423       SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27424                                  RHS.getOperand(1));
27425       return DAG.getSetCC(DL, N->getValueType(0), addV,
27426                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27427     }
27428
27429   if (VT.getScalarType() == MVT::i1 &&
27430       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27431     bool IsSEXT0 =
27432         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27433         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27434     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27435
27436     if (!IsSEXT0 || !IsVZero1) {
27437       // Swap the operands and update the condition code.
27438       std::swap(LHS, RHS);
27439       CC = ISD::getSetCCSwappedOperands(CC);
27440
27441       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27442                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27443       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27444     }
27445
27446     if (IsSEXT0 && IsVZero1) {
27447       assert(VT == LHS.getOperand(0).getValueType() &&
27448              "Uexpected operand type");
27449       if (CC == ISD::SETGT)
27450         return DAG.getConstant(0, DL, VT);
27451       if (CC == ISD::SETLE)
27452         return DAG.getConstant(1, DL, VT);
27453       if (CC == ISD::SETEQ || CC == ISD::SETGE)
27454         return DAG.getNOT(DL, LHS.getOperand(0), VT);
27455
27456       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27457              "Unexpected condition code!");
27458       return LHS.getOperand(0);
27459     }
27460   }
27461
27462   return SDValue();
27463 }
27464
27465 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
27466   SDValue V0 = N->getOperand(0);
27467   SDValue V1 = N->getOperand(1);
27468   SDLoc DL(N);
27469   EVT VT = N->getValueType(0);
27470
27471   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
27472   // operands and changing the mask to 1. This saves us a bunch of
27473   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
27474   // x86InstrInfo knows how to commute this back after instruction selection
27475   // if it would help register allocation.
27476
27477   // TODO: If optimizing for size or a processor that doesn't suffer from
27478   // partial register update stalls, this should be transformed into a MOVSD
27479   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
27480
27481   if (VT == MVT::v2f64)
27482     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
27483       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
27484         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
27485         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
27486       }
27487
27488   return SDValue();
27489 }
27490
27491 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27492   SDLoc DL(N);
27493   // Gather and Scatter instructions use k-registers for masks. The type of
27494   // the masks is v*i1. So the mask will be truncated anyway.
27495   // The SIGN_EXTEND_INREG my be dropped.
27496   SDValue Mask = N->getOperand(2);
27497   if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27498     SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27499     NewOps[2] = Mask.getOperand(0);
27500     DAG.UpdateNodeOperands(N, NewOps);
27501   }
27502   return SDValue();
27503 }
27504
27505 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27506 // as "sbb reg,reg", since it can be extended without zext and produces
27507 // an all-ones bit which is more useful than 0/1 in some cases.
27508 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27509                                MVT VT) {
27510   if (VT == MVT::i8)
27511     return DAG.getNode(ISD::AND, DL, VT,
27512                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27513                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
27514                                    EFLAGS),
27515                        DAG.getConstant(1, DL, VT));
27516   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27517   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27518                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27519                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
27520                                  EFLAGS));
27521 }
27522
27523 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27524 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27525                                    TargetLowering::DAGCombinerInfo &DCI,
27526                                    const X86Subtarget *Subtarget) {
27527   SDLoc DL(N);
27528   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27529   SDValue EFLAGS = N->getOperand(1);
27530
27531   if (CC == X86::COND_A) {
27532     // Try to convert COND_A into COND_B in an attempt to facilitate
27533     // materializing "setb reg".
27534     //
27535     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27536     // cannot take an immediate as its first operand.
27537     //
27538     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27539         EFLAGS.getValueType().isInteger() &&
27540         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27541       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27542                                    EFLAGS.getNode()->getVTList(),
27543                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27544       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27545       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27546     }
27547   }
27548
27549   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27550   // a zext and produces an all-ones bit which is more useful than 0/1 in some
27551   // cases.
27552   if (CC == X86::COND_B)
27553     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27554
27555   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27556     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27557     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27558   }
27559
27560   return SDValue();
27561 }
27562
27563 // Optimize branch condition evaluation.
27564 //
27565 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27566                                     TargetLowering::DAGCombinerInfo &DCI,
27567                                     const X86Subtarget *Subtarget) {
27568   SDLoc DL(N);
27569   SDValue Chain = N->getOperand(0);
27570   SDValue Dest = N->getOperand(1);
27571   SDValue EFLAGS = N->getOperand(3);
27572   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27573
27574   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27575     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27576     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27577                        Flags);
27578   }
27579
27580   return SDValue();
27581 }
27582
27583 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27584                                                          SelectionDAG &DAG) {
27585   // Take advantage of vector comparisons producing 0 or -1 in each lane to
27586   // optimize away operation when it's from a constant.
27587   //
27588   // The general transformation is:
27589   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27590   //       AND(VECTOR_CMP(x,y), constant2)
27591   //    constant2 = UNARYOP(constant)
27592
27593   // Early exit if this isn't a vector operation, the operand of the
27594   // unary operation isn't a bitwise AND, or if the sizes of the operations
27595   // aren't the same.
27596   EVT VT = N->getValueType(0);
27597   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27598       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27599       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27600     return SDValue();
27601
27602   // Now check that the other operand of the AND is a constant. We could
27603   // make the transformation for non-constant splats as well, but it's unclear
27604   // that would be a benefit as it would not eliminate any operations, just
27605   // perform one more step in scalar code before moving to the vector unit.
27606   if (BuildVectorSDNode *BV =
27607           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27608     // Bail out if the vector isn't a constant.
27609     if (!BV->isConstant())
27610       return SDValue();
27611
27612     // Everything checks out. Build up the new and improved node.
27613     SDLoc DL(N);
27614     EVT IntVT = BV->getValueType(0);
27615     // Create a new constant of the appropriate type for the transformed
27616     // DAG.
27617     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27618     // The AND node needs bitcasts to/from an integer vector type around it.
27619     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27620     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27621                                  N->getOperand(0)->getOperand(0), MaskConst);
27622     SDValue Res = DAG.getBitcast(VT, NewAnd);
27623     return Res;
27624   }
27625
27626   return SDValue();
27627 }
27628
27629 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27630                                         const X86Subtarget *Subtarget) {
27631   SDValue Op0 = N->getOperand(0);
27632   EVT VT = N->getValueType(0);
27633   EVT InVT = Op0.getValueType();
27634   EVT InSVT = InVT.getScalarType();
27635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27636
27637   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27638   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27639   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27640     SDLoc dl(N);
27641     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27642                                  InVT.getVectorNumElements());
27643     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27644
27645     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27646       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27647
27648     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27649   }
27650
27651   return SDValue();
27652 }
27653
27654 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27655                                         const X86Subtarget *Subtarget) {
27656   // First try to optimize away the conversion entirely when it's
27657   // conditionally from a constant. Vectors only.
27658   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27659     return Res;
27660
27661   // Now move on to more general possibilities.
27662   SDValue Op0 = N->getOperand(0);
27663   EVT VT = N->getValueType(0);
27664   EVT InVT = Op0.getValueType();
27665   EVT InSVT = InVT.getScalarType();
27666
27667   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27668   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27669   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27670     SDLoc dl(N);
27671     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27672                                  InVT.getVectorNumElements());
27673     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27674     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27675   }
27676
27677   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27678   // a 32-bit target where SSE doesn't support i64->FP operations.
27679   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27680     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27681     EVT LdVT = Ld->getValueType(0);
27682
27683     // This transformation is not supported if the result type is f16
27684     if (VT == MVT::f16)
27685       return SDValue();
27686
27687     if (!Ld->isVolatile() && !VT.isVector() &&
27688         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27689         !Subtarget->is64Bit() && LdVT == MVT::i64) {
27690       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27691           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27692       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27693       return FILDChain;
27694     }
27695   }
27696   return SDValue();
27697 }
27698
27699 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27700 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27701                                  X86TargetLowering::DAGCombinerInfo &DCI) {
27702   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27703   // the result is either zero or one (depending on the input carry bit).
27704   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27705   if (X86::isZeroNode(N->getOperand(0)) &&
27706       X86::isZeroNode(N->getOperand(1)) &&
27707       // We don't have a good way to replace an EFLAGS use, so only do this when
27708       // dead right now.
27709       SDValue(N, 1).use_empty()) {
27710     SDLoc DL(N);
27711     EVT VT = N->getValueType(0);
27712     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27713     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27714                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27715                                            DAG.getConstant(X86::COND_B, DL,
27716                                                            MVT::i8),
27717                                            N->getOperand(2)),
27718                                DAG.getConstant(1, DL, VT));
27719     return DCI.CombineTo(N, Res1, CarryOut);
27720   }
27721
27722   return SDValue();
27723 }
27724
27725 // fold (add Y, (sete  X, 0)) -> adc  0, Y
27726 //      (add Y, (setne X, 0)) -> sbb -1, Y
27727 //      (sub (sete  X, 0), Y) -> sbb  0, Y
27728 //      (sub (setne X, 0), Y) -> adc -1, Y
27729 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27730   SDLoc DL(N);
27731
27732   // Look through ZExts.
27733   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27734   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27735     return SDValue();
27736
27737   SDValue SetCC = Ext.getOperand(0);
27738   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27739     return SDValue();
27740
27741   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27742   if (CC != X86::COND_E && CC != X86::COND_NE)
27743     return SDValue();
27744
27745   SDValue Cmp = SetCC.getOperand(1);
27746   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27747       !X86::isZeroNode(Cmp.getOperand(1)) ||
27748       !Cmp.getOperand(0).getValueType().isInteger())
27749     return SDValue();
27750
27751   SDValue CmpOp0 = Cmp.getOperand(0);
27752   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27753                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
27754
27755   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27756   if (CC == X86::COND_NE)
27757     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27758                        DL, OtherVal.getValueType(), OtherVal,
27759                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27760                        NewCmp);
27761   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27762                      DL, OtherVal.getValueType(), OtherVal,
27763                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27764 }
27765
27766 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27767 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27768                                  const X86Subtarget *Subtarget) {
27769   EVT VT = N->getValueType(0);
27770   SDValue Op0 = N->getOperand(0);
27771   SDValue Op1 = N->getOperand(1);
27772
27773   // Try to synthesize horizontal adds from adds of shuffles.
27774   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27775        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27776       isHorizontalBinOp(Op0, Op1, true))
27777     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27778
27779   return OptimizeConditionalInDecrement(N, DAG);
27780 }
27781
27782 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27783                                  const X86Subtarget *Subtarget) {
27784   SDValue Op0 = N->getOperand(0);
27785   SDValue Op1 = N->getOperand(1);
27786
27787   // X86 can't encode an immediate LHS of a sub. See if we can push the
27788   // negation into a preceding instruction.
27789   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27790     // If the RHS of the sub is a XOR with one use and a constant, invert the
27791     // immediate. Then add one to the LHS of the sub so we can turn
27792     // X-Y -> X+~Y+1, saving one register.
27793     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27794         isa<ConstantSDNode>(Op1.getOperand(1))) {
27795       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27796       EVT VT = Op0.getValueType();
27797       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27798                                    Op1.getOperand(0),
27799                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
27800       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27801                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27802     }
27803   }
27804
27805   // Try to synthesize horizontal adds from adds of shuffles.
27806   EVT VT = N->getValueType(0);
27807   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27808        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27809       isHorizontalBinOp(Op0, Op1, true))
27810     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27811
27812   return OptimizeConditionalInDecrement(N, DAG);
27813 }
27814
27815 /// performVZEXTCombine - Performs build vector combines
27816 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27817                                    TargetLowering::DAGCombinerInfo &DCI,
27818                                    const X86Subtarget *Subtarget) {
27819   SDLoc DL(N);
27820   MVT VT = N->getSimpleValueType(0);
27821   SDValue Op = N->getOperand(0);
27822   MVT OpVT = Op.getSimpleValueType();
27823   MVT OpEltVT = OpVT.getVectorElementType();
27824   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27825
27826   // (vzext (bitcast (vzext (x)) -> (vzext x)
27827   SDValue V = Op;
27828   while (V.getOpcode() == ISD::BITCAST)
27829     V = V.getOperand(0);
27830
27831   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27832     MVT InnerVT = V.getSimpleValueType();
27833     MVT InnerEltVT = InnerVT.getVectorElementType();
27834
27835     // If the element sizes match exactly, we can just do one larger vzext. This
27836     // is always an exact type match as vzext operates on integer types.
27837     if (OpEltVT == InnerEltVT) {
27838       assert(OpVT == InnerVT && "Types must match for vzext!");
27839       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27840     }
27841
27842     // The only other way we can combine them is if only a single element of the
27843     // inner vzext is used in the input to the outer vzext.
27844     if (InnerEltVT.getSizeInBits() < InputBits)
27845       return SDValue();
27846
27847     // In this case, the inner vzext is completely dead because we're going to
27848     // only look at bits inside of the low element. Just do the outer vzext on
27849     // a bitcast of the input to the inner.
27850     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27851   }
27852
27853   // Check if we can bypass extracting and re-inserting an element of an input
27854   // vector. Essentially:
27855   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27856   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27857       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27858       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27859     SDValue ExtractedV = V.getOperand(0);
27860     SDValue OrigV = ExtractedV.getOperand(0);
27861     if (isNullConstant(ExtractedV.getOperand(1))) {
27862         MVT OrigVT = OrigV.getSimpleValueType();
27863         // Extract a subvector if necessary...
27864         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27865           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27866           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27867                                     OrigVT.getVectorNumElements() / Ratio);
27868           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27869                               DAG.getIntPtrConstant(0, DL));
27870         }
27871         Op = DAG.getBitcast(OpVT, OrigV);
27872         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27873       }
27874   }
27875
27876   return SDValue();
27877 }
27878
27879 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27880                                              DAGCombinerInfo &DCI) const {
27881   SelectionDAG &DAG = DCI.DAG;
27882   switch (N->getOpcode()) {
27883   default: break;
27884   case ISD::EXTRACT_VECTOR_ELT:
27885     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27886   case ISD::VSELECT:
27887   case ISD::SELECT:
27888   case X86ISD::SHRUNKBLEND:
27889     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27890   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
27891   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27892   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
27893   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
27894   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
27895   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
27896   case ISD::SHL:
27897   case ISD::SRA:
27898   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
27899   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
27900   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
27901   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
27902   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
27903   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27904   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
27905   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
27906   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27907   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27908   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
27909   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
27910   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
27911   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
27912   case X86ISD::FXOR:
27913   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
27914   case X86ISD::FMIN:
27915   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
27916   case ISD::FMINNUM:
27917   case ISD::FMAXNUM:        return performFMinNumFMaxNumCombine(N, DAG,
27918                                                                 Subtarget);
27919   case X86ISD::FAND:        return PerformFANDCombine(N, DAG, Subtarget);
27920   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG, Subtarget);
27921   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
27922   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
27923   case ISD::ANY_EXTEND:
27924   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
27925   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
27926   case ISD::SIGN_EXTEND_INREG:
27927     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27928   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
27929   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27930   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27931   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
27932   case X86ISD::SHUFP:       // Handle all target specific shuffles
27933   case X86ISD::PALIGNR:
27934   case X86ISD::UNPCKH:
27935   case X86ISD::UNPCKL:
27936   case X86ISD::MOVHLPS:
27937   case X86ISD::MOVLHPS:
27938   case X86ISD::PSHUFB:
27939   case X86ISD::PSHUFD:
27940   case X86ISD::PSHUFHW:
27941   case X86ISD::PSHUFLW:
27942   case X86ISD::MOVSS:
27943   case X86ISD::MOVSD:
27944   case X86ISD::VPERMILPI:
27945   case X86ISD::VPERM2X128:
27946   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
27947   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
27948   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
27949   case ISD::MGATHER:
27950   case ISD::MSCATTER:       return PerformGatherScatterCombine(N, DAG);
27951   }
27952
27953   return SDValue();
27954 }
27955
27956 /// isTypeDesirableForOp - Return true if the target has native support for
27957 /// the specified value type and it is 'desirable' to use the type for the
27958 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
27959 /// instruction encodings are longer and some i16 instructions are slow.
27960 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
27961   if (!isTypeLegal(VT))
27962     return false;
27963   if (VT != MVT::i16)
27964     return true;
27965
27966   switch (Opc) {
27967   default:
27968     return true;
27969   case ISD::LOAD:
27970   case ISD::SIGN_EXTEND:
27971   case ISD::ZERO_EXTEND:
27972   case ISD::ANY_EXTEND:
27973   case ISD::SHL:
27974   case ISD::SRL:
27975   case ISD::SUB:
27976   case ISD::ADD:
27977   case ISD::MUL:
27978   case ISD::AND:
27979   case ISD::OR:
27980   case ISD::XOR:
27981     return false;
27982   }
27983 }
27984
27985 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
27986 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
27987 /// we don't adjust the stack we clobber the first frame index.
27988 /// See X86InstrInfo::copyPhysReg.
27989 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
27990     MachineFunction *MF) const {
27991   const MachineRegisterInfo &MRI = MF->getRegInfo();
27992
27993   return any_of(MRI.reg_instructions(X86::EFLAGS),
27994                 [](const MachineInstr &RI) { return RI.isCopy(); });
27995 }
27996
27997 /// IsDesirableToPromoteOp - This method query the target whether it is
27998 /// beneficial for dag combiner to promote the specified node. If true, it
27999 /// should return the desired promotion type by reference.
28000 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28001   EVT VT = Op.getValueType();
28002   if (VT != MVT::i16)
28003     return false;
28004
28005   bool Promote = false;
28006   bool Commute = false;
28007   switch (Op.getOpcode()) {
28008   default: break;
28009   case ISD::LOAD: {
28010     LoadSDNode *LD = cast<LoadSDNode>(Op);
28011     // If the non-extending load has a single use and it's not live out, then it
28012     // might be folded.
28013     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28014                                                      Op.hasOneUse()*/) {
28015       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28016              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28017         // The only case where we'd want to promote LOAD (rather then it being
28018         // promoted as an operand is when it's only use is liveout.
28019         if (UI->getOpcode() != ISD::CopyToReg)
28020           return false;
28021       }
28022     }
28023     Promote = true;
28024     break;
28025   }
28026   case ISD::SIGN_EXTEND:
28027   case ISD::ZERO_EXTEND:
28028   case ISD::ANY_EXTEND:
28029     Promote = true;
28030     break;
28031   case ISD::SHL:
28032   case ISD::SRL: {
28033     SDValue N0 = Op.getOperand(0);
28034     // Look out for (store (shl (load), x)).
28035     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28036       return false;
28037     Promote = true;
28038     break;
28039   }
28040   case ISD::ADD:
28041   case ISD::MUL:
28042   case ISD::AND:
28043   case ISD::OR:
28044   case ISD::XOR:
28045     Commute = true;
28046     // fallthrough
28047   case ISD::SUB: {
28048     SDValue N0 = Op.getOperand(0);
28049     SDValue N1 = Op.getOperand(1);
28050     if (!Commute && MayFoldLoad(N1))
28051       return false;
28052     // Avoid disabling potential load folding opportunities.
28053     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28054       return false;
28055     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28056       return false;
28057     Promote = true;
28058   }
28059   }
28060
28061   PVT = MVT::i32;
28062   return Promote;
28063 }
28064
28065 //===----------------------------------------------------------------------===//
28066 //                           X86 Inline Assembly Support
28067 //===----------------------------------------------------------------------===//
28068
28069 // Helper to match a string separated by whitespace.
28070 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28071   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28072
28073   for (StringRef Piece : Pieces) {
28074     if (!S.startswith(Piece)) // Check if the piece matches.
28075       return false;
28076
28077     S = S.substr(Piece.size());
28078     StringRef::size_type Pos = S.find_first_not_of(" \t");
28079     if (Pos == 0) // We matched a prefix.
28080       return false;
28081
28082     S = S.substr(Pos);
28083   }
28084
28085   return S.empty();
28086 }
28087
28088 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28089
28090   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28091     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28092         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28093         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28094
28095       if (AsmPieces.size() == 3)
28096         return true;
28097       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28098         return true;
28099     }
28100   }
28101   return false;
28102 }
28103
28104 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28105   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28106
28107   std::string AsmStr = IA->getAsmString();
28108
28109   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28110   if (!Ty || Ty->getBitWidth() % 16 != 0)
28111     return false;
28112
28113   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28114   SmallVector<StringRef, 4> AsmPieces;
28115   SplitString(AsmStr, AsmPieces, ";\n");
28116
28117   switch (AsmPieces.size()) {
28118   default: return false;
28119   case 1:
28120     // FIXME: this should verify that we are targeting a 486 or better.  If not,
28121     // we will turn this bswap into something that will be lowered to logical
28122     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
28123     // lower so don't worry about this.
28124     // bswap $0
28125     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28126         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28127         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28128         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28129         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28130         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28131       // No need to check constraints, nothing other than the equivalent of
28132       // "=r,0" would be valid here.
28133       return IntrinsicLowering::LowerToByteSwap(CI);
28134     }
28135
28136     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
28137     if (CI->getType()->isIntegerTy(16) &&
28138         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28139         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28140          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28141       AsmPieces.clear();
28142       StringRef ConstraintsStr = IA->getConstraintString();
28143       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28144       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28145       if (clobbersFlagRegisters(AsmPieces))
28146         return IntrinsicLowering::LowerToByteSwap(CI);
28147     }
28148     break;
28149   case 3:
28150     if (CI->getType()->isIntegerTy(32) &&
28151         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28152         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28153         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28154         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28155       AsmPieces.clear();
28156       StringRef ConstraintsStr = IA->getConstraintString();
28157       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28158       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28159       if (clobbersFlagRegisters(AsmPieces))
28160         return IntrinsicLowering::LowerToByteSwap(CI);
28161     }
28162
28163     if (CI->getType()->isIntegerTy(64)) {
28164       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28165       if (Constraints.size() >= 2 &&
28166           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28167           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28168         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
28169         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28170             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28171             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28172           return IntrinsicLowering::LowerToByteSwap(CI);
28173       }
28174     }
28175     break;
28176   }
28177   return false;
28178 }
28179
28180 /// getConstraintType - Given a constraint letter, return the type of
28181 /// constraint it is for this target.
28182 X86TargetLowering::ConstraintType
28183 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28184   if (Constraint.size() == 1) {
28185     switch (Constraint[0]) {
28186     case 'R':
28187     case 'q':
28188     case 'Q':
28189     case 'f':
28190     case 't':
28191     case 'u':
28192     case 'y':
28193     case 'x':
28194     case 'Y':
28195     case 'l':
28196       return C_RegisterClass;
28197     case 'a':
28198     case 'b':
28199     case 'c':
28200     case 'd':
28201     case 'S':
28202     case 'D':
28203     case 'A':
28204       return C_Register;
28205     case 'I':
28206     case 'J':
28207     case 'K':
28208     case 'L':
28209     case 'M':
28210     case 'N':
28211     case 'G':
28212     case 'C':
28213     case 'e':
28214     case 'Z':
28215       return C_Other;
28216     default:
28217       break;
28218     }
28219   }
28220   return TargetLowering::getConstraintType(Constraint);
28221 }
28222
28223 /// Examine constraint type and operand type and determine a weight value.
28224 /// This object must already have been set up with the operand type
28225 /// and the current alternative constraint selected.
28226 TargetLowering::ConstraintWeight
28227   X86TargetLowering::getSingleConstraintMatchWeight(
28228     AsmOperandInfo &info, const char *constraint) const {
28229   ConstraintWeight weight = CW_Invalid;
28230   Value *CallOperandVal = info.CallOperandVal;
28231     // If we don't have a value, we can't do a match,
28232     // but allow it at the lowest weight.
28233   if (!CallOperandVal)
28234     return CW_Default;
28235   Type *type = CallOperandVal->getType();
28236   // Look at the constraint type.
28237   switch (*constraint) {
28238   default:
28239     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28240   case 'R':
28241   case 'q':
28242   case 'Q':
28243   case 'a':
28244   case 'b':
28245   case 'c':
28246   case 'd':
28247   case 'S':
28248   case 'D':
28249   case 'A':
28250     if (CallOperandVal->getType()->isIntegerTy())
28251       weight = CW_SpecificReg;
28252     break;
28253   case 'f':
28254   case 't':
28255   case 'u':
28256     if (type->isFloatingPointTy())
28257       weight = CW_SpecificReg;
28258     break;
28259   case 'y':
28260     if (type->isX86_MMXTy() && Subtarget->hasMMX())
28261       weight = CW_SpecificReg;
28262     break;
28263   case 'x':
28264   case 'Y':
28265     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28266         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28267       weight = CW_Register;
28268     break;
28269   case 'I':
28270     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28271       if (C->getZExtValue() <= 31)
28272         weight = CW_Constant;
28273     }
28274     break;
28275   case 'J':
28276     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28277       if (C->getZExtValue() <= 63)
28278         weight = CW_Constant;
28279     }
28280     break;
28281   case 'K':
28282     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28283       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28284         weight = CW_Constant;
28285     }
28286     break;
28287   case 'L':
28288     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28289       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28290         weight = CW_Constant;
28291     }
28292     break;
28293   case 'M':
28294     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28295       if (C->getZExtValue() <= 3)
28296         weight = CW_Constant;
28297     }
28298     break;
28299   case 'N':
28300     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28301       if (C->getZExtValue() <= 0xff)
28302         weight = CW_Constant;
28303     }
28304     break;
28305   case 'G':
28306   case 'C':
28307     if (isa<ConstantFP>(CallOperandVal)) {
28308       weight = CW_Constant;
28309     }
28310     break;
28311   case 'e':
28312     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28313       if ((C->getSExtValue() >= -0x80000000LL) &&
28314           (C->getSExtValue() <= 0x7fffffffLL))
28315         weight = CW_Constant;
28316     }
28317     break;
28318   case 'Z':
28319     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28320       if (C->getZExtValue() <= 0xffffffff)
28321         weight = CW_Constant;
28322     }
28323     break;
28324   }
28325   return weight;
28326 }
28327
28328 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28329 /// with another that has more specific requirements based on the type of the
28330 /// corresponding operand.
28331 const char *X86TargetLowering::
28332 LowerXConstraint(EVT ConstraintVT) const {
28333   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28334   // 'f' like normal targets.
28335   if (ConstraintVT.isFloatingPoint()) {
28336     if (Subtarget->hasSSE2())
28337       return "Y";
28338     if (Subtarget->hasSSE1())
28339       return "x";
28340   }
28341
28342   return TargetLowering::LowerXConstraint(ConstraintVT);
28343 }
28344
28345 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28346 /// vector.  If it is invalid, don't add anything to Ops.
28347 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28348                                                      std::string &Constraint,
28349                                                      std::vector<SDValue>&Ops,
28350                                                      SelectionDAG &DAG) const {
28351   SDValue Result;
28352
28353   // Only support length 1 constraints for now.
28354   if (Constraint.length() > 1) return;
28355
28356   char ConstraintLetter = Constraint[0];
28357   switch (ConstraintLetter) {
28358   default: break;
28359   case 'I':
28360     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28361       if (C->getZExtValue() <= 31) {
28362         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28363                                        Op.getValueType());
28364         break;
28365       }
28366     }
28367     return;
28368   case 'J':
28369     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28370       if (C->getZExtValue() <= 63) {
28371         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28372                                        Op.getValueType());
28373         break;
28374       }
28375     }
28376     return;
28377   case 'K':
28378     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28379       if (isInt<8>(C->getSExtValue())) {
28380         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28381                                        Op.getValueType());
28382         break;
28383       }
28384     }
28385     return;
28386   case 'L':
28387     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28388       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28389           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28390         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28391                                        Op.getValueType());
28392         break;
28393       }
28394     }
28395     return;
28396   case 'M':
28397     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28398       if (C->getZExtValue() <= 3) {
28399         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28400                                        Op.getValueType());
28401         break;
28402       }
28403     }
28404     return;
28405   case 'N':
28406     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28407       if (C->getZExtValue() <= 255) {
28408         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28409                                        Op.getValueType());
28410         break;
28411       }
28412     }
28413     return;
28414   case 'O':
28415     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28416       if (C->getZExtValue() <= 127) {
28417         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28418                                        Op.getValueType());
28419         break;
28420       }
28421     }
28422     return;
28423   case 'e': {
28424     // 32-bit signed value
28425     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28426       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28427                                            C->getSExtValue())) {
28428         // Widen to 64 bits here to get it sign extended.
28429         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28430         break;
28431       }
28432     // FIXME gcc accepts some relocatable values here too, but only in certain
28433     // memory models; it's complicated.
28434     }
28435     return;
28436   }
28437   case 'Z': {
28438     // 32-bit unsigned value
28439     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28440       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28441                                            C->getZExtValue())) {
28442         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28443                                        Op.getValueType());
28444         break;
28445       }
28446     }
28447     // FIXME gcc accepts some relocatable values here too, but only in certain
28448     // memory models; it's complicated.
28449     return;
28450   }
28451   case 'i': {
28452     // Literal immediates are always ok.
28453     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28454       // Widen to 64 bits here to get it sign extended.
28455       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28456       break;
28457     }
28458
28459     // In any sort of PIC mode addresses need to be computed at runtime by
28460     // adding in a register or some sort of table lookup.  These can't
28461     // be used as immediates.
28462     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28463       return;
28464
28465     // If we are in non-pic codegen mode, we allow the address of a global (with
28466     // an optional displacement) to be used with 'i'.
28467     GlobalAddressSDNode *GA = nullptr;
28468     int64_t Offset = 0;
28469
28470     // Match either (GA), (GA+C), (GA+C1+C2), etc.
28471     while (1) {
28472       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28473         Offset += GA->getOffset();
28474         break;
28475       } else if (Op.getOpcode() == ISD::ADD) {
28476         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28477           Offset += C->getZExtValue();
28478           Op = Op.getOperand(0);
28479           continue;
28480         }
28481       } else if (Op.getOpcode() == ISD::SUB) {
28482         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28483           Offset += -C->getZExtValue();
28484           Op = Op.getOperand(0);
28485           continue;
28486         }
28487       }
28488
28489       // Otherwise, this isn't something we can handle, reject it.
28490       return;
28491     }
28492
28493     const GlobalValue *GV = GA->getGlobal();
28494     // If we require an extra load to get this address, as in PIC mode, we
28495     // can't accept it.
28496     if (isGlobalStubReference(
28497             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28498       return;
28499
28500     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28501                                         GA->getValueType(0), Offset);
28502     break;
28503   }
28504   }
28505
28506   if (Result.getNode()) {
28507     Ops.push_back(Result);
28508     return;
28509   }
28510   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28511 }
28512
28513 std::pair<unsigned, const TargetRegisterClass *>
28514 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28515                                                 StringRef Constraint,
28516                                                 MVT VT) const {
28517   // First, see if this is a constraint that directly corresponds to an LLVM
28518   // register class.
28519   if (Constraint.size() == 1) {
28520     // GCC Constraint Letters
28521     switch (Constraint[0]) {
28522     default: break;
28523       // TODO: Slight differences here in allocation order and leaving
28524       // RIP in the class. Do they matter any more here than they do
28525       // in the normal allocation?
28526     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28527       if (Subtarget->is64Bit()) {
28528         if (VT == MVT::i32 || VT == MVT::f32)
28529           return std::make_pair(0U, &X86::GR32RegClass);
28530         if (VT == MVT::i16)
28531           return std::make_pair(0U, &X86::GR16RegClass);
28532         if (VT == MVT::i8 || VT == MVT::i1)
28533           return std::make_pair(0U, &X86::GR8RegClass);
28534         if (VT == MVT::i64 || VT == MVT::f64)
28535           return std::make_pair(0U, &X86::GR64RegClass);
28536         break;
28537       }
28538       // 32-bit fallthrough
28539     case 'Q':   // Q_REGS
28540       if (VT == MVT::i32 || VT == MVT::f32)
28541         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28542       if (VT == MVT::i16)
28543         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28544       if (VT == MVT::i8 || VT == MVT::i1)
28545         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28546       if (VT == MVT::i64)
28547         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28548       break;
28549     case 'r':   // GENERAL_REGS
28550     case 'l':   // INDEX_REGS
28551       if (VT == MVT::i8 || VT == MVT::i1)
28552         return std::make_pair(0U, &X86::GR8RegClass);
28553       if (VT == MVT::i16)
28554         return std::make_pair(0U, &X86::GR16RegClass);
28555       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28556         return std::make_pair(0U, &X86::GR32RegClass);
28557       return std::make_pair(0U, &X86::GR64RegClass);
28558     case 'R':   // LEGACY_REGS
28559       if (VT == MVT::i8 || VT == MVT::i1)
28560         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28561       if (VT == MVT::i16)
28562         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28563       if (VT == MVT::i32 || !Subtarget->is64Bit())
28564         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28565       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28566     case 'f':  // FP Stack registers.
28567       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28568       // value to the correct fpstack register class.
28569       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28570         return std::make_pair(0U, &X86::RFP32RegClass);
28571       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28572         return std::make_pair(0U, &X86::RFP64RegClass);
28573       return std::make_pair(0U, &X86::RFP80RegClass);
28574     case 'y':   // MMX_REGS if MMX allowed.
28575       if (!Subtarget->hasMMX()) break;
28576       return std::make_pair(0U, &X86::VR64RegClass);
28577     case 'Y':   // SSE_REGS if SSE2 allowed
28578       if (!Subtarget->hasSSE2()) break;
28579       // FALL THROUGH.
28580     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28581       if (!Subtarget->hasSSE1()) break;
28582
28583       switch (VT.SimpleTy) {
28584       default: break;
28585       // Scalar SSE types.
28586       case MVT::f32:
28587       case MVT::i32:
28588         return std::make_pair(0U, &X86::FR32RegClass);
28589       case MVT::f64:
28590       case MVT::i64:
28591         return std::make_pair(0U, &X86::FR64RegClass);
28592       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28593       // Vector types.
28594       case MVT::v16i8:
28595       case MVT::v8i16:
28596       case MVT::v4i32:
28597       case MVT::v2i64:
28598       case MVT::v4f32:
28599       case MVT::v2f64:
28600         return std::make_pair(0U, &X86::VR128RegClass);
28601       // AVX types.
28602       case MVT::v32i8:
28603       case MVT::v16i16:
28604       case MVT::v8i32:
28605       case MVT::v4i64:
28606       case MVT::v8f32:
28607       case MVT::v4f64:
28608         return std::make_pair(0U, &X86::VR256RegClass);
28609       case MVT::v8f64:
28610       case MVT::v16f32:
28611       case MVT::v16i32:
28612       case MVT::v8i64:
28613         return std::make_pair(0U, &X86::VR512RegClass);
28614       }
28615       break;
28616     }
28617   }
28618
28619   // Use the default implementation in TargetLowering to convert the register
28620   // constraint into a member of a register class.
28621   std::pair<unsigned, const TargetRegisterClass*> Res;
28622   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28623
28624   // Not found as a standard register?
28625   if (!Res.second) {
28626     // Map st(0) -> st(7) -> ST0
28627     if (Constraint.size() == 7 && Constraint[0] == '{' &&
28628         tolower(Constraint[1]) == 's' &&
28629         tolower(Constraint[2]) == 't' &&
28630         Constraint[3] == '(' &&
28631         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28632         Constraint[5] == ')' &&
28633         Constraint[6] == '}') {
28634
28635       Res.first = X86::FP0+Constraint[4]-'0';
28636       Res.second = &X86::RFP80RegClass;
28637       return Res;
28638     }
28639
28640     // GCC allows "st(0)" to be called just plain "st".
28641     if (StringRef("{st}").equals_lower(Constraint)) {
28642       Res.first = X86::FP0;
28643       Res.second = &X86::RFP80RegClass;
28644       return Res;
28645     }
28646
28647     // flags -> EFLAGS
28648     if (StringRef("{flags}").equals_lower(Constraint)) {
28649       Res.first = X86::EFLAGS;
28650       Res.second = &X86::CCRRegClass;
28651       return Res;
28652     }
28653
28654     // 'A' means EAX + EDX.
28655     if (Constraint == "A") {
28656       Res.first = X86::EAX;
28657       Res.second = &X86::GR32_ADRegClass;
28658       return Res;
28659     }
28660     return Res;
28661   }
28662
28663   // Otherwise, check to see if this is a register class of the wrong value
28664   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28665   // turn into {ax},{dx}.
28666   // MVT::Other is used to specify clobber names.
28667   if (Res.second->hasType(VT) || VT == MVT::Other)
28668     return Res;   // Correct type already, nothing to do.
28669
28670   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28671   // return "eax". This should even work for things like getting 64bit integer
28672   // registers when given an f64 type.
28673   const TargetRegisterClass *Class = Res.second;
28674   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28675       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28676     unsigned Size = VT.getSizeInBits();
28677     if (Size == 1) Size = 8;
28678     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28679     if (DestReg > 0) {
28680       Res.first = DestReg;
28681       Res.second = Size == 8 ? &X86::GR8RegClass
28682                  : Size == 16 ? &X86::GR16RegClass
28683                  : Size == 32 ? &X86::GR32RegClass
28684                  : &X86::GR64RegClass;
28685       assert(Res.second->contains(Res.first) && "Register in register class");
28686     } else {
28687       // No register found/type mismatch.
28688       Res.first = 0;
28689       Res.second = nullptr;
28690     }
28691   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28692              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28693              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28694              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28695              Class == &X86::VR512RegClass) {
28696     // Handle references to XMM physical registers that got mapped into the
28697     // wrong class.  This can happen with constraints like {xmm0} where the
28698     // target independent register mapper will just pick the first match it can
28699     // find, ignoring the required type.
28700
28701     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28702     if (VT == MVT::f32 || VT == MVT::i32)
28703       Res.second = &X86::FR32RegClass;
28704     else if (VT == MVT::f64 || VT == MVT::i64)
28705       Res.second = &X86::FR64RegClass;
28706     else if (X86::VR128RegClass.hasType(VT))
28707       Res.second = &X86::VR128RegClass;
28708     else if (X86::VR256RegClass.hasType(VT))
28709       Res.second = &X86::VR256RegClass;
28710     else if (X86::VR512RegClass.hasType(VT))
28711       Res.second = &X86::VR512RegClass;
28712     else {
28713       // Type mismatch and not a clobber: Return an error;
28714       Res.first = 0;
28715       Res.second = nullptr;
28716     }
28717   }
28718
28719   return Res;
28720 }
28721
28722 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28723                                             const AddrMode &AM, Type *Ty,
28724                                             unsigned AS) const {
28725   // Scaling factors are not free at all.
28726   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28727   // will take 2 allocations in the out of order engine instead of 1
28728   // for plain addressing mode, i.e. inst (reg1).
28729   // E.g.,
28730   // vaddps (%rsi,%drx), %ymm0, %ymm1
28731   // Requires two allocations (one for the load, one for the computation)
28732   // whereas:
28733   // vaddps (%rsi), %ymm0, %ymm1
28734   // Requires just 1 allocation, i.e., freeing allocations for other operations
28735   // and having less micro operations to execute.
28736   //
28737   // For some X86 architectures, this is even worse because for instance for
28738   // stores, the complex addressing mode forces the instruction to use the
28739   // "load" ports instead of the dedicated "store" port.
28740   // E.g., on Haswell:
28741   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28742   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28743   if (isLegalAddressingMode(DL, AM, Ty, AS))
28744     // Scale represents reg2 * scale, thus account for 1
28745     // as soon as we use a second register.
28746     return AM.Scale != 0;
28747   return -1;
28748 }
28749
28750 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28751   // Integer division on x86 is expensive. However, when aggressively optimizing
28752   // for code size, we prefer to use a div instruction, as it is usually smaller
28753   // than the alternative sequence.
28754   // The exception to this is vector division. Since x86 doesn't have vector
28755   // integer division, leaving the division as-is is a loss even in terms of
28756   // size, because it will have to be scalarized, while the alternative code
28757   // sequence can be performed in vector form.
28758   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28759                                    Attribute::MinSize);
28760   return OptSize && !VT.isVector();
28761 }