[X86] Moved lowerVectorShuffleWithUNPCK earlier to make reuse easier. NFCI.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117   }
118
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
168     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
169   } else if (!Subtarget->useSoftFloat()) {
170     // We have an algorithm for SSE2->double, and we turn this into a
171     // 64-bit FILD followed by conditional FADD for other targets.
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173     // We have an algorithm for SSE2, and we turn this into a 64-bit
174     // FILD for other targets.
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
176   }
177
178   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
179   // this operation.
180   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
181   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
182
183   if (!Subtarget->useSoftFloat()) {
184     // SSE has no i16 to fp conversion, only i32
185     if (X86ScalarSSEf32) {
186       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
187       // f32 and f64 cases are Legal, f80 case is not
188       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
189     } else {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
192     }
193   } else {
194     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
195     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
196   }
197
198   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
199   // are Legal, f80 is custom lowered.
200   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
201   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
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 (X86ScalarSSEf32) {
209     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
210     // f32 and f64 cases are Legal, f80 case is not
211     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
212   } else {
213     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
214     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
215   }
216
217   // Handle FP_TO_UINT by promoting the destination to a larger signed
218   // conversion.
219   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
220   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
221   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
222
223   if (Subtarget->is64Bit()) {
224     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
225       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
226       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
227       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
228     } else {
229       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
231     }
232   } else if (!Subtarget->useSoftFloat()) {
233     // Since AVX is a superset of SSE3, only check for SSE here.
234     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
235       // Expand FP_TO_UINT into a select.
236       // FIXME: We would like to use a Custom expander here eventually to do
237       // the optimal thing for SSE vs. the default expansion in the legalizer.
238       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
239     else
240       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
241       // With SSE3 we can use fisttpll to convert to a signed i64; without
242       // SSE, we're stuck with a fistpll.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
244
245     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
246   }
247
248   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
249   if (!X86ScalarSSEf64) {
250     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
251     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
252     if (Subtarget->is64Bit()) {
253       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
254       // Without SSE, i64->f64 goes through memory.
255       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
256     }
257   }
258
259   // Scalar integer divide and remainder are lowered to use operations that
260   // produce two results, to match the available instructions. This exposes
261   // the two-result form to trivial CSE, which is able to combine x/y and x%y
262   // into a single instruction.
263   //
264   // Scalar integer multiply-high is also lowered to use two-result
265   // operations, to match the available instructions. However, plain multiply
266   // (low) operations are left as Legal, as there are single-result
267   // instructions for this in x86. Using the two-result multiply instructions
268   // when both high and low results are needed must be arranged by dagcombine.
269   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
270     MVT VT = IntVTs[i];
271     setOperationAction(ISD::MULHS, VT, Expand);
272     setOperationAction(ISD::MULHU, VT, Expand);
273     setOperationAction(ISD::SDIV, VT, Expand);
274     setOperationAction(ISD::UDIV, VT, Expand);
275     setOperationAction(ISD::SREM, VT, Expand);
276     setOperationAction(ISD::UREM, VT, Expand);
277
278     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
279     setOperationAction(ISD::ADDC, VT, Custom);
280     setOperationAction(ISD::ADDE, VT, Custom);
281     setOperationAction(ISD::SUBC, VT, Custom);
282     setOperationAction(ISD::SUBE, VT, Custom);
283   }
284
285   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
286   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
287   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
288   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
289   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
290   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
291   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
294   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
295   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
296   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
297   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
301   if (Subtarget->is64Bit())
302     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
303   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
304   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
305   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
306   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
307
308   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
309     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
310     // is. We should promote the value to 64-bits to solve this.
311     // This is what the CRT headers do - `fmodf` is an inline header
312     // function casting to f64 and calling `fmod`.
313     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
314   } else {
315     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
316   }
317
318   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
319   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
320   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
321
322   // Promote the i8 variants and force them on up to i32 which has a shorter
323   // encoding.
324   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
326   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
327   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
328   if (Subtarget->hasBMI()) {
329     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
330     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
331     if (Subtarget->is64Bit())
332       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
333   } else {
334     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
335     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
336     if (Subtarget->is64Bit())
337       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
338   }
339
340   if (Subtarget->hasLZCNT()) {
341     // When promoting the i8 variants, force them to i32 for a shorter
342     // encoding.
343     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
346     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
347     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
348     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
349     if (Subtarget->is64Bit())
350       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
351   } else {
352     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
353     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
354     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
356     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
358     if (Subtarget->is64Bit()) {
359       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
360       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
361     }
362   }
363
364   // Special handling for half-precision floating point conversions.
365   // If we don't have F16C support, then lower half float conversions
366   // into library calls.
367   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
368     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
369     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
370   }
371
372   // There's never any support for operations beyond MVT::f32.
373   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
374   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
375   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
376   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
377
378   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
379   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
382   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
383   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
384
385   if (Subtarget->hasPOPCNT()) {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
387   } else {
388     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
389     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
390     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
391     if (Subtarget->is64Bit())
392       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
393   }
394
395   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
396
397   if (!Subtarget->hasMOVBE())
398     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
399
400   // These should be promoted to a larger select which is supported.
401   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
402   // X86 wants to expand cmov itself.
403   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
404   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
407   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
410   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
417     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
418   }
419   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
420   setOperationAction(ISD::CATCHRET        , MVT::Other, Custom);
421   setOperationAction(ISD::CLEANUPRET      , MVT::Other, Custom);
422   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
423   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
424   // support continuation, user-level threading, and etc.. As a result, no
425   // other SjLj exception interfaces are implemented and please don't build
426   // your own exception handling based on them.
427   // LLVM/Clang supports zero-cost DWARF exception handling.
428   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
429   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
430
431   // Darwin ABI issue.
432   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
433   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
434   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
435   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
436   if (Subtarget->is64Bit())
437     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
438   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
439   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
440   if (Subtarget->is64Bit()) {
441     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
442     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
443     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
444     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
445     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
446   }
447   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
448   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
449   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
450   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
453     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
454     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
455   }
456
457   if (Subtarget->hasSSE1())
458     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
459
460   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
461
462   // Expand certain atomics
463   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
464     MVT VT = IntVTs[i];
465     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
466     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
467     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
468   }
469
470   if (Subtarget->hasCmpxchg16b()) {
471     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
472   }
473
474   // FIXME - use subtarget debug flags
475   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
476       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
477     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
478   }
479
480   if (Subtarget->isTarget64BitLP64()) {
481     setExceptionPointerRegister(X86::RAX);
482     setExceptionSelectorRegister(X86::RDX);
483   } else {
484     setExceptionPointerRegister(X86::EAX);
485     setExceptionSelectorRegister(X86::EDX);
486   }
487   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
488   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
489
490   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
491   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
492
493   setOperationAction(ISD::TRAP, MVT::Other, Legal);
494   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
495
496   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
497   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
498   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
499   if (Subtarget->is64Bit()) {
500     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
501     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
502   } else {
503     // TargetInfo::CharPtrBuiltinVaList
504     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
505     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
506   }
507
508   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
509   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
510
511   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
512
513   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
514   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
515   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
516
517   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
518     // f32 and f64 use SSE.
519     // Set up the FP register classes.
520     addRegisterClass(MVT::f32, &X86::FR32RegClass);
521     addRegisterClass(MVT::f64, &X86::FR64RegClass);
522
523     // Use ANDPD to simulate FABS.
524     setOperationAction(ISD::FABS , MVT::f64, Custom);
525     setOperationAction(ISD::FABS , MVT::f32, Custom);
526
527     // Use XORP to simulate FNEG.
528     setOperationAction(ISD::FNEG , MVT::f64, Custom);
529     setOperationAction(ISD::FNEG , MVT::f32, Custom);
530
531     // Use ANDPD and ORPD to simulate FCOPYSIGN.
532     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
533     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
534
535     // Lower this to FGETSIGNx86 plus an AND.
536     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
537     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
538
539     // We don't support sin/cos/fmod
540     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
543     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
546
547     // Expand FP immediates into loads from the stack, except for the special
548     // cases we handle.
549     addLegalFPImmediate(APFloat(+0.0)); // xorpd
550     addLegalFPImmediate(APFloat(+0.0f)); // xorps
551   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
552     // Use SSE for f32, x87 for f64.
553     // Set up the FP register classes.
554     addRegisterClass(MVT::f32, &X86::FR32RegClass);
555     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
556
557     // Use ANDPS to simulate FABS.
558     setOperationAction(ISD::FABS , MVT::f32, Custom);
559
560     // Use XORP to simulate FNEG.
561     setOperationAction(ISD::FNEG , MVT::f32, Custom);
562
563     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
564
565     // Use ANDPS and ORPS to simulate FCOPYSIGN.
566     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
567     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
568
569     // We don't support sin/cos/fmod
570     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
571     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
572     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
573
574     // Special cases we handle for FP constants.
575     addLegalFPImmediate(APFloat(+0.0f)); // xorps
576     addLegalFPImmediate(APFloat(+0.0)); // FLD0
577     addLegalFPImmediate(APFloat(+1.0)); // FLD1
578     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
579     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
580
581     if (!TM.Options.UnsafeFPMath) {
582       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
583       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
584       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
585     }
586   } else if (!Subtarget->useSoftFloat()) {
587     // f32 and f64 in x87.
588     // Set up the FP register classes.
589     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
590     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
591
592     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
593     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
596
597     if (!TM.Options.UnsafeFPMath) {
598       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
599       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
601       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
603       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
604     }
605     addLegalFPImmediate(APFloat(+0.0)); // FLD0
606     addLegalFPImmediate(APFloat(+1.0)); // FLD1
607     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
608     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
609     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
610     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
611     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
612     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
613   }
614
615   // We don't support FMA.
616   setOperationAction(ISD::FMA, MVT::f64, Expand);
617   setOperationAction(ISD::FMA, MVT::f32, Expand);
618
619   // Long double always uses X87.
620   if (!Subtarget->useSoftFloat()) {
621     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
622     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
623     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
624     {
625       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
626       addLegalFPImmediate(TmpFlt);  // FLD0
627       TmpFlt.changeSign();
628       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
629
630       bool ignored;
631       APFloat TmpFlt2(+1.0);
632       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
633                       &ignored);
634       addLegalFPImmediate(TmpFlt2);  // FLD1
635       TmpFlt2.changeSign();
636       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
637     }
638
639     if (!TM.Options.UnsafeFPMath) {
640       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
641       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
642       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
643     }
644
645     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
646     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
647     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
648     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
649     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
650     setOperationAction(ISD::FMA, MVT::f80, Expand);
651   }
652
653   // Always use a library call for pow.
654   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
656   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
657
658   setOperationAction(ISD::FLOG, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
660   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP, MVT::f80, Expand);
662   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
663   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
664   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
665
666   // First set operation action for all vector types to either promote
667   // (for widening) or expand (for scalarization). Then we will selectively
668   // turn on ones that can be effectively codegen'd.
669   for (MVT VT : MVT::vector_valuetypes()) {
670     setOperationAction(ISD::ADD , VT, Expand);
671     setOperationAction(ISD::SUB , VT, Expand);
672     setOperationAction(ISD::FADD, VT, Expand);
673     setOperationAction(ISD::FNEG, VT, Expand);
674     setOperationAction(ISD::FSUB, VT, Expand);
675     setOperationAction(ISD::MUL , VT, Expand);
676     setOperationAction(ISD::FMUL, VT, Expand);
677     setOperationAction(ISD::SDIV, VT, Expand);
678     setOperationAction(ISD::UDIV, VT, Expand);
679     setOperationAction(ISD::FDIV, VT, Expand);
680     setOperationAction(ISD::SREM, VT, Expand);
681     setOperationAction(ISD::UREM, VT, Expand);
682     setOperationAction(ISD::LOAD, VT, Expand);
683     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
684     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
685     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
686     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
688     setOperationAction(ISD::FABS, VT, Expand);
689     setOperationAction(ISD::FSIN, VT, Expand);
690     setOperationAction(ISD::FSINCOS, VT, Expand);
691     setOperationAction(ISD::FCOS, VT, Expand);
692     setOperationAction(ISD::FSINCOS, VT, Expand);
693     setOperationAction(ISD::FREM, VT, Expand);
694     setOperationAction(ISD::FMA,  VT, Expand);
695     setOperationAction(ISD::FPOWI, VT, Expand);
696     setOperationAction(ISD::FSQRT, VT, Expand);
697     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
698     setOperationAction(ISD::FFLOOR, VT, Expand);
699     setOperationAction(ISD::FCEIL, VT, Expand);
700     setOperationAction(ISD::FTRUNC, VT, Expand);
701     setOperationAction(ISD::FRINT, VT, Expand);
702     setOperationAction(ISD::FNEARBYINT, VT, Expand);
703     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
704     setOperationAction(ISD::MULHS, VT, Expand);
705     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
706     setOperationAction(ISD::MULHU, VT, Expand);
707     setOperationAction(ISD::SDIVREM, VT, Expand);
708     setOperationAction(ISD::UDIVREM, VT, Expand);
709     setOperationAction(ISD::FPOW, VT, Expand);
710     setOperationAction(ISD::CTPOP, VT, Expand);
711     setOperationAction(ISD::CTTZ, VT, Expand);
712     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
713     setOperationAction(ISD::CTLZ, VT, Expand);
714     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
715     setOperationAction(ISD::SHL, VT, Expand);
716     setOperationAction(ISD::SRA, VT, Expand);
717     setOperationAction(ISD::SRL, VT, Expand);
718     setOperationAction(ISD::ROTL, VT, Expand);
719     setOperationAction(ISD::ROTR, VT, Expand);
720     setOperationAction(ISD::BSWAP, VT, Expand);
721     setOperationAction(ISD::SETCC, VT, Expand);
722     setOperationAction(ISD::FLOG, VT, Expand);
723     setOperationAction(ISD::FLOG2, VT, Expand);
724     setOperationAction(ISD::FLOG10, VT, Expand);
725     setOperationAction(ISD::FEXP, VT, Expand);
726     setOperationAction(ISD::FEXP2, VT, Expand);
727     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
728     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
729     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
730     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
731     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
732     setOperationAction(ISD::TRUNCATE, VT, Expand);
733     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
734     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
735     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
736     setOperationAction(ISD::VSELECT, VT, Expand);
737     setOperationAction(ISD::SELECT_CC, VT, Expand);
738     for (MVT InnerVT : MVT::vector_valuetypes()) {
739       setTruncStoreAction(InnerVT, VT, Expand);
740
741       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
742       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
743
744       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
745       // types, we have to deal with them whether we ask for Expansion or not.
746       // Setting Expand causes its own optimisation problems though, so leave
747       // them legal.
748       if (VT.getVectorElementType() == MVT::i1)
749         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
750
751       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
752       // split/scalarized right now.
753       if (VT.getVectorElementType() == MVT::f16)
754         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
755     }
756   }
757
758   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
759   // with -msoft-float, disable use of MMX as well.
760   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
761     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
762     // No operations on x86mmx supported, everything uses intrinsics.
763   }
764
765   // MMX-sized vectors (other than x86mmx) are expected to be expanded
766   // into smaller operations.
767   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
768     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
769     setOperationAction(ISD::AND,                MMXTy,      Expand);
770     setOperationAction(ISD::OR,                 MMXTy,      Expand);
771     setOperationAction(ISD::XOR,                MMXTy,      Expand);
772     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
773     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
774     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
775   }
776   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
777
778   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
779     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
780
781     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
786     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
787     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
788     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
789     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
790     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
791     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
792     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
793     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
794     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
795   }
796
797   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
798     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
799
800     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
801     // registers cannot be used even for integer operations.
802     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
803     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
804     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
805     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
806
807     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
808     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
809     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
810     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
811     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
812     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
813     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
814     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
815     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
816     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
817     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
818     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
819     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
820     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
821     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
822     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
823     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
828     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
829     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
830
831     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
832     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
833     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
834     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
835
836     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
838     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
839     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
840
841     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
842     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
846
847     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
848     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
849     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
850     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
851
852     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
853     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
854       MVT VT = (MVT::SimpleValueType)i;
855       // Do not attempt to custom lower non-power-of-2 vectors
856       if (!isPowerOf2_32(VT.getVectorNumElements()))
857         continue;
858       // Do not attempt to custom lower non-128-bit vectors
859       if (!VT.is128BitVector())
860         continue;
861       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
862       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
863       setOperationAction(ISD::VSELECT,            VT, Custom);
864       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
865     }
866
867     // We support custom legalizing of sext and anyext loads for specific
868     // memory vector types which we can load as a scalar (or sequence of
869     // scalars) and extend in-register to a legal 128-bit vector type. For sext
870     // loads these must work with a single scalar load.
871     for (MVT VT : MVT::integer_vector_valuetypes()) {
872       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
881     }
882
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
885     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
887     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
889     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
890     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
891
892     if (Subtarget->is64Bit()) {
893       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
894       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
895     }
896
897     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
898     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
899       MVT VT = (MVT::SimpleValueType)i;
900
901       // Do not attempt to promote non-128-bit vectors
902       if (!VT.is128BitVector())
903         continue;
904
905       setOperationAction(ISD::AND,    VT, Promote);
906       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
907       setOperationAction(ISD::OR,     VT, Promote);
908       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
909       setOperationAction(ISD::XOR,    VT, Promote);
910       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
911       setOperationAction(ISD::LOAD,   VT, Promote);
912       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
913       setOperationAction(ISD::SELECT, VT, Promote);
914       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
915     }
916
917     // Custom lower v2i64 and v2f64 selects.
918     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
919     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
920     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
921     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
922
923     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
924     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
925
926     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
927
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
929     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
930     // As there is no 64-bit GPR available, we need build a special custom
931     // sequence to convert from v2i32 to v2f32.
932     if (!Subtarget->is64Bit())
933       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
934
935     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
936     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
937
938     for (MVT VT : MVT::fp_vector_valuetypes())
939       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
940
941     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
943     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
944   }
945
946   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
947     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
948       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
949       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
950       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
951       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
952       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
953     }
954
955     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
956     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
957     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
958     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
959     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
960     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
961     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
962     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
963
964     // FIXME: Do we need to handle scalar-to-vector here?
965     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
966
967     // We directly match byte blends in the backend as they match the VSELECT
968     // condition form.
969     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
970
971     // SSE41 brings specific instructions for doing vector sign extend even in
972     // cases where we don't have SRA.
973     for (MVT VT : MVT::integer_vector_valuetypes()) {
974       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
975       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
976       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
977     }
978
979     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
983     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
986
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
990     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
991     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
992     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
993
994     // i8 and i16 vectors are custom because the source register and source
995     // source memory operand types are not the same width.  f32 vectors are
996     // custom since the immediate controlling the insert encodes additional
997     // information.
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
999     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1001     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1002
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1005     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1006     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1007
1008     // FIXME: these should be Legal, but that's only for the case where
1009     // the index is constant.  For now custom expand to deal with that.
1010     if (Subtarget->is64Bit()) {
1011       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1012       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1013     }
1014   }
1015
1016   if (Subtarget->hasSSE2()) {
1017     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1018     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1019     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1020
1021     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1026
1027     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1028     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1029
1030     // In the customized shift lowering, the legal cases in AVX2 will be
1031     // recognized.
1032     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1037
1038     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1039     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1040   }
1041
1042   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1043     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1045     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1046     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1047     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1048     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1049
1050     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1052     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1053
1054     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1056     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1057     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1058     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1059     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1060     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1061     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1062     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1063     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1064     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1065     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1066
1067     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1069     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1070     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1071     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1072     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1073     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1074     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1075     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1076     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1077     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1078     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1079
1080     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1081     // even though v8i16 is a legal type.
1082     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1083     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1085
1086     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1087     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1088     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1089
1090     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1091     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1092
1093     for (MVT VT : MVT::fp_vector_valuetypes())
1094       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1095
1096     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1103     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1104
1105     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1106     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1107     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1108     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1109
1110     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1111     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1112     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1113
1114     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1118     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1119     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1120     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1121     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1122     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1123     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1124     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1125     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1126
1127     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1128     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1129     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1130     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1131
1132     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1133       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1134       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1135       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1136       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1137       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1138       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1139     }
1140
1141     if (Subtarget->hasInt256()) {
1142       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1143       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1144       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1145       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1146
1147       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1148       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1149       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1150       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1151
1152       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1153       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1154       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1155       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1156
1157       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1158       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1159       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1160       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1161
1162       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1171       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1172       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1173       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1174
1175       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1176       // when we have a 256bit-wide blend with immediate.
1177       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1178
1179       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1183       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1184       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1185       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1186
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1190       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1191       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1192       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1193     } else {
1194       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1195       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1197       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1198
1199       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1200       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1202       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1203
1204       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1205       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1206       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1207       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1208
1209       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1210       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1211       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1212       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1213       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1214       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1215       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1216       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1217       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1218       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1219       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1220       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1221     }
1222
1223     // In the customized shift lowering, the legal cases in AVX2 will be
1224     // recognized.
1225     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1226     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1227
1228     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1229     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1230
1231     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1232     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1233
1234     // Custom lower several nodes for 256-bit types.
1235     for (MVT VT : MVT::vector_valuetypes()) {
1236       if (VT.getScalarSizeInBits() >= 32) {
1237         setOperationAction(ISD::MLOAD,  VT, Legal);
1238         setOperationAction(ISD::MSTORE, VT, Legal);
1239       }
1240       // Extract subvector is special because the value type
1241       // (result) is 128-bit but the source is 256-bit wide.
1242       if (VT.is128BitVector()) {
1243         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1244       }
1245       // Do not attempt to custom lower other non-256-bit vectors
1246       if (!VT.is256BitVector())
1247         continue;
1248
1249       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1250       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1251       setOperationAction(ISD::VSELECT,            VT, Custom);
1252       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1253       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1254       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1255       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1256       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1257     }
1258
1259     if (Subtarget->hasInt256())
1260       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1261
1262
1263     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1264     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1265       MVT VT = (MVT::SimpleValueType)i;
1266
1267       // Do not attempt to promote non-256-bit vectors
1268       if (!VT.is256BitVector())
1269         continue;
1270
1271       setOperationAction(ISD::AND,    VT, Promote);
1272       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1273       setOperationAction(ISD::OR,     VT, Promote);
1274       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1275       setOperationAction(ISD::XOR,    VT, Promote);
1276       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1277       setOperationAction(ISD::LOAD,   VT, Promote);
1278       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1279       setOperationAction(ISD::SELECT, VT, Promote);
1280       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1281     }
1282   }
1283
1284   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1285     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1286     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1287     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1288     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1289
1290     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1291     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1292     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1293
1294     for (MVT VT : MVT::fp_vector_valuetypes())
1295       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1296
1297     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1298     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1299     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1300     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1301     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1302     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1303     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1304     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1305     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1306     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1307     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1308     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1309
1310     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1311     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1312     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1313     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1314     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1315     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1316     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1317     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1318     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1323
1324     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1329     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1330
1331     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1336     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1337     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1338     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1339
1340     // FIXME:  [US]INT_TO_FP are not legal for f80.
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1342     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1343     if (Subtarget->is64Bit()) {
1344       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1345       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1346     }
1347     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1349     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1350     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1352     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1355     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1360     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1361     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1362     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1363
1364     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1365     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1366     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1367     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1368     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1369     if (Subtarget->hasVLX()){
1370       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1371       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1372       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1373       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1374       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1375
1376       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1377       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1378       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1379       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1380       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1381     }
1382     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1383     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1384     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1385     if (Subtarget->hasDQI()) {
1386       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1387       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1388
1389       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1390       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1391       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1392       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1393       if (Subtarget->hasVLX()) {
1394         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1395         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1396         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1397         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1398         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1399         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1400         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1401         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1402       }
1403     }
1404     if (Subtarget->hasVLX()) {
1405       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1406       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1407       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1408       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1411       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1412       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1413     }
1414     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1415     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1416     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1417     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1418     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1419     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1420     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1421     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1422     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1423     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1424     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1425     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1426     if (Subtarget->hasDQI()) {
1427       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1428       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1429     }
1430     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1431     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1432     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1433     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1434     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1435     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1436     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1437     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1438     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1439     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1440
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1445     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1446
1447     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1448     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1449
1450     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1451
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1453     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1455     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1457     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1460     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1461     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1462     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1463
1464     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1465     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1466     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1467     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1468     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1469     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1470     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1471     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1472
1473     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1474     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1475
1476     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1477     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1478
1479     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1480
1481     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1482     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1483
1484     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1485     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1486
1487     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1488     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1489
1490     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1491     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1492     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1493     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1494     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1495     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1496
1497     if (Subtarget->hasCDI()) {
1498       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1499       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1500       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64, Legal);
1501       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1502     }
1503     if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1504       setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1505       setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1506       setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1507       setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1508       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1509       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1510       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1511       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1512     }
1513     if (Subtarget->hasDQI()) {
1514       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1515       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1516       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1517     }
1518     // Custom lower several nodes.
1519     for (MVT VT : MVT::vector_valuetypes()) {
1520       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1521       if (EltSize == 1) {
1522         setOperationAction(ISD::AND, VT, Legal);
1523         setOperationAction(ISD::OR,  VT, Legal);
1524         setOperationAction(ISD::XOR,  VT, Legal);
1525       }
1526       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1527         setOperationAction(ISD::MGATHER,  VT, Custom);
1528         setOperationAction(ISD::MSCATTER, VT, Custom);
1529       }
1530       // Extract subvector is special because the value type
1531       // (result) is 256/128-bit but the source is 512-bit wide.
1532       if (VT.is128BitVector() || VT.is256BitVector()) {
1533         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1534       }
1535       if (VT.getVectorElementType() == MVT::i1)
1536         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1537
1538       // Do not attempt to custom lower other non-512-bit vectors
1539       if (!VT.is512BitVector())
1540         continue;
1541
1542       if (EltSize >= 32) {
1543         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1544         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1545         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1546         setOperationAction(ISD::VSELECT,             VT, Legal);
1547         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1548         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1549         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1550         setOperationAction(ISD::MLOAD,               VT, Legal);
1551         setOperationAction(ISD::MSTORE,              VT, Legal);
1552       }
1553     }
1554     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1555       MVT VT = (MVT::SimpleValueType)i;
1556
1557       // Do not attempt to promote non-512-bit vectors.
1558       if (!VT.is512BitVector())
1559         continue;
1560
1561       setOperationAction(ISD::SELECT, VT, Promote);
1562       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1563     }
1564   }// has  AVX-512
1565
1566   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1567     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1568     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1569
1570     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1571     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1572
1573     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1574     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1575     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1576     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1577     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1578     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1579     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1580     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1581     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1582     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1583     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1584     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1585     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1586     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1587     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1588     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1589     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1590     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1591     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1592     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1593     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1594     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1595     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1596     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1597     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1598     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1599     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1600     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1601     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1602     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1603     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1604
1605     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1606     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1607     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1608     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1609     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1610     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1611     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1612     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1613
1614     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1615     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1616     if (Subtarget->hasVLX())
1617       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1618
1619     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1620       const MVT VT = (MVT::SimpleValueType)i;
1621
1622       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1623
1624       // Do not attempt to promote non-512-bit vectors.
1625       if (!VT.is512BitVector())
1626         continue;
1627
1628       if (EltSize < 32) {
1629         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1630         setOperationAction(ISD::VSELECT,             VT, Legal);
1631       }
1632     }
1633   }
1634
1635   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1636     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1637     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1638
1639     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1640     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1641     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1642     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1644     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1645     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1646     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1647     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1648     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1649
1650     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1651     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1652     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1653     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1654     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1655     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1656     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1657     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1658
1659     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1660     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1661     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1662     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1663     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1664     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1665     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1666     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1667   }
1668
1669   // We want to custom lower some of our intrinsics.
1670   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1671   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1672   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1673   if (!Subtarget->is64Bit())
1674     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1675
1676   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1677   // handle type legalization for these operations here.
1678   //
1679   // FIXME: We really should do custom legalization for addition and
1680   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1681   // than generic legalization for 64-bit multiplication-with-overflow, though.
1682   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1683     // Add/Sub/Mul with overflow operations are custom lowered.
1684     MVT VT = IntVTs[i];
1685     setOperationAction(ISD::SADDO, VT, Custom);
1686     setOperationAction(ISD::UADDO, VT, Custom);
1687     setOperationAction(ISD::SSUBO, VT, Custom);
1688     setOperationAction(ISD::USUBO, VT, Custom);
1689     setOperationAction(ISD::SMULO, VT, Custom);
1690     setOperationAction(ISD::UMULO, VT, Custom);
1691   }
1692
1693
1694   if (!Subtarget->is64Bit()) {
1695     // These libcalls are not available in 32-bit.
1696     setLibcallName(RTLIB::SHL_I128, nullptr);
1697     setLibcallName(RTLIB::SRL_I128, nullptr);
1698     setLibcallName(RTLIB::SRA_I128, nullptr);
1699   }
1700
1701   // Combine sin / cos into one node or libcall if possible.
1702   if (Subtarget->hasSinCos()) {
1703     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1704     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1705     if (Subtarget->isTargetDarwin()) {
1706       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1707       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1708       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1709       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1710     }
1711   }
1712
1713   if (Subtarget->isTargetWin64()) {
1714     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1715     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1716     setOperationAction(ISD::SREM, MVT::i128, Custom);
1717     setOperationAction(ISD::UREM, MVT::i128, Custom);
1718     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1719     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1720   }
1721
1722   // We have target-specific dag combine patterns for the following nodes:
1723   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1724   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1725   setTargetDAGCombine(ISD::BITCAST);
1726   setTargetDAGCombine(ISD::VSELECT);
1727   setTargetDAGCombine(ISD::SELECT);
1728   setTargetDAGCombine(ISD::SHL);
1729   setTargetDAGCombine(ISD::SRA);
1730   setTargetDAGCombine(ISD::SRL);
1731   setTargetDAGCombine(ISD::OR);
1732   setTargetDAGCombine(ISD::AND);
1733   setTargetDAGCombine(ISD::ADD);
1734   setTargetDAGCombine(ISD::FADD);
1735   setTargetDAGCombine(ISD::FSUB);
1736   setTargetDAGCombine(ISD::FMA);
1737   setTargetDAGCombine(ISD::SUB);
1738   setTargetDAGCombine(ISD::LOAD);
1739   setTargetDAGCombine(ISD::MLOAD);
1740   setTargetDAGCombine(ISD::STORE);
1741   setTargetDAGCombine(ISD::MSTORE);
1742   setTargetDAGCombine(ISD::ZERO_EXTEND);
1743   setTargetDAGCombine(ISD::ANY_EXTEND);
1744   setTargetDAGCombine(ISD::SIGN_EXTEND);
1745   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1746   setTargetDAGCombine(ISD::SINT_TO_FP);
1747   setTargetDAGCombine(ISD::UINT_TO_FP);
1748   setTargetDAGCombine(ISD::SETCC);
1749   setTargetDAGCombine(ISD::BUILD_VECTOR);
1750   setTargetDAGCombine(ISD::MUL);
1751   setTargetDAGCombine(ISD::XOR);
1752
1753   computeRegisterProperties(Subtarget->getRegisterInfo());
1754
1755   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1756   MaxStoresPerMemsetOptSize = 8;
1757   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1758   MaxStoresPerMemcpyOptSize = 4;
1759   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1760   MaxStoresPerMemmoveOptSize = 4;
1761   setPrefLoopAlignment(4); // 2^4 bytes.
1762
1763   // Predictable cmov don't hurt on atom because it's in-order.
1764   PredictableSelectIsExpensive = !Subtarget->isAtom();
1765   EnableExtLdPromotion = true;
1766   setPrefFunctionAlignment(4); // 2^4 bytes.
1767
1768   verifyIntrinsicTables();
1769 }
1770
1771 // This has so far only been implemented for 64-bit MachO.
1772 bool X86TargetLowering::useLoadStackGuardNode() const {
1773   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1774 }
1775
1776 TargetLoweringBase::LegalizeTypeAction
1777 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1778   if (ExperimentalVectorWideningLegalization &&
1779       VT.getVectorNumElements() != 1 &&
1780       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1781     return TypeWidenVector;
1782
1783   return TargetLoweringBase::getPreferredVectorAction(VT);
1784 }
1785
1786 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1787                                           EVT VT) const {
1788   if (!VT.isVector())
1789     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1790
1791   const unsigned NumElts = VT.getVectorNumElements();
1792   const EVT EltVT = VT.getVectorElementType();
1793   if (VT.is512BitVector()) {
1794     if (Subtarget->hasAVX512())
1795       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1796           EltVT == MVT::f32 || EltVT == MVT::f64)
1797         switch(NumElts) {
1798         case  8: return MVT::v8i1;
1799         case 16: return MVT::v16i1;
1800       }
1801     if (Subtarget->hasBWI())
1802       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1803         switch(NumElts) {
1804         case 32: return MVT::v32i1;
1805         case 64: return MVT::v64i1;
1806       }
1807   }
1808
1809   if (VT.is256BitVector() || VT.is128BitVector()) {
1810     if (Subtarget->hasVLX())
1811       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1812           EltVT == MVT::f32 || EltVT == MVT::f64)
1813         switch(NumElts) {
1814         case 2: return MVT::v2i1;
1815         case 4: return MVT::v4i1;
1816         case 8: return MVT::v8i1;
1817       }
1818     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1819       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1820         switch(NumElts) {
1821         case  8: return MVT::v8i1;
1822         case 16: return MVT::v16i1;
1823         case 32: return MVT::v32i1;
1824       }
1825   }
1826
1827   return VT.changeVectorElementTypeToInteger();
1828 }
1829
1830 /// Helper for getByValTypeAlignment to determine
1831 /// the desired ByVal argument alignment.
1832 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1833   if (MaxAlign == 16)
1834     return;
1835   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1836     if (VTy->getBitWidth() == 128)
1837       MaxAlign = 16;
1838   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1839     unsigned EltAlign = 0;
1840     getMaxByValAlign(ATy->getElementType(), EltAlign);
1841     if (EltAlign > MaxAlign)
1842       MaxAlign = EltAlign;
1843   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1844     for (auto *EltTy : STy->elements()) {
1845       unsigned EltAlign = 0;
1846       getMaxByValAlign(EltTy, EltAlign);
1847       if (EltAlign > MaxAlign)
1848         MaxAlign = EltAlign;
1849       if (MaxAlign == 16)
1850         break;
1851     }
1852   }
1853 }
1854
1855 /// Return the desired alignment for ByVal aggregate
1856 /// function arguments in the caller parameter area. For X86, aggregates
1857 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1858 /// are at 4-byte boundaries.
1859 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1860                                                   const DataLayout &DL) const {
1861   if (Subtarget->is64Bit()) {
1862     // Max of 8 and alignment of type.
1863     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1864     if (TyAlign > 8)
1865       return TyAlign;
1866     return 8;
1867   }
1868
1869   unsigned Align = 4;
1870   if (Subtarget->hasSSE1())
1871     getMaxByValAlign(Ty, Align);
1872   return Align;
1873 }
1874
1875 /// Returns the target specific optimal type for load
1876 /// and store operations as a result of memset, memcpy, and memmove
1877 /// lowering. If DstAlign is zero that means it's safe to destination
1878 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1879 /// means there isn't a need to check it against alignment requirement,
1880 /// probably because the source does not need to be loaded. If 'IsMemset' is
1881 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1882 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1883 /// source is constant so it does not need to be loaded.
1884 /// It returns EVT::Other if the type should be determined using generic
1885 /// target-independent logic.
1886 EVT
1887 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1888                                        unsigned DstAlign, unsigned SrcAlign,
1889                                        bool IsMemset, bool ZeroMemset,
1890                                        bool MemcpyStrSrc,
1891                                        MachineFunction &MF) const {
1892   const Function *F = MF.getFunction();
1893   if ((!IsMemset || ZeroMemset) &&
1894       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1895     if (Size >= 16 &&
1896         (!Subtarget->isUnalignedMem16Slow() ||
1897          ((DstAlign == 0 || DstAlign >= 16) &&
1898           (SrcAlign == 0 || SrcAlign >= 16)))) {
1899       if (Size >= 32) {
1900         // FIXME: Check if unaligned 32-byte accesses are slow.
1901         if (Subtarget->hasInt256())
1902           return MVT::v8i32;
1903         if (Subtarget->hasFp256())
1904           return MVT::v8f32;
1905       }
1906       if (Subtarget->hasSSE2())
1907         return MVT::v4i32;
1908       if (Subtarget->hasSSE1())
1909         return MVT::v4f32;
1910     } else if (!MemcpyStrSrc && Size >= 8 &&
1911                !Subtarget->is64Bit() &&
1912                Subtarget->hasSSE2()) {
1913       // Do not use f64 to lower memcpy if source is string constant. It's
1914       // better to use i32 to avoid the loads.
1915       return MVT::f64;
1916     }
1917   }
1918   // This is a compromise. If we reach here, unaligned accesses may be slow on
1919   // this target. However, creating smaller, aligned accesses could be even
1920   // slower and would certainly be a lot more code.
1921   if (Subtarget->is64Bit() && Size >= 8)
1922     return MVT::i64;
1923   return MVT::i32;
1924 }
1925
1926 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1927   if (VT == MVT::f32)
1928     return X86ScalarSSEf32;
1929   else if (VT == MVT::f64)
1930     return X86ScalarSSEf64;
1931   return true;
1932 }
1933
1934 bool
1935 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1936                                                   unsigned,
1937                                                   unsigned,
1938                                                   bool *Fast) const {
1939   if (Fast) {
1940     switch (VT.getSizeInBits()) {
1941     default:
1942       // 8-byte and under are always assumed to be fast.
1943       *Fast = true;
1944       break;
1945     case 128:
1946       *Fast = !Subtarget->isUnalignedMem16Slow();
1947       break;
1948     case 256:
1949       *Fast = !Subtarget->isUnalignedMem32Slow();
1950       break;
1951     // TODO: What about AVX-512 (512-bit) accesses?
1952     }
1953   }
1954   // Misaligned accesses of any size are always allowed.
1955   return true;
1956 }
1957
1958 /// Return the entry encoding for a jump table in the
1959 /// current function.  The returned value is a member of the
1960 /// MachineJumpTableInfo::JTEntryKind enum.
1961 unsigned X86TargetLowering::getJumpTableEncoding() const {
1962   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1963   // symbol.
1964   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1965       Subtarget->isPICStyleGOT())
1966     return MachineJumpTableInfo::EK_Custom32;
1967
1968   // Otherwise, use the normal jump table encoding heuristics.
1969   return TargetLowering::getJumpTableEncoding();
1970 }
1971
1972 bool X86TargetLowering::useSoftFloat() const {
1973   return Subtarget->useSoftFloat();
1974 }
1975
1976 const MCExpr *
1977 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1978                                              const MachineBasicBlock *MBB,
1979                                              unsigned uid,MCContext &Ctx) const{
1980   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1981          Subtarget->isPICStyleGOT());
1982   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1983   // entries.
1984   return MCSymbolRefExpr::create(MBB->getSymbol(),
1985                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1986 }
1987
1988 /// Returns relocation base for the given PIC jumptable.
1989 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1990                                                     SelectionDAG &DAG) const {
1991   if (!Subtarget->is64Bit())
1992     // This doesn't have SDLoc associated with it, but is not really the
1993     // same as a Register.
1994     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1995                        getPointerTy(DAG.getDataLayout()));
1996   return Table;
1997 }
1998
1999 /// This returns the relocation base for the given PIC jumptable,
2000 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2001 const MCExpr *X86TargetLowering::
2002 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2003                              MCContext &Ctx) const {
2004   // X86-64 uses RIP relative addressing based on the jump table label.
2005   if (Subtarget->isPICStyleRIPRel())
2006     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2007
2008   // Otherwise, the reference is relative to the PIC base.
2009   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2010 }
2011
2012 std::pair<const TargetRegisterClass *, uint8_t>
2013 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2014                                            MVT VT) const {
2015   const TargetRegisterClass *RRC = nullptr;
2016   uint8_t Cost = 1;
2017   switch (VT.SimpleTy) {
2018   default:
2019     return TargetLowering::findRepresentativeClass(TRI, VT);
2020   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2021     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2022     break;
2023   case MVT::x86mmx:
2024     RRC = &X86::VR64RegClass;
2025     break;
2026   case MVT::f32: case MVT::f64:
2027   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2028   case MVT::v4f32: case MVT::v2f64:
2029   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2030   case MVT::v4f64:
2031     RRC = &X86::VR128RegClass;
2032     break;
2033   }
2034   return std::make_pair(RRC, Cost);
2035 }
2036
2037 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2038                                                unsigned &Offset) const {
2039   if (!Subtarget->isTargetLinux())
2040     return false;
2041
2042   if (Subtarget->is64Bit()) {
2043     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2044     Offset = 0x28;
2045     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2046       AddressSpace = 256;
2047     else
2048       AddressSpace = 257;
2049   } else {
2050     // %gs:0x14 on i386
2051     Offset = 0x14;
2052     AddressSpace = 256;
2053   }
2054   return true;
2055 }
2056
2057 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2058                                             unsigned DestAS) const {
2059   assert(SrcAS != DestAS && "Expected different address spaces!");
2060
2061   return SrcAS < 256 && DestAS < 256;
2062 }
2063
2064 //===----------------------------------------------------------------------===//
2065 //               Return Value Calling Convention Implementation
2066 //===----------------------------------------------------------------------===//
2067
2068 #include "X86GenCallingConv.inc"
2069
2070 bool
2071 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2072                                   MachineFunction &MF, bool isVarArg,
2073                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2074                         LLVMContext &Context) const {
2075   SmallVector<CCValAssign, 16> RVLocs;
2076   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2077   return CCInfo.CheckReturn(Outs, RetCC_X86);
2078 }
2079
2080 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2081   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2082   return ScratchRegs;
2083 }
2084
2085 SDValue
2086 X86TargetLowering::LowerReturn(SDValue Chain,
2087                                CallingConv::ID CallConv, bool isVarArg,
2088                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2089                                const SmallVectorImpl<SDValue> &OutVals,
2090                                SDLoc dl, SelectionDAG &DAG) const {
2091   MachineFunction &MF = DAG.getMachineFunction();
2092   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2093
2094   SmallVector<CCValAssign, 16> RVLocs;
2095   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2096   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2097
2098   SDValue Flag;
2099   SmallVector<SDValue, 6> RetOps;
2100   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2101   // Operand #1 = Bytes To Pop
2102   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2103                    MVT::i16));
2104
2105   // Copy the result values into the output registers.
2106   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2107     CCValAssign &VA = RVLocs[i];
2108     assert(VA.isRegLoc() && "Can only return in registers!");
2109     SDValue ValToCopy = OutVals[i];
2110     EVT ValVT = ValToCopy.getValueType();
2111
2112     // Promote values to the appropriate types.
2113     if (VA.getLocInfo() == CCValAssign::SExt)
2114       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2115     else if (VA.getLocInfo() == CCValAssign::ZExt)
2116       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2117     else if (VA.getLocInfo() == CCValAssign::AExt) {
2118       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2119         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2120       else
2121         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2122     }
2123     else if (VA.getLocInfo() == CCValAssign::BCvt)
2124       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2125
2126     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2127            "Unexpected FP-extend for return value.");
2128
2129     // If this is x86-64, and we disabled SSE, we can't return FP values,
2130     // or SSE or MMX vectors.
2131     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2132          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2133           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2134       report_fatal_error("SSE register return with SSE disabled");
2135     }
2136     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2137     // llvm-gcc has never done it right and no one has noticed, so this
2138     // should be OK for now.
2139     if (ValVT == MVT::f64 &&
2140         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2141       report_fatal_error("SSE2 register return with SSE2 disabled");
2142
2143     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2144     // the RET instruction and handled by the FP Stackifier.
2145     if (VA.getLocReg() == X86::FP0 ||
2146         VA.getLocReg() == X86::FP1) {
2147       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2148       // change the value to the FP stack register class.
2149       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2150         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2151       RetOps.push_back(ValToCopy);
2152       // Don't emit a copytoreg.
2153       continue;
2154     }
2155
2156     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2157     // which is returned in RAX / RDX.
2158     if (Subtarget->is64Bit()) {
2159       if (ValVT == MVT::x86mmx) {
2160         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2161           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2162           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2163                                   ValToCopy);
2164           // If we don't have SSE2 available, convert to v4f32 so the generated
2165           // register is legal.
2166           if (!Subtarget->hasSSE2())
2167             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2168         }
2169       }
2170     }
2171
2172     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2173     Flag = Chain.getValue(1);
2174     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2175   }
2176
2177   // All x86 ABIs require that for returning structs by value we copy
2178   // the sret argument into %rax/%eax (depending on ABI) for the return.
2179   // We saved the argument into a virtual register in the entry block,
2180   // so now we copy the value out and into %rax/%eax.
2181   //
2182   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2183   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2184   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2185   // either case FuncInfo->setSRetReturnReg() will have been called.
2186   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2187     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2188                                      getPointerTy(MF.getDataLayout()));
2189
2190     unsigned RetValReg
2191         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2192           X86::RAX : X86::EAX;
2193     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2194     Flag = Chain.getValue(1);
2195
2196     // RAX/EAX now acts like a return value.
2197     RetOps.push_back(
2198         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2199   }
2200
2201   RetOps[0] = Chain;  // Update chain.
2202
2203   // Add the flag if we have it.
2204   if (Flag.getNode())
2205     RetOps.push_back(Flag);
2206
2207   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2208 }
2209
2210 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2211   if (N->getNumValues() != 1)
2212     return false;
2213   if (!N->hasNUsesOfValue(1, 0))
2214     return false;
2215
2216   SDValue TCChain = Chain;
2217   SDNode *Copy = *N->use_begin();
2218   if (Copy->getOpcode() == ISD::CopyToReg) {
2219     // If the copy has a glue operand, we conservatively assume it isn't safe to
2220     // perform a tail call.
2221     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2222       return false;
2223     TCChain = Copy->getOperand(0);
2224   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2225     return false;
2226
2227   bool HasRet = false;
2228   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2229        UI != UE; ++UI) {
2230     if (UI->getOpcode() != X86ISD::RET_FLAG)
2231       return false;
2232     // If we are returning more than one value, we can definitely
2233     // not make a tail call see PR19530
2234     if (UI->getNumOperands() > 4)
2235       return false;
2236     if (UI->getNumOperands() == 4 &&
2237         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2238       return false;
2239     HasRet = true;
2240   }
2241
2242   if (!HasRet)
2243     return false;
2244
2245   Chain = TCChain;
2246   return true;
2247 }
2248
2249 EVT
2250 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2251                                             ISD::NodeType ExtendKind) const {
2252   MVT ReturnMVT;
2253   // TODO: Is this also valid on 32-bit?
2254   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2255     ReturnMVT = MVT::i8;
2256   else
2257     ReturnMVT = MVT::i32;
2258
2259   EVT MinVT = getRegisterType(Context, ReturnMVT);
2260   return VT.bitsLT(MinVT) ? MinVT : VT;
2261 }
2262
2263 /// Lower the result values of a call into the
2264 /// appropriate copies out of appropriate physical registers.
2265 ///
2266 SDValue
2267 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2268                                    CallingConv::ID CallConv, bool isVarArg,
2269                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2270                                    SDLoc dl, SelectionDAG &DAG,
2271                                    SmallVectorImpl<SDValue> &InVals) const {
2272
2273   // Assign locations to each value returned by this call.
2274   SmallVector<CCValAssign, 16> RVLocs;
2275   bool Is64Bit = Subtarget->is64Bit();
2276   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2277                  *DAG.getContext());
2278   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2279
2280   // Copy all of the result registers out of their specified physreg.
2281   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2282     CCValAssign &VA = RVLocs[i];
2283     EVT CopyVT = VA.getLocVT();
2284
2285     // If this is x86-64, and we disabled SSE, we can't return FP values
2286     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2287         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2288       report_fatal_error("SSE register return with SSE disabled");
2289     }
2290
2291     // If we prefer to use the value in xmm registers, copy it out as f80 and
2292     // use a truncate to move it from fp stack reg to xmm reg.
2293     bool RoundAfterCopy = false;
2294     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2295         isScalarFPTypeInSSEReg(VA.getValVT())) {
2296       CopyVT = MVT::f80;
2297       RoundAfterCopy = (CopyVT != VA.getLocVT());
2298     }
2299
2300     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2301                                CopyVT, InFlag).getValue(1);
2302     SDValue Val = Chain.getValue(0);
2303
2304     if (RoundAfterCopy)
2305       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2306                         // This truncation won't change the value.
2307                         DAG.getIntPtrConstant(1, dl));
2308
2309     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2310       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2311
2312     InFlag = Chain.getValue(2);
2313     InVals.push_back(Val);
2314   }
2315
2316   return Chain;
2317 }
2318
2319 //===----------------------------------------------------------------------===//
2320 //                C & StdCall & Fast Calling Convention implementation
2321 //===----------------------------------------------------------------------===//
2322 //  StdCall calling convention seems to be standard for many Windows' API
2323 //  routines and around. It differs from C calling convention just a little:
2324 //  callee should clean up the stack, not caller. Symbols should be also
2325 //  decorated in some fancy way :) It doesn't support any vector arguments.
2326 //  For info on fast calling convention see Fast Calling Convention (tail call)
2327 //  implementation LowerX86_32FastCCCallTo.
2328
2329 /// CallIsStructReturn - Determines whether a call uses struct return
2330 /// semantics.
2331 enum StructReturnType {
2332   NotStructReturn,
2333   RegStructReturn,
2334   StackStructReturn
2335 };
2336 static StructReturnType
2337 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2338   if (Outs.empty())
2339     return NotStructReturn;
2340
2341   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2342   if (!Flags.isSRet())
2343     return NotStructReturn;
2344   if (Flags.isInReg())
2345     return RegStructReturn;
2346   return StackStructReturn;
2347 }
2348
2349 /// Determines whether a function uses struct return semantics.
2350 static StructReturnType
2351 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2352   if (Ins.empty())
2353     return NotStructReturn;
2354
2355   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2356   if (!Flags.isSRet())
2357     return NotStructReturn;
2358   if (Flags.isInReg())
2359     return RegStructReturn;
2360   return StackStructReturn;
2361 }
2362
2363 /// Make a copy of an aggregate at address specified by "Src" to address
2364 /// "Dst" with size and alignment information specified by the specific
2365 /// parameter attribute. The copy will be passed as a byval function parameter.
2366 static SDValue
2367 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2368                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2369                           SDLoc dl) {
2370   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2371
2372   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2373                        /*isVolatile*/false, /*AlwaysInline=*/true,
2374                        /*isTailCall*/false,
2375                        MachinePointerInfo(), MachinePointerInfo());
2376 }
2377
2378 /// Return true if the calling convention is one that
2379 /// supports tail call optimization.
2380 static bool IsTailCallConvention(CallingConv::ID CC) {
2381   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2382           CC == CallingConv::HiPE);
2383 }
2384
2385 /// \brief Return true if the calling convention is a C calling convention.
2386 static bool IsCCallConvention(CallingConv::ID CC) {
2387   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2388           CC == CallingConv::X86_64_SysV);
2389 }
2390
2391 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2392   auto Attr =
2393       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2394   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2395     return false;
2396
2397   CallSite CS(CI);
2398   CallingConv::ID CalleeCC = CS.getCallingConv();
2399   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2400     return false;
2401
2402   return true;
2403 }
2404
2405 /// Return true if the function is being made into
2406 /// a tailcall target by changing its ABI.
2407 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2408                                    bool GuaranteedTailCallOpt) {
2409   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2410 }
2411
2412 SDValue
2413 X86TargetLowering::LowerMemArgument(SDValue Chain,
2414                                     CallingConv::ID CallConv,
2415                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2416                                     SDLoc dl, SelectionDAG &DAG,
2417                                     const CCValAssign &VA,
2418                                     MachineFrameInfo *MFI,
2419                                     unsigned i) const {
2420   // Create the nodes corresponding to a load from this parameter slot.
2421   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2422   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2423       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2424   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2425   EVT ValVT;
2426
2427   // If value is passed by pointer we have address passed instead of the value
2428   // itself.
2429   bool ExtendedInMem = VA.isExtInLoc() &&
2430     VA.getValVT().getScalarType() == MVT::i1;
2431
2432   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2433     ValVT = VA.getLocVT();
2434   else
2435     ValVT = VA.getValVT();
2436
2437   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2438   // changed with more analysis.
2439   // In case of tail call optimization mark all arguments mutable. Since they
2440   // could be overwritten by lowering of arguments in case of a tail call.
2441   if (Flags.isByVal()) {
2442     unsigned Bytes = Flags.getByValSize();
2443     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2444     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2445     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2446   } else {
2447     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2448                                     VA.getLocMemOffset(), isImmutable);
2449     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2450     SDValue Val = DAG.getLoad(
2451         ValVT, dl, Chain, FIN,
2452         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2453         false, false, 0);
2454     return ExtendedInMem ?
2455       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2456   }
2457 }
2458
2459 // FIXME: Get this from tablegen.
2460 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2461                                                 const X86Subtarget *Subtarget) {
2462   assert(Subtarget->is64Bit());
2463
2464   if (Subtarget->isCallingConvWin64(CallConv)) {
2465     static const MCPhysReg GPR64ArgRegsWin64[] = {
2466       X86::RCX, X86::RDX, X86::R8,  X86::R9
2467     };
2468     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2469   }
2470
2471   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2472     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2473   };
2474   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2475 }
2476
2477 // FIXME: Get this from tablegen.
2478 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2479                                                 CallingConv::ID CallConv,
2480                                                 const X86Subtarget *Subtarget) {
2481   assert(Subtarget->is64Bit());
2482   if (Subtarget->isCallingConvWin64(CallConv)) {
2483     // The XMM registers which might contain var arg parameters are shadowed
2484     // in their paired GPR.  So we only need to save the GPR to their home
2485     // slots.
2486     // TODO: __vectorcall will change this.
2487     return None;
2488   }
2489
2490   const Function *Fn = MF.getFunction();
2491   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2492   bool isSoftFloat = Subtarget->useSoftFloat();
2493   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2494          "SSE register cannot be used when SSE is disabled!");
2495   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2496     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2497     // registers.
2498     return None;
2499
2500   static const MCPhysReg XMMArgRegs64Bit[] = {
2501     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2502     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2503   };
2504   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2505 }
2506
2507 SDValue
2508 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2509                                         CallingConv::ID CallConv,
2510                                         bool isVarArg,
2511                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2512                                         SDLoc dl,
2513                                         SelectionDAG &DAG,
2514                                         SmallVectorImpl<SDValue> &InVals)
2515                                           const {
2516   MachineFunction &MF = DAG.getMachineFunction();
2517   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2518   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2519
2520   const Function* Fn = MF.getFunction();
2521   if (Fn->hasExternalLinkage() &&
2522       Subtarget->isTargetCygMing() &&
2523       Fn->getName() == "main")
2524     FuncInfo->setForceFramePointer(true);
2525
2526   MachineFrameInfo *MFI = MF.getFrameInfo();
2527   bool Is64Bit = Subtarget->is64Bit();
2528   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2529
2530   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2531          "Var args not supported with calling convention fastcc, ghc or hipe");
2532
2533   // Assign locations to all of the incoming arguments.
2534   SmallVector<CCValAssign, 16> ArgLocs;
2535   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2536
2537   // Allocate shadow area for Win64
2538   if (IsWin64)
2539     CCInfo.AllocateStack(32, 8);
2540
2541   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2542
2543   unsigned LastVal = ~0U;
2544   SDValue ArgValue;
2545   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2546     CCValAssign &VA = ArgLocs[i];
2547     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2548     // places.
2549     assert(VA.getValNo() != LastVal &&
2550            "Don't support value assigned to multiple locs yet");
2551     (void)LastVal;
2552     LastVal = VA.getValNo();
2553
2554     if (VA.isRegLoc()) {
2555       EVT RegVT = VA.getLocVT();
2556       const TargetRegisterClass *RC;
2557       if (RegVT == MVT::i32)
2558         RC = &X86::GR32RegClass;
2559       else if (Is64Bit && RegVT == MVT::i64)
2560         RC = &X86::GR64RegClass;
2561       else if (RegVT == MVT::f32)
2562         RC = &X86::FR32RegClass;
2563       else if (RegVT == MVT::f64)
2564         RC = &X86::FR64RegClass;
2565       else if (RegVT.is512BitVector())
2566         RC = &X86::VR512RegClass;
2567       else if (RegVT.is256BitVector())
2568         RC = &X86::VR256RegClass;
2569       else if (RegVT.is128BitVector())
2570         RC = &X86::VR128RegClass;
2571       else if (RegVT == MVT::x86mmx)
2572         RC = &X86::VR64RegClass;
2573       else if (RegVT == MVT::i1)
2574         RC = &X86::VK1RegClass;
2575       else if (RegVT == MVT::v8i1)
2576         RC = &X86::VK8RegClass;
2577       else if (RegVT == MVT::v16i1)
2578         RC = &X86::VK16RegClass;
2579       else if (RegVT == MVT::v32i1)
2580         RC = &X86::VK32RegClass;
2581       else if (RegVT == MVT::v64i1)
2582         RC = &X86::VK64RegClass;
2583       else
2584         llvm_unreachable("Unknown argument type!");
2585
2586       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2587       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2588
2589       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2590       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2591       // right size.
2592       if (VA.getLocInfo() == CCValAssign::SExt)
2593         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2594                                DAG.getValueType(VA.getValVT()));
2595       else if (VA.getLocInfo() == CCValAssign::ZExt)
2596         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2597                                DAG.getValueType(VA.getValVT()));
2598       else if (VA.getLocInfo() == CCValAssign::BCvt)
2599         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2600
2601       if (VA.isExtInLoc()) {
2602         // Handle MMX values passed in XMM regs.
2603         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2604           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2605         else
2606           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2607       }
2608     } else {
2609       assert(VA.isMemLoc());
2610       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2611     }
2612
2613     // If value is passed via pointer - do a load.
2614     if (VA.getLocInfo() == CCValAssign::Indirect)
2615       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2616                              MachinePointerInfo(), false, false, false, 0);
2617
2618     InVals.push_back(ArgValue);
2619   }
2620
2621   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2622     // All x86 ABIs require that for returning structs by value we copy the
2623     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2624     // the argument into a virtual register so that we can access it from the
2625     // return points.
2626     if (Ins[i].Flags.isSRet()) {
2627       unsigned Reg = FuncInfo->getSRetReturnReg();
2628       if (!Reg) {
2629         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2630         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2631         FuncInfo->setSRetReturnReg(Reg);
2632       }
2633       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2634       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2635       break;
2636     }
2637   }
2638
2639   unsigned StackSize = CCInfo.getNextStackOffset();
2640   // Align stack specially for tail calls.
2641   if (FuncIsMadeTailCallSafe(CallConv,
2642                              MF.getTarget().Options.GuaranteedTailCallOpt))
2643     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2644
2645   // If the function takes variable number of arguments, make a frame index for
2646   // the start of the first vararg value... for expansion of llvm.va_start. We
2647   // can skip this if there are no va_start calls.
2648   if (MFI->hasVAStart() &&
2649       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2650                    CallConv != CallingConv::X86_ThisCall))) {
2651     FuncInfo->setVarArgsFrameIndex(
2652         MFI->CreateFixedObject(1, StackSize, true));
2653   }
2654
2655   MachineModuleInfo &MMI = MF.getMMI();
2656   const Function *WinEHParent = nullptr;
2657   if (MMI.hasWinEHFuncInfo(Fn))
2658     WinEHParent = MMI.getWinEHParent(Fn);
2659   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2660   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2661
2662   // Figure out if XMM registers are in use.
2663   assert(!(Subtarget->useSoftFloat() &&
2664            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2665          "SSE register cannot be used when SSE is disabled!");
2666
2667   // 64-bit calling conventions support varargs and register parameters, so we
2668   // have to do extra work to spill them in the prologue.
2669   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2670     // Find the first unallocated argument registers.
2671     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2672     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2673     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2674     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2675     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2676            "SSE register cannot be used when SSE is disabled!");
2677
2678     // Gather all the live in physical registers.
2679     SmallVector<SDValue, 6> LiveGPRs;
2680     SmallVector<SDValue, 8> LiveXMMRegs;
2681     SDValue ALVal;
2682     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2683       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2684       LiveGPRs.push_back(
2685           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2686     }
2687     if (!ArgXMMs.empty()) {
2688       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2689       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2690       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2691         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2692         LiveXMMRegs.push_back(
2693             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2694       }
2695     }
2696
2697     if (IsWin64) {
2698       // Get to the caller-allocated home save location.  Add 8 to account
2699       // for the return address.
2700       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2701       FuncInfo->setRegSaveFrameIndex(
2702           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2703       // Fixup to set vararg frame on shadow area (4 x i64).
2704       if (NumIntRegs < 4)
2705         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2706     } else {
2707       // For X86-64, if there are vararg parameters that are passed via
2708       // registers, then we must store them to their spots on the stack so
2709       // they may be loaded by deferencing the result of va_next.
2710       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2711       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2712       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2713           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2714     }
2715
2716     // Store the integer parameter registers.
2717     SmallVector<SDValue, 8> MemOps;
2718     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2719                                       getPointerTy(DAG.getDataLayout()));
2720     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2721     for (SDValue Val : LiveGPRs) {
2722       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2723                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2724       SDValue Store =
2725           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2726                        MachinePointerInfo::getFixedStack(
2727                            DAG.getMachineFunction(),
2728                            FuncInfo->getRegSaveFrameIndex(), Offset),
2729                        false, false, 0);
2730       MemOps.push_back(Store);
2731       Offset += 8;
2732     }
2733
2734     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2735       // Now store the XMM (fp + vector) parameter registers.
2736       SmallVector<SDValue, 12> SaveXMMOps;
2737       SaveXMMOps.push_back(Chain);
2738       SaveXMMOps.push_back(ALVal);
2739       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2740                              FuncInfo->getRegSaveFrameIndex(), dl));
2741       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2742                              FuncInfo->getVarArgsFPOffset(), dl));
2743       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2744                         LiveXMMRegs.end());
2745       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2746                                    MVT::Other, SaveXMMOps));
2747     }
2748
2749     if (!MemOps.empty())
2750       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2751   } else if (IsWin64 && IsWinEHOutlined) {
2752     // Get to the caller-allocated home save location.  Add 8 to account
2753     // for the return address.
2754     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2755     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2756         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2757
2758     MMI.getWinEHFuncInfo(Fn)
2759         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2760         FuncInfo->getRegSaveFrameIndex();
2761
2762     // Store the second integer parameter (rdx) into rsp+16 relative to the
2763     // stack pointer at the entry of the function.
2764     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2765                                       getPointerTy(DAG.getDataLayout()));
2766     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2767     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2768     Chain = DAG.getStore(
2769         Val.getValue(1), dl, Val, RSFIN,
2770         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2771                                           FuncInfo->getRegSaveFrameIndex()),
2772         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2773   }
2774
2775   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2776     // Find the largest legal vector type.
2777     MVT VecVT = MVT::Other;
2778     // FIXME: Only some x86_32 calling conventions support AVX512.
2779     if (Subtarget->hasAVX512() &&
2780         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2781                      CallConv == CallingConv::Intel_OCL_BI)))
2782       VecVT = MVT::v16f32;
2783     else if (Subtarget->hasAVX())
2784       VecVT = MVT::v8f32;
2785     else if (Subtarget->hasSSE2())
2786       VecVT = MVT::v4f32;
2787
2788     // We forward some GPRs and some vector types.
2789     SmallVector<MVT, 2> RegParmTypes;
2790     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2791     RegParmTypes.push_back(IntVT);
2792     if (VecVT != MVT::Other)
2793       RegParmTypes.push_back(VecVT);
2794
2795     // Compute the set of forwarded registers. The rest are scratch.
2796     SmallVectorImpl<ForwardedRegister> &Forwards =
2797         FuncInfo->getForwardedMustTailRegParms();
2798     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2799
2800     // Conservatively forward AL on x86_64, since it might be used for varargs.
2801     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2802       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2803       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2804     }
2805
2806     // Copy all forwards from physical to virtual registers.
2807     for (ForwardedRegister &F : Forwards) {
2808       // FIXME: Can we use a less constrained schedule?
2809       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2810       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2811       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2812     }
2813   }
2814
2815   // Some CCs need callee pop.
2816   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2817                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2818     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2819   } else {
2820     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2821     // If this is an sret function, the return should pop the hidden pointer.
2822     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2823         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2824         argsAreStructReturn(Ins) == StackStructReturn)
2825       FuncInfo->setBytesToPopOnReturn(4);
2826   }
2827
2828   if (!Is64Bit) {
2829     // RegSaveFrameIndex is X86-64 only.
2830     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2831     if (CallConv == CallingConv::X86_FastCall ||
2832         CallConv == CallingConv::X86_ThisCall)
2833       // fastcc functions can't have varargs.
2834       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2835   }
2836
2837   FuncInfo->setArgumentStackSize(StackSize);
2838
2839   if (IsWinEHParent) {
2840     if (Is64Bit) {
2841       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2842       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2843       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2844       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2845       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2846                            MachinePointerInfo::getFixedStack(
2847                                DAG.getMachineFunction(), UnwindHelpFI),
2848                            /*isVolatile=*/true,
2849                            /*isNonTemporal=*/false, /*Alignment=*/0);
2850     } else {
2851       // Functions using Win32 EH are considered to have opaque SP adjustments
2852       // to force local variables to be addressed from the frame or base
2853       // pointers.
2854       MFI->setHasOpaqueSPAdjustment(true);
2855     }
2856   }
2857
2858   return Chain;
2859 }
2860
2861 SDValue
2862 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2863                                     SDValue StackPtr, SDValue Arg,
2864                                     SDLoc dl, SelectionDAG &DAG,
2865                                     const CCValAssign &VA,
2866                                     ISD::ArgFlagsTy Flags) const {
2867   unsigned LocMemOffset = VA.getLocMemOffset();
2868   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2869   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2870                        StackPtr, PtrOff);
2871   if (Flags.isByVal())
2872     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2873
2874   return DAG.getStore(
2875       Chain, dl, Arg, PtrOff,
2876       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2877       false, false, 0);
2878 }
2879
2880 /// Emit a load of return address if tail call
2881 /// optimization is performed and it is required.
2882 SDValue
2883 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2884                                            SDValue &OutRetAddr, SDValue Chain,
2885                                            bool IsTailCall, bool Is64Bit,
2886                                            int FPDiff, SDLoc dl) const {
2887   // Adjust the Return address stack slot.
2888   EVT VT = getPointerTy(DAG.getDataLayout());
2889   OutRetAddr = getReturnAddressFrameIndex(DAG);
2890
2891   // Load the "old" Return address.
2892   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2893                            false, false, false, 0);
2894   return SDValue(OutRetAddr.getNode(), 1);
2895 }
2896
2897 /// Emit a store of the return address if tail call
2898 /// optimization is performed and it is required (FPDiff!=0).
2899 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2900                                         SDValue Chain, SDValue RetAddrFrIdx,
2901                                         EVT PtrVT, unsigned SlotSize,
2902                                         int FPDiff, SDLoc dl) {
2903   // Store the return address to the appropriate stack slot.
2904   if (!FPDiff) return Chain;
2905   // Calculate the new stack slot for the return address.
2906   int NewReturnAddrFI =
2907     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2908                                          false);
2909   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2910   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2911                        MachinePointerInfo::getFixedStack(
2912                            DAG.getMachineFunction(), NewReturnAddrFI),
2913                        false, false, 0);
2914   return Chain;
2915 }
2916
2917 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2918 /// operation of specified width.
2919 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2920                        SDValue V2) {
2921   unsigned NumElems = VT.getVectorNumElements();
2922   SmallVector<int, 8> Mask;
2923   Mask.push_back(NumElems);
2924   for (unsigned i = 1; i != NumElems; ++i)
2925     Mask.push_back(i);
2926   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2927 }
2928
2929 SDValue
2930 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2931                              SmallVectorImpl<SDValue> &InVals) const {
2932   SelectionDAG &DAG                     = CLI.DAG;
2933   SDLoc &dl                             = CLI.DL;
2934   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2935   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2936   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2937   SDValue Chain                         = CLI.Chain;
2938   SDValue Callee                        = CLI.Callee;
2939   CallingConv::ID CallConv              = CLI.CallConv;
2940   bool &isTailCall                      = CLI.IsTailCall;
2941   bool isVarArg                         = CLI.IsVarArg;
2942
2943   MachineFunction &MF = DAG.getMachineFunction();
2944   bool Is64Bit        = Subtarget->is64Bit();
2945   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2946   StructReturnType SR = callIsStructReturn(Outs);
2947   bool IsSibcall      = false;
2948   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2949   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2950
2951   if (Attr.getValueAsString() == "true")
2952     isTailCall = false;
2953
2954   if (Subtarget->isPICStyleGOT() &&
2955       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2956     // If we are using a GOT, disable tail calls to external symbols with
2957     // default visibility. Tail calling such a symbol requires using a GOT
2958     // relocation, which forces early binding of the symbol. This breaks code
2959     // that require lazy function symbol resolution. Using musttail or
2960     // GuaranteedTailCallOpt will override this.
2961     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2962     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2963                G->getGlobal()->hasDefaultVisibility()))
2964       isTailCall = false;
2965   }
2966
2967   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2968   if (IsMustTail) {
2969     // Force this to be a tail call.  The verifier rules are enough to ensure
2970     // that we can lower this successfully without moving the return address
2971     // around.
2972     isTailCall = true;
2973   } else if (isTailCall) {
2974     // Check if it's really possible to do a tail call.
2975     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2976                     isVarArg, SR != NotStructReturn,
2977                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2978                     Outs, OutVals, Ins, DAG);
2979
2980     // Sibcalls are automatically detected tailcalls which do not require
2981     // ABI changes.
2982     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2983       IsSibcall = true;
2984
2985     if (isTailCall)
2986       ++NumTailCalls;
2987   }
2988
2989   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2990          "Var args not supported with calling convention fastcc, ghc or hipe");
2991
2992   // Analyze operands of the call, assigning locations to each operand.
2993   SmallVector<CCValAssign, 16> ArgLocs;
2994   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2995
2996   // Allocate shadow area for Win64
2997   if (IsWin64)
2998     CCInfo.AllocateStack(32, 8);
2999
3000   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3001
3002   // Get a count of how many bytes are to be pushed on the stack.
3003   unsigned NumBytes = CCInfo.getNextStackOffset();
3004   if (IsSibcall)
3005     // This is a sibcall. The memory operands are available in caller's
3006     // own caller's stack.
3007     NumBytes = 0;
3008   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3009            IsTailCallConvention(CallConv))
3010     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3011
3012   int FPDiff = 0;
3013   if (isTailCall && !IsSibcall && !IsMustTail) {
3014     // Lower arguments at fp - stackoffset + fpdiff.
3015     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3016
3017     FPDiff = NumBytesCallerPushed - NumBytes;
3018
3019     // Set the delta of movement of the returnaddr stackslot.
3020     // But only set if delta is greater than previous delta.
3021     if (FPDiff < X86Info->getTCReturnAddrDelta())
3022       X86Info->setTCReturnAddrDelta(FPDiff);
3023   }
3024
3025   unsigned NumBytesToPush = NumBytes;
3026   unsigned NumBytesToPop = NumBytes;
3027
3028   // If we have an inalloca argument, all stack space has already been allocated
3029   // for us and be right at the top of the stack.  We don't support multiple
3030   // arguments passed in memory when using inalloca.
3031   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3032     NumBytesToPush = 0;
3033     if (!ArgLocs.back().isMemLoc())
3034       report_fatal_error("cannot use inalloca attribute on a register "
3035                          "parameter");
3036     if (ArgLocs.back().getLocMemOffset() != 0)
3037       report_fatal_error("any parameter with the inalloca attribute must be "
3038                          "the only memory argument");
3039   }
3040
3041   if (!IsSibcall)
3042     Chain = DAG.getCALLSEQ_START(
3043         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3044
3045   SDValue RetAddrFrIdx;
3046   // Load return address for tail calls.
3047   if (isTailCall && FPDiff)
3048     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3049                                     Is64Bit, FPDiff, dl);
3050
3051   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3052   SmallVector<SDValue, 8> MemOpChains;
3053   SDValue StackPtr;
3054
3055   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3056   // of tail call optimization arguments are handle later.
3057   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3058   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3059     // Skip inalloca arguments, they have already been written.
3060     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3061     if (Flags.isInAlloca())
3062       continue;
3063
3064     CCValAssign &VA = ArgLocs[i];
3065     EVT RegVT = VA.getLocVT();
3066     SDValue Arg = OutVals[i];
3067     bool isByVal = Flags.isByVal();
3068
3069     // Promote the value if needed.
3070     switch (VA.getLocInfo()) {
3071     default: llvm_unreachable("Unknown loc info!");
3072     case CCValAssign::Full: break;
3073     case CCValAssign::SExt:
3074       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3075       break;
3076     case CCValAssign::ZExt:
3077       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3078       break;
3079     case CCValAssign::AExt:
3080       if (Arg.getValueType().isVector() &&
3081           Arg.getValueType().getScalarType() == MVT::i1)
3082         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3083       else if (RegVT.is128BitVector()) {
3084         // Special case: passing MMX values in XMM registers.
3085         Arg = DAG.getBitcast(MVT::i64, Arg);
3086         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3087         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3088       } else
3089         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3090       break;
3091     case CCValAssign::BCvt:
3092       Arg = DAG.getBitcast(RegVT, Arg);
3093       break;
3094     case CCValAssign::Indirect: {
3095       // Store the argument.
3096       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3097       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3098       Chain = DAG.getStore(
3099           Chain, dl, Arg, SpillSlot,
3100           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3101           false, false, 0);
3102       Arg = SpillSlot;
3103       break;
3104     }
3105     }
3106
3107     if (VA.isRegLoc()) {
3108       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3109       if (isVarArg && IsWin64) {
3110         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3111         // shadow reg if callee is a varargs function.
3112         unsigned ShadowReg = 0;
3113         switch (VA.getLocReg()) {
3114         case X86::XMM0: ShadowReg = X86::RCX; break;
3115         case X86::XMM1: ShadowReg = X86::RDX; break;
3116         case X86::XMM2: ShadowReg = X86::R8; break;
3117         case X86::XMM3: ShadowReg = X86::R9; break;
3118         }
3119         if (ShadowReg)
3120           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3121       }
3122     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3123       assert(VA.isMemLoc());
3124       if (!StackPtr.getNode())
3125         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3126                                       getPointerTy(DAG.getDataLayout()));
3127       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3128                                              dl, DAG, VA, Flags));
3129     }
3130   }
3131
3132   if (!MemOpChains.empty())
3133     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3134
3135   if (Subtarget->isPICStyleGOT()) {
3136     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3137     // GOT pointer.
3138     if (!isTailCall) {
3139       RegsToPass.push_back(std::make_pair(
3140           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3141                                           getPointerTy(DAG.getDataLayout()))));
3142     } else {
3143       // If we are tail calling and generating PIC/GOT style code load the
3144       // address of the callee into ECX. The value in ecx is used as target of
3145       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3146       // for tail calls on PIC/GOT architectures. Normally we would just put the
3147       // address of GOT into ebx and then call target@PLT. But for tail calls
3148       // ebx would be restored (since ebx is callee saved) before jumping to the
3149       // target@PLT.
3150
3151       // Note: The actual moving to ECX is done further down.
3152       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3153       if (G && !G->getGlobal()->hasLocalLinkage() &&
3154           G->getGlobal()->hasDefaultVisibility())
3155         Callee = LowerGlobalAddress(Callee, DAG);
3156       else if (isa<ExternalSymbolSDNode>(Callee))
3157         Callee = LowerExternalSymbol(Callee, DAG);
3158     }
3159   }
3160
3161   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3162     // From AMD64 ABI document:
3163     // For calls that may call functions that use varargs or stdargs
3164     // (prototype-less calls or calls to functions containing ellipsis (...) in
3165     // the declaration) %al is used as hidden argument to specify the number
3166     // of SSE registers used. The contents of %al do not need to match exactly
3167     // the number of registers, but must be an ubound on the number of SSE
3168     // registers used and is in the range 0 - 8 inclusive.
3169
3170     // Count the number of XMM registers allocated.
3171     static const MCPhysReg XMMArgRegs[] = {
3172       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3173       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3174     };
3175     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3176     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3177            && "SSE registers cannot be used when SSE is disabled");
3178
3179     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3180                                         DAG.getConstant(NumXMMRegs, dl,
3181                                                         MVT::i8)));
3182   }
3183
3184   if (isVarArg && IsMustTail) {
3185     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3186     for (const auto &F : Forwards) {
3187       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3188       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3189     }
3190   }
3191
3192   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3193   // don't need this because the eligibility check rejects calls that require
3194   // shuffling arguments passed in memory.
3195   if (!IsSibcall && isTailCall) {
3196     // Force all the incoming stack arguments to be loaded from the stack
3197     // before any new outgoing arguments are stored to the stack, because the
3198     // outgoing stack slots may alias the incoming argument stack slots, and
3199     // the alias isn't otherwise explicit. This is slightly more conservative
3200     // than necessary, because it means that each store effectively depends
3201     // on every argument instead of just those arguments it would clobber.
3202     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3203
3204     SmallVector<SDValue, 8> MemOpChains2;
3205     SDValue FIN;
3206     int FI = 0;
3207     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3208       CCValAssign &VA = ArgLocs[i];
3209       if (VA.isRegLoc())
3210         continue;
3211       assert(VA.isMemLoc());
3212       SDValue Arg = OutVals[i];
3213       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3214       // Skip inalloca arguments.  They don't require any work.
3215       if (Flags.isInAlloca())
3216         continue;
3217       // Create frame index.
3218       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3219       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3220       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3221       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3222
3223       if (Flags.isByVal()) {
3224         // Copy relative to framepointer.
3225         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3226         if (!StackPtr.getNode())
3227           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3228                                         getPointerTy(DAG.getDataLayout()));
3229         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3230                              StackPtr, Source);
3231
3232         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3233                                                          ArgChain,
3234                                                          Flags, DAG, dl));
3235       } else {
3236         // Store relative to framepointer.
3237         MemOpChains2.push_back(DAG.getStore(
3238             ArgChain, dl, Arg, FIN,
3239             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3240             false, false, 0));
3241       }
3242     }
3243
3244     if (!MemOpChains2.empty())
3245       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3246
3247     // Store the return address to the appropriate stack slot.
3248     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3249                                      getPointerTy(DAG.getDataLayout()),
3250                                      RegInfo->getSlotSize(), FPDiff, dl);
3251   }
3252
3253   // Build a sequence of copy-to-reg nodes chained together with token chain
3254   // and flag operands which copy the outgoing args into registers.
3255   SDValue InFlag;
3256   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3257     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3258                              RegsToPass[i].second, InFlag);
3259     InFlag = Chain.getValue(1);
3260   }
3261
3262   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3263     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3264     // In the 64-bit large code model, we have to make all calls
3265     // through a register, since the call instruction's 32-bit
3266     // pc-relative offset may not be large enough to hold the whole
3267     // address.
3268   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3269     // If the callee is a GlobalAddress node (quite common, every direct call
3270     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3271     // it.
3272     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3273
3274     // We should use extra load for direct calls to dllimported functions in
3275     // non-JIT mode.
3276     const GlobalValue *GV = G->getGlobal();
3277     if (!GV->hasDLLImportStorageClass()) {
3278       unsigned char OpFlags = 0;
3279       bool ExtraLoad = false;
3280       unsigned WrapperKind = ISD::DELETED_NODE;
3281
3282       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3283       // external symbols most go through the PLT in PIC mode.  If the symbol
3284       // has hidden or protected visibility, or if it is static or local, then
3285       // we don't need to use the PLT - we can directly call it.
3286       if (Subtarget->isTargetELF() &&
3287           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3288           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3289         OpFlags = X86II::MO_PLT;
3290       } else if (Subtarget->isPICStyleStubAny() &&
3291                  !GV->isStrongDefinitionForLinker() &&
3292                  (!Subtarget->getTargetTriple().isMacOSX() ||
3293                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3294         // PC-relative references to external symbols should go through $stub,
3295         // unless we're building with the leopard linker or later, which
3296         // automatically synthesizes these stubs.
3297         OpFlags = X86II::MO_DARWIN_STUB;
3298       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3299                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3300         // If the function is marked as non-lazy, generate an indirect call
3301         // which loads from the GOT directly. This avoids runtime overhead
3302         // at the cost of eager binding (and one extra byte of encoding).
3303         OpFlags = X86II::MO_GOTPCREL;
3304         WrapperKind = X86ISD::WrapperRIP;
3305         ExtraLoad = true;
3306       }
3307
3308       Callee = DAG.getTargetGlobalAddress(
3309           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3310
3311       // Add a wrapper if needed.
3312       if (WrapperKind != ISD::DELETED_NODE)
3313         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3314                              getPointerTy(DAG.getDataLayout()), Callee);
3315       // Add extra indirection if needed.
3316       if (ExtraLoad)
3317         Callee = DAG.getLoad(
3318             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3319             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3320             false, 0);
3321     }
3322   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3323     unsigned char OpFlags = 0;
3324
3325     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3326     // external symbols should go through the PLT.
3327     if (Subtarget->isTargetELF() &&
3328         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3329       OpFlags = X86II::MO_PLT;
3330     } else if (Subtarget->isPICStyleStubAny() &&
3331                (!Subtarget->getTargetTriple().isMacOSX() ||
3332                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3333       // PC-relative references to external symbols should go through $stub,
3334       // unless we're building with the leopard linker or later, which
3335       // automatically synthesizes these stubs.
3336       OpFlags = X86II::MO_DARWIN_STUB;
3337     }
3338
3339     Callee = DAG.getTargetExternalSymbol(
3340         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3341   } else if (Subtarget->isTarget64BitILP32() &&
3342              Callee->getValueType(0) == MVT::i32) {
3343     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3344     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3345   }
3346
3347   // Returns a chain & a flag for retval copy to use.
3348   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3349   SmallVector<SDValue, 8> Ops;
3350
3351   if (!IsSibcall && isTailCall) {
3352     Chain = DAG.getCALLSEQ_END(Chain,
3353                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3354                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3355     InFlag = Chain.getValue(1);
3356   }
3357
3358   Ops.push_back(Chain);
3359   Ops.push_back(Callee);
3360
3361   if (isTailCall)
3362     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3363
3364   // Add argument registers to the end of the list so that they are known live
3365   // into the call.
3366   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3367     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3368                                   RegsToPass[i].second.getValueType()));
3369
3370   // Add a register mask operand representing the call-preserved registers.
3371   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3372   assert(Mask && "Missing call preserved mask for calling convention");
3373
3374   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3375   // the function clobbers all registers. If an exception is thrown, the runtime
3376   // will not restore CSRs.
3377   // FIXME: Model this more precisely so that we can register allocate across
3378   // the normal edge and spill and fill across the exceptional edge.
3379   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3380     const Function *CallerFn = MF.getFunction();
3381     EHPersonality Pers =
3382         CallerFn->hasPersonalityFn()
3383             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3384             : EHPersonality::Unknown;
3385     if (isMSVCEHPersonality(Pers))
3386       Mask = RegInfo->getNoPreservedMask();
3387   }
3388
3389   Ops.push_back(DAG.getRegisterMask(Mask));
3390
3391   if (InFlag.getNode())
3392     Ops.push_back(InFlag);
3393
3394   if (isTailCall) {
3395     // We used to do:
3396     //// If this is the first return lowered for this function, add the regs
3397     //// to the liveout set for the function.
3398     // This isn't right, although it's probably harmless on x86; liveouts
3399     // should be computed from returns not tail calls.  Consider a void
3400     // function making a tail call to a function returning int.
3401     MF.getFrameInfo()->setHasTailCall();
3402     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3403   }
3404
3405   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3406   InFlag = Chain.getValue(1);
3407
3408   // Create the CALLSEQ_END node.
3409   unsigned NumBytesForCalleeToPop;
3410   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3411                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3412     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3413   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3414            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3415            SR == StackStructReturn)
3416     // If this is a call to a struct-return function, the callee
3417     // pops the hidden struct pointer, so we have to push it back.
3418     // This is common for Darwin/X86, Linux & Mingw32 targets.
3419     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3420     NumBytesForCalleeToPop = 4;
3421   else
3422     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3423
3424   // Returns a flag for retval copy to use.
3425   if (!IsSibcall) {
3426     Chain = DAG.getCALLSEQ_END(Chain,
3427                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3428                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3429                                                      true),
3430                                InFlag, dl);
3431     InFlag = Chain.getValue(1);
3432   }
3433
3434   // Handle result values, copying them out of physregs into vregs that we
3435   // return.
3436   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3437                          Ins, dl, DAG, InVals);
3438 }
3439
3440 //===----------------------------------------------------------------------===//
3441 //                Fast Calling Convention (tail call) implementation
3442 //===----------------------------------------------------------------------===//
3443
3444 //  Like std call, callee cleans arguments, convention except that ECX is
3445 //  reserved for storing the tail called function address. Only 2 registers are
3446 //  free for argument passing (inreg). Tail call optimization is performed
3447 //  provided:
3448 //                * tailcallopt is enabled
3449 //                * caller/callee are fastcc
3450 //  On X86_64 architecture with GOT-style position independent code only local
3451 //  (within module) calls are supported at the moment.
3452 //  To keep the stack aligned according to platform abi the function
3453 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3454 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3455 //  If a tail called function callee has more arguments than the caller the
3456 //  caller needs to make sure that there is room to move the RETADDR to. This is
3457 //  achieved by reserving an area the size of the argument delta right after the
3458 //  original RETADDR, but before the saved framepointer or the spilled registers
3459 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3460 //  stack layout:
3461 //    arg1
3462 //    arg2
3463 //    RETADDR
3464 //    [ new RETADDR
3465 //      move area ]
3466 //    (possible EBP)
3467 //    ESI
3468 //    EDI
3469 //    local1 ..
3470
3471 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3472 /// requirement.
3473 unsigned
3474 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3475                                                SelectionDAG& DAG) const {
3476   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3477   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3478   unsigned StackAlignment = TFI.getStackAlignment();
3479   uint64_t AlignMask = StackAlignment - 1;
3480   int64_t Offset = StackSize;
3481   unsigned SlotSize = RegInfo->getSlotSize();
3482   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3483     // Number smaller than 12 so just add the difference.
3484     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3485   } else {
3486     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3487     Offset = ((~AlignMask) & Offset) + StackAlignment +
3488       (StackAlignment-SlotSize);
3489   }
3490   return Offset;
3491 }
3492
3493 /// Return true if the given stack call argument is already available in the
3494 /// same position (relatively) of the caller's incoming argument stack.
3495 static
3496 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3497                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3498                          const X86InstrInfo *TII) {
3499   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3500   int FI = INT_MAX;
3501   if (Arg.getOpcode() == ISD::CopyFromReg) {
3502     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3503     if (!TargetRegisterInfo::isVirtualRegister(VR))
3504       return false;
3505     MachineInstr *Def = MRI->getVRegDef(VR);
3506     if (!Def)
3507       return false;
3508     if (!Flags.isByVal()) {
3509       if (!TII->isLoadFromStackSlot(Def, FI))
3510         return false;
3511     } else {
3512       unsigned Opcode = Def->getOpcode();
3513       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3514            Opcode == X86::LEA64_32r) &&
3515           Def->getOperand(1).isFI()) {
3516         FI = Def->getOperand(1).getIndex();
3517         Bytes = Flags.getByValSize();
3518       } else
3519         return false;
3520     }
3521   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3522     if (Flags.isByVal())
3523       // ByVal argument is passed in as a pointer but it's now being
3524       // dereferenced. e.g.
3525       // define @foo(%struct.X* %A) {
3526       //   tail call @bar(%struct.X* byval %A)
3527       // }
3528       return false;
3529     SDValue Ptr = Ld->getBasePtr();
3530     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3531     if (!FINode)
3532       return false;
3533     FI = FINode->getIndex();
3534   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3535     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3536     FI = FINode->getIndex();
3537     Bytes = Flags.getByValSize();
3538   } else
3539     return false;
3540
3541   assert(FI != INT_MAX);
3542   if (!MFI->isFixedObjectIndex(FI))
3543     return false;
3544   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3545 }
3546
3547 /// Check whether the call is eligible for tail call optimization. Targets
3548 /// that want to do tail call optimization should implement this function.
3549 bool
3550 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3551                                                      CallingConv::ID CalleeCC,
3552                                                      bool isVarArg,
3553                                                      bool isCalleeStructRet,
3554                                                      bool isCallerStructRet,
3555                                                      Type *RetTy,
3556                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3557                                     const SmallVectorImpl<SDValue> &OutVals,
3558                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3559                                                      SelectionDAG &DAG) const {
3560   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3561     return false;
3562
3563   // If -tailcallopt is specified, make fastcc functions tail-callable.
3564   const MachineFunction &MF = DAG.getMachineFunction();
3565   const Function *CallerF = MF.getFunction();
3566
3567   // If the function return type is x86_fp80 and the callee return type is not,
3568   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3569   // perform a tailcall optimization here.
3570   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3571     return false;
3572
3573   CallingConv::ID CallerCC = CallerF->getCallingConv();
3574   bool CCMatch = CallerCC == CalleeCC;
3575   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3576   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3577
3578   // Win64 functions have extra shadow space for argument homing. Don't do the
3579   // sibcall if the caller and callee have mismatched expectations for this
3580   // space.
3581   if (IsCalleeWin64 != IsCallerWin64)
3582     return false;
3583
3584   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3585     if (IsTailCallConvention(CalleeCC) && CCMatch)
3586       return true;
3587     return false;
3588   }
3589
3590   // Look for obvious safe cases to perform tail call optimization that do not
3591   // require ABI changes. This is what gcc calls sibcall.
3592
3593   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3594   // emit a special epilogue.
3595   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3596   if (RegInfo->needsStackRealignment(MF))
3597     return false;
3598
3599   // Also avoid sibcall optimization if either caller or callee uses struct
3600   // return semantics.
3601   if (isCalleeStructRet || isCallerStructRet)
3602     return false;
3603
3604   // An stdcall/thiscall caller is expected to clean up its arguments; the
3605   // callee isn't going to do that.
3606   // FIXME: this is more restrictive than needed. We could produce a tailcall
3607   // when the stack adjustment matches. For example, with a thiscall that takes
3608   // only one argument.
3609   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3610                    CallerCC == CallingConv::X86_ThisCall))
3611     return false;
3612
3613   // Do not sibcall optimize vararg calls unless all arguments are passed via
3614   // registers.
3615   if (isVarArg && !Outs.empty()) {
3616
3617     // Optimizing for varargs on Win64 is unlikely to be safe without
3618     // additional testing.
3619     if (IsCalleeWin64 || IsCallerWin64)
3620       return false;
3621
3622     SmallVector<CCValAssign, 16> ArgLocs;
3623     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3624                    *DAG.getContext());
3625
3626     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3627     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3628       if (!ArgLocs[i].isRegLoc())
3629         return false;
3630   }
3631
3632   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3633   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3634   // this into a sibcall.
3635   bool Unused = false;
3636   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3637     if (!Ins[i].Used) {
3638       Unused = true;
3639       break;
3640     }
3641   }
3642   if (Unused) {
3643     SmallVector<CCValAssign, 16> RVLocs;
3644     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3645                    *DAG.getContext());
3646     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3647     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3648       CCValAssign &VA = RVLocs[i];
3649       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3650         return false;
3651     }
3652   }
3653
3654   // If the calling conventions do not match, then we'd better make sure the
3655   // results are returned in the same way as what the caller expects.
3656   if (!CCMatch) {
3657     SmallVector<CCValAssign, 16> RVLocs1;
3658     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3659                     *DAG.getContext());
3660     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3661
3662     SmallVector<CCValAssign, 16> RVLocs2;
3663     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3664                     *DAG.getContext());
3665     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3666
3667     if (RVLocs1.size() != RVLocs2.size())
3668       return false;
3669     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3670       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3671         return false;
3672       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3673         return false;
3674       if (RVLocs1[i].isRegLoc()) {
3675         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3676           return false;
3677       } else {
3678         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3679           return false;
3680       }
3681     }
3682   }
3683
3684   // If the callee takes no arguments then go on to check the results of the
3685   // call.
3686   if (!Outs.empty()) {
3687     // Check if stack adjustment is needed. For now, do not do this if any
3688     // argument is passed on the stack.
3689     SmallVector<CCValAssign, 16> ArgLocs;
3690     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3691                    *DAG.getContext());
3692
3693     // Allocate shadow area for Win64
3694     if (IsCalleeWin64)
3695       CCInfo.AllocateStack(32, 8);
3696
3697     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3698     if (CCInfo.getNextStackOffset()) {
3699       MachineFunction &MF = DAG.getMachineFunction();
3700       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3701         return false;
3702
3703       // Check if the arguments are already laid out in the right way as
3704       // the caller's fixed stack objects.
3705       MachineFrameInfo *MFI = MF.getFrameInfo();
3706       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3707       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3708       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3709         CCValAssign &VA = ArgLocs[i];
3710         SDValue Arg = OutVals[i];
3711         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3712         if (VA.getLocInfo() == CCValAssign::Indirect)
3713           return false;
3714         if (!VA.isRegLoc()) {
3715           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3716                                    MFI, MRI, TII))
3717             return false;
3718         }
3719       }
3720     }
3721
3722     // If the tailcall address may be in a register, then make sure it's
3723     // possible to register allocate for it. In 32-bit, the call address can
3724     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3725     // callee-saved registers are restored. These happen to be the same
3726     // registers used to pass 'inreg' arguments so watch out for those.
3727     if (!Subtarget->is64Bit() &&
3728         ((!isa<GlobalAddressSDNode>(Callee) &&
3729           !isa<ExternalSymbolSDNode>(Callee)) ||
3730          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3731       unsigned NumInRegs = 0;
3732       // In PIC we need an extra register to formulate the address computation
3733       // for the callee.
3734       unsigned MaxInRegs =
3735         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3736
3737       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3738         CCValAssign &VA = ArgLocs[i];
3739         if (!VA.isRegLoc())
3740           continue;
3741         unsigned Reg = VA.getLocReg();
3742         switch (Reg) {
3743         default: break;
3744         case X86::EAX: case X86::EDX: case X86::ECX:
3745           if (++NumInRegs == MaxInRegs)
3746             return false;
3747           break;
3748         }
3749       }
3750     }
3751   }
3752
3753   return true;
3754 }
3755
3756 FastISel *
3757 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3758                                   const TargetLibraryInfo *libInfo) const {
3759   return X86::createFastISel(funcInfo, libInfo);
3760 }
3761
3762 //===----------------------------------------------------------------------===//
3763 //                           Other Lowering Hooks
3764 //===----------------------------------------------------------------------===//
3765
3766 static bool MayFoldLoad(SDValue Op) {
3767   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3768 }
3769
3770 static bool MayFoldIntoStore(SDValue Op) {
3771   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3772 }
3773
3774 static bool isTargetShuffle(unsigned Opcode) {
3775   switch(Opcode) {
3776   default: return false;
3777   case X86ISD::BLENDI:
3778   case X86ISD::PSHUFB:
3779   case X86ISD::PSHUFD:
3780   case X86ISD::PSHUFHW:
3781   case X86ISD::PSHUFLW:
3782   case X86ISD::SHUFP:
3783   case X86ISD::PALIGNR:
3784   case X86ISD::MOVLHPS:
3785   case X86ISD::MOVLHPD:
3786   case X86ISD::MOVHLPS:
3787   case X86ISD::MOVLPS:
3788   case X86ISD::MOVLPD:
3789   case X86ISD::MOVSHDUP:
3790   case X86ISD::MOVSLDUP:
3791   case X86ISD::MOVDDUP:
3792   case X86ISD::MOVSS:
3793   case X86ISD::MOVSD:
3794   case X86ISD::UNPCKL:
3795   case X86ISD::UNPCKH:
3796   case X86ISD::VPERMILPI:
3797   case X86ISD::VPERM2X128:
3798   case X86ISD::VPERMI:
3799   case X86ISD::VPERMV:
3800   case X86ISD::VPERMV3:
3801     return true;
3802   }
3803 }
3804
3805 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3806                                     SDValue V1, unsigned TargetMask,
3807                                     SelectionDAG &DAG) {
3808   switch(Opc) {
3809   default: llvm_unreachable("Unknown x86 shuffle node");
3810   case X86ISD::PSHUFD:
3811   case X86ISD::PSHUFHW:
3812   case X86ISD::PSHUFLW:
3813   case X86ISD::VPERMILPI:
3814   case X86ISD::VPERMI:
3815     return DAG.getNode(Opc, dl, VT, V1,
3816                        DAG.getConstant(TargetMask, dl, MVT::i8));
3817   }
3818 }
3819
3820 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3821                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3822   switch(Opc) {
3823   default: llvm_unreachable("Unknown x86 shuffle node");
3824   case X86ISD::MOVLHPS:
3825   case X86ISD::MOVLHPD:
3826   case X86ISD::MOVHLPS:
3827   case X86ISD::MOVLPS:
3828   case X86ISD::MOVLPD:
3829   case X86ISD::MOVSS:
3830   case X86ISD::MOVSD:
3831   case X86ISD::UNPCKL:
3832   case X86ISD::UNPCKH:
3833     return DAG.getNode(Opc, dl, VT, V1, V2);
3834   }
3835 }
3836
3837 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3838   MachineFunction &MF = DAG.getMachineFunction();
3839   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3840   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3841   int ReturnAddrIndex = FuncInfo->getRAIndex();
3842
3843   if (ReturnAddrIndex == 0) {
3844     // Set up a frame object for the return address.
3845     unsigned SlotSize = RegInfo->getSlotSize();
3846     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3847                                                            -(int64_t)SlotSize,
3848                                                            false);
3849     FuncInfo->setRAIndex(ReturnAddrIndex);
3850   }
3851
3852   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3853 }
3854
3855 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3856                                        bool hasSymbolicDisplacement) {
3857   // Offset should fit into 32 bit immediate field.
3858   if (!isInt<32>(Offset))
3859     return false;
3860
3861   // If we don't have a symbolic displacement - we don't have any extra
3862   // restrictions.
3863   if (!hasSymbolicDisplacement)
3864     return true;
3865
3866   // FIXME: Some tweaks might be needed for medium code model.
3867   if (M != CodeModel::Small && M != CodeModel::Kernel)
3868     return false;
3869
3870   // For small code model we assume that latest object is 16MB before end of 31
3871   // bits boundary. We may also accept pretty large negative constants knowing
3872   // that all objects are in the positive half of address space.
3873   if (M == CodeModel::Small && Offset < 16*1024*1024)
3874     return true;
3875
3876   // For kernel code model we know that all object resist in the negative half
3877   // of 32bits address space. We may not accept negative offsets, since they may
3878   // be just off and we may accept pretty large positive ones.
3879   if (M == CodeModel::Kernel && Offset >= 0)
3880     return true;
3881
3882   return false;
3883 }
3884
3885 /// Determines whether the callee is required to pop its own arguments.
3886 /// Callee pop is necessary to support tail calls.
3887 bool X86::isCalleePop(CallingConv::ID CallingConv,
3888                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3889   switch (CallingConv) {
3890   default:
3891     return false;
3892   case CallingConv::X86_StdCall:
3893   case CallingConv::X86_FastCall:
3894   case CallingConv::X86_ThisCall:
3895     return !is64Bit;
3896   case CallingConv::Fast:
3897   case CallingConv::GHC:
3898   case CallingConv::HiPE:
3899     if (IsVarArg)
3900       return false;
3901     return TailCallOpt;
3902   }
3903 }
3904
3905 /// \brief Return true if the condition is an unsigned comparison operation.
3906 static bool isX86CCUnsigned(unsigned X86CC) {
3907   switch (X86CC) {
3908   default: llvm_unreachable("Invalid integer condition!");
3909   case X86::COND_E:     return true;
3910   case X86::COND_G:     return false;
3911   case X86::COND_GE:    return false;
3912   case X86::COND_L:     return false;
3913   case X86::COND_LE:    return false;
3914   case X86::COND_NE:    return true;
3915   case X86::COND_B:     return true;
3916   case X86::COND_A:     return true;
3917   case X86::COND_BE:    return true;
3918   case X86::COND_AE:    return true;
3919   }
3920   llvm_unreachable("covered switch fell through?!");
3921 }
3922
3923 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3924 /// condition code, returning the condition code and the LHS/RHS of the
3925 /// comparison to make.
3926 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3927                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3928   if (!isFP) {
3929     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3930       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3931         // X > -1   -> X == 0, jump !sign.
3932         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3933         return X86::COND_NS;
3934       }
3935       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3936         // X < 0   -> X == 0, jump on sign.
3937         return X86::COND_S;
3938       }
3939       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3940         // X < 1   -> X <= 0
3941         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3942         return X86::COND_LE;
3943       }
3944     }
3945
3946     switch (SetCCOpcode) {
3947     default: llvm_unreachable("Invalid integer condition!");
3948     case ISD::SETEQ:  return X86::COND_E;
3949     case ISD::SETGT:  return X86::COND_G;
3950     case ISD::SETGE:  return X86::COND_GE;
3951     case ISD::SETLT:  return X86::COND_L;
3952     case ISD::SETLE:  return X86::COND_LE;
3953     case ISD::SETNE:  return X86::COND_NE;
3954     case ISD::SETULT: return X86::COND_B;
3955     case ISD::SETUGT: return X86::COND_A;
3956     case ISD::SETULE: return X86::COND_BE;
3957     case ISD::SETUGE: return X86::COND_AE;
3958     }
3959   }
3960
3961   // First determine if it is required or is profitable to flip the operands.
3962
3963   // If LHS is a foldable load, but RHS is not, flip the condition.
3964   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3965       !ISD::isNON_EXTLoad(RHS.getNode())) {
3966     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3967     std::swap(LHS, RHS);
3968   }
3969
3970   switch (SetCCOpcode) {
3971   default: break;
3972   case ISD::SETOLT:
3973   case ISD::SETOLE:
3974   case ISD::SETUGT:
3975   case ISD::SETUGE:
3976     std::swap(LHS, RHS);
3977     break;
3978   }
3979
3980   // On a floating point condition, the flags are set as follows:
3981   // ZF  PF  CF   op
3982   //  0 | 0 | 0 | X > Y
3983   //  0 | 0 | 1 | X < Y
3984   //  1 | 0 | 0 | X == Y
3985   //  1 | 1 | 1 | unordered
3986   switch (SetCCOpcode) {
3987   default: llvm_unreachable("Condcode should be pre-legalized away");
3988   case ISD::SETUEQ:
3989   case ISD::SETEQ:   return X86::COND_E;
3990   case ISD::SETOLT:              // flipped
3991   case ISD::SETOGT:
3992   case ISD::SETGT:   return X86::COND_A;
3993   case ISD::SETOLE:              // flipped
3994   case ISD::SETOGE:
3995   case ISD::SETGE:   return X86::COND_AE;
3996   case ISD::SETUGT:              // flipped
3997   case ISD::SETULT:
3998   case ISD::SETLT:   return X86::COND_B;
3999   case ISD::SETUGE:              // flipped
4000   case ISD::SETULE:
4001   case ISD::SETLE:   return X86::COND_BE;
4002   case ISD::SETONE:
4003   case ISD::SETNE:   return X86::COND_NE;
4004   case ISD::SETUO:   return X86::COND_P;
4005   case ISD::SETO:    return X86::COND_NP;
4006   case ISD::SETOEQ:
4007   case ISD::SETUNE:  return X86::COND_INVALID;
4008   }
4009 }
4010
4011 /// Is there a floating point cmov for the specific X86 condition code?
4012 /// Current x86 isa includes the following FP cmov instructions:
4013 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4014 static bool hasFPCMov(unsigned X86CC) {
4015   switch (X86CC) {
4016   default:
4017     return false;
4018   case X86::COND_B:
4019   case X86::COND_BE:
4020   case X86::COND_E:
4021   case X86::COND_P:
4022   case X86::COND_A:
4023   case X86::COND_AE:
4024   case X86::COND_NE:
4025   case X86::COND_NP:
4026     return true;
4027   }
4028 }
4029
4030 /// Returns true if the target can instruction select the
4031 /// specified FP immediate natively. If false, the legalizer will
4032 /// materialize the FP immediate as a load from a constant pool.
4033 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4034   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4035     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4036       return true;
4037   }
4038   return false;
4039 }
4040
4041 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4042                                               ISD::LoadExtType ExtTy,
4043                                               EVT NewVT) const {
4044   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4045   // relocation target a movq or addq instruction: don't let the load shrink.
4046   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4047   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4048     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4049       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4050   return true;
4051 }
4052
4053 /// \brief Returns true if it is beneficial to convert a load of a constant
4054 /// to just the constant itself.
4055 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4056                                                           Type *Ty) const {
4057   assert(Ty->isIntegerTy());
4058
4059   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4060   if (BitSize == 0 || BitSize > 64)
4061     return false;
4062   return true;
4063 }
4064
4065 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4066                                                 unsigned Index) const {
4067   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4068     return false;
4069
4070   return (Index == 0 || Index == ResVT.getVectorNumElements());
4071 }
4072
4073 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4074   // Speculate cttz only if we can directly use TZCNT.
4075   return Subtarget->hasBMI();
4076 }
4077
4078 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4079   // Speculate ctlz only if we can directly use LZCNT.
4080   return Subtarget->hasLZCNT();
4081 }
4082
4083 /// Return true if every element in Mask, beginning
4084 /// from position Pos and ending in Pos+Size is undef.
4085 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4086   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4087     if (0 <= Mask[i])
4088       return false;
4089   return true;
4090 }
4091
4092 /// Return true if Val is undef or if its value falls within the
4093 /// specified range (L, H].
4094 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4095   return (Val < 0) || (Val >= Low && Val < Hi);
4096 }
4097
4098 /// Val is either less than zero (undef) or equal to the specified value.
4099 static bool isUndefOrEqual(int Val, int CmpVal) {
4100   return (Val < 0 || Val == CmpVal);
4101 }
4102
4103 /// Return true if every element in Mask, beginning
4104 /// from position Pos and ending in Pos+Size, falls within the specified
4105 /// sequential range (Low, Low+Size]. or is undef.
4106 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4107                                        unsigned Pos, unsigned Size, int Low) {
4108   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4109     if (!isUndefOrEqual(Mask[i], Low))
4110       return false;
4111   return true;
4112 }
4113
4114 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4115 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4116 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4117   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4118   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4119     return false;
4120
4121   // The index should be aligned on a vecWidth-bit boundary.
4122   uint64_t Index =
4123     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4124
4125   MVT VT = N->getSimpleValueType(0);
4126   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4127   bool Result = (Index * ElSize) % vecWidth == 0;
4128
4129   return Result;
4130 }
4131
4132 /// Return true if the specified INSERT_SUBVECTOR
4133 /// operand specifies a subvector insert that is suitable for input to
4134 /// insertion of 128 or 256-bit subvectors
4135 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4136   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4137   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4138     return false;
4139   // The index should be aligned on a vecWidth-bit boundary.
4140   uint64_t Index =
4141     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4142
4143   MVT VT = N->getSimpleValueType(0);
4144   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4145   bool Result = (Index * ElSize) % vecWidth == 0;
4146
4147   return Result;
4148 }
4149
4150 bool X86::isVINSERT128Index(SDNode *N) {
4151   return isVINSERTIndex(N, 128);
4152 }
4153
4154 bool X86::isVINSERT256Index(SDNode *N) {
4155   return isVINSERTIndex(N, 256);
4156 }
4157
4158 bool X86::isVEXTRACT128Index(SDNode *N) {
4159   return isVEXTRACTIndex(N, 128);
4160 }
4161
4162 bool X86::isVEXTRACT256Index(SDNode *N) {
4163   return isVEXTRACTIndex(N, 256);
4164 }
4165
4166 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4167   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4168   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4169     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4170
4171   uint64_t Index =
4172     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4173
4174   MVT VecVT = N->getOperand(0).getSimpleValueType();
4175   MVT ElVT = VecVT.getVectorElementType();
4176
4177   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4178   return Index / NumElemsPerChunk;
4179 }
4180
4181 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4182   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4183   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4184     llvm_unreachable("Illegal insert subvector for VINSERT");
4185
4186   uint64_t Index =
4187     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4188
4189   MVT VecVT = N->getSimpleValueType(0);
4190   MVT ElVT = VecVT.getVectorElementType();
4191
4192   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4193   return Index / NumElemsPerChunk;
4194 }
4195
4196 /// Return the appropriate immediate to extract the specified
4197 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4198 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4199   return getExtractVEXTRACTImmediate(N, 128);
4200 }
4201
4202 /// Return the appropriate immediate to extract the specified
4203 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4204 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4205   return getExtractVEXTRACTImmediate(N, 256);
4206 }
4207
4208 /// Return the appropriate immediate to insert at the specified
4209 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4210 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4211   return getInsertVINSERTImmediate(N, 128);
4212 }
4213
4214 /// Return the appropriate immediate to insert at the specified
4215 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4216 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4217   return getInsertVINSERTImmediate(N, 256);
4218 }
4219
4220 /// Returns true if Elt is a constant integer zero
4221 static bool isZero(SDValue V) {
4222   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4223   return C && C->isNullValue();
4224 }
4225
4226 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4227 bool X86::isZeroNode(SDValue Elt) {
4228   if (isZero(Elt))
4229     return true;
4230   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4231     return CFP->getValueAPF().isPosZero();
4232   return false;
4233 }
4234
4235 /// Returns a vector of specified type with all zero elements.
4236 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4237                              SelectionDAG &DAG, SDLoc dl) {
4238   assert(VT.isVector() && "Expected a vector type");
4239
4240   // Always build SSE zero vectors as <4 x i32> bitcasted
4241   // to their dest type. This ensures they get CSE'd.
4242   SDValue Vec;
4243   if (VT.is128BitVector()) {  // SSE
4244     if (Subtarget->hasSSE2()) {  // SSE2
4245       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4246       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4247     } else { // SSE1
4248       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4249       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4250     }
4251   } else if (VT.is256BitVector()) { // AVX
4252     if (Subtarget->hasInt256()) { // AVX2
4253       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4254       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4255       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4256     } else {
4257       // 256-bit logic and arithmetic instructions in AVX are all
4258       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4259       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4260       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4261       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4262     }
4263   } else if (VT.is512BitVector()) { // AVX-512
4264       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4265       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4266                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4267       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4268   } else if (VT.getScalarType() == MVT::i1) {
4269
4270     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4271             && "Unexpected vector type");
4272     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4273             && "Unexpected vector type");
4274     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4275     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4276     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4277   } else
4278     llvm_unreachable("Unexpected vector type");
4279
4280   return DAG.getBitcast(VT, Vec);
4281 }
4282
4283 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4284                                 SelectionDAG &DAG, SDLoc dl,
4285                                 unsigned vectorWidth) {
4286   assert((vectorWidth == 128 || vectorWidth == 256) &&
4287          "Unsupported vector width");
4288   EVT VT = Vec.getValueType();
4289   EVT ElVT = VT.getVectorElementType();
4290   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4291   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4292                                   VT.getVectorNumElements()/Factor);
4293
4294   // Extract from UNDEF is UNDEF.
4295   if (Vec.getOpcode() == ISD::UNDEF)
4296     return DAG.getUNDEF(ResultVT);
4297
4298   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4299   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4300
4301   // This is the index of the first element of the vectorWidth-bit chunk
4302   // we want.
4303   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4304                                * ElemsPerChunk);
4305
4306   // If the input is a buildvector just emit a smaller one.
4307   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4308     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4309                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4310                                     ElemsPerChunk));
4311
4312   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4313   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4314 }
4315
4316 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4317 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4318 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4319 /// instructions or a simple subregister reference. Idx is an index in the
4320 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4321 /// lowering EXTRACT_VECTOR_ELT operations easier.
4322 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4323                                    SelectionDAG &DAG, SDLoc dl) {
4324   assert((Vec.getValueType().is256BitVector() ||
4325           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4326   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4327 }
4328
4329 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4330 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4331                                    SelectionDAG &DAG, SDLoc dl) {
4332   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4333   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4334 }
4335
4336 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4337                                unsigned IdxVal, SelectionDAG &DAG,
4338                                SDLoc dl, unsigned vectorWidth) {
4339   assert((vectorWidth == 128 || vectorWidth == 256) &&
4340          "Unsupported vector width");
4341   // Inserting UNDEF is Result
4342   if (Vec.getOpcode() == ISD::UNDEF)
4343     return Result;
4344   EVT VT = Vec.getValueType();
4345   EVT ElVT = VT.getVectorElementType();
4346   EVT ResultVT = Result.getValueType();
4347
4348   // Insert the relevant vectorWidth bits.
4349   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4350
4351   // This is the index of the first element of the vectorWidth-bit chunk
4352   // we want.
4353   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4354                                * ElemsPerChunk);
4355
4356   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4357   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4358 }
4359
4360 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4361 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4362 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4363 /// simple superregister reference.  Idx is an index in the 128 bits
4364 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4365 /// lowering INSERT_VECTOR_ELT operations easier.
4366 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4367                                   SelectionDAG &DAG, SDLoc dl) {
4368   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4369
4370   // For insertion into the zero index (low half) of a 256-bit vector, it is
4371   // more efficient to generate a blend with immediate instead of an insert*128.
4372   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4373   // extend the subvector to the size of the result vector. Make sure that
4374   // we are not recursing on that node by checking for undef here.
4375   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4376       Result.getOpcode() != ISD::UNDEF) {
4377     EVT ResultVT = Result.getValueType();
4378     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4379     SDValue Undef = DAG.getUNDEF(ResultVT);
4380     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4381                                  Vec, ZeroIndex);
4382
4383     // The blend instruction, and therefore its mask, depend on the data type.
4384     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4385     if (ScalarType.isFloatingPoint()) {
4386       // Choose either vblendps (float) or vblendpd (double).
4387       unsigned ScalarSize = ScalarType.getSizeInBits();
4388       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4389       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4390       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4391       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4392     }
4393
4394     const X86Subtarget &Subtarget =
4395     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4396
4397     // AVX2 is needed for 256-bit integer blend support.
4398     // Integers must be cast to 32-bit because there is only vpblendd;
4399     // vpblendw can't be used for this because it has a handicapped mask.
4400
4401     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4402     // is still more efficient than using the wrong domain vinsertf128 that
4403     // will be created by InsertSubVector().
4404     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4405
4406     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4407     Vec256 = DAG.getBitcast(CastVT, Vec256);
4408     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4409     return DAG.getBitcast(ResultVT, Vec256);
4410   }
4411
4412   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4413 }
4414
4415 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4416                                   SelectionDAG &DAG, SDLoc dl) {
4417   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4418   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4419 }
4420
4421 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4422 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4423 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4424 /// large BUILD_VECTORS.
4425 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4426                                    unsigned NumElems, SelectionDAG &DAG,
4427                                    SDLoc dl) {
4428   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4429   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4430 }
4431
4432 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4433                                    unsigned NumElems, SelectionDAG &DAG,
4434                                    SDLoc dl) {
4435   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4436   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4437 }
4438
4439 /// Returns a vector of specified type with all bits set.
4440 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4441 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4442 /// Then bitcast to their original type, ensuring they get CSE'd.
4443 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4444                              SDLoc dl) {
4445   assert(VT.isVector() && "Expected a vector type");
4446
4447   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4448   SDValue Vec;
4449   if (VT.is256BitVector()) {
4450     if (HasInt256) { // AVX2
4451       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4452       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4453     } else { // AVX
4454       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4455       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4456     }
4457   } else if (VT.is128BitVector()) {
4458     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4459   } else
4460     llvm_unreachable("Unexpected vector type");
4461
4462   return DAG.getBitcast(VT, Vec);
4463 }
4464
4465 /// Returns a vector_shuffle node for an unpackl operation.
4466 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4467                           SDValue V2) {
4468   unsigned NumElems = VT.getVectorNumElements();
4469   SmallVector<int, 8> Mask;
4470   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4471     Mask.push_back(i);
4472     Mask.push_back(i + NumElems);
4473   }
4474   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4475 }
4476
4477 /// Returns a vector_shuffle node for an unpackh operation.
4478 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4479                           SDValue V2) {
4480   unsigned NumElems = VT.getVectorNumElements();
4481   SmallVector<int, 8> Mask;
4482   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4483     Mask.push_back(i + Half);
4484     Mask.push_back(i + NumElems + Half);
4485   }
4486   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4487 }
4488
4489 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4490 /// This produces a shuffle where the low element of V2 is swizzled into the
4491 /// zero/undef vector, landing at element Idx.
4492 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4493 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4494                                            bool IsZero,
4495                                            const X86Subtarget *Subtarget,
4496                                            SelectionDAG &DAG) {
4497   MVT VT = V2.getSimpleValueType();
4498   SDValue V1 = IsZero
4499     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4500   unsigned NumElems = VT.getVectorNumElements();
4501   SmallVector<int, 16> MaskVec;
4502   for (unsigned i = 0; i != NumElems; ++i)
4503     // If this is the insertion idx, put the low elt of V2 here.
4504     MaskVec.push_back(i == Idx ? NumElems : i);
4505   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4506 }
4507
4508 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4509 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4510 /// uses one source. Note that this will set IsUnary for shuffles which use a
4511 /// single input multiple times, and in those cases it will
4512 /// adjust the mask to only have indices within that single input.
4513 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4514 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4515                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4516   unsigned NumElems = VT.getVectorNumElements();
4517   SDValue ImmN;
4518
4519   IsUnary = false;
4520   bool IsFakeUnary = false;
4521   switch(N->getOpcode()) {
4522   case X86ISD::BLENDI:
4523     ImmN = N->getOperand(N->getNumOperands()-1);
4524     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4525     break;
4526   case X86ISD::SHUFP:
4527     ImmN = N->getOperand(N->getNumOperands()-1);
4528     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4530     break;
4531   case X86ISD::UNPCKH:
4532     DecodeUNPCKHMask(VT, Mask);
4533     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4534     break;
4535   case X86ISD::UNPCKL:
4536     DecodeUNPCKLMask(VT, Mask);
4537     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4538     break;
4539   case X86ISD::MOVHLPS:
4540     DecodeMOVHLPSMask(NumElems, Mask);
4541     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4542     break;
4543   case X86ISD::MOVLHPS:
4544     DecodeMOVLHPSMask(NumElems, Mask);
4545     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4546     break;
4547   case X86ISD::PALIGNR:
4548     ImmN = N->getOperand(N->getNumOperands()-1);
4549     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4550     break;
4551   case X86ISD::PSHUFD:
4552   case X86ISD::VPERMILPI:
4553     ImmN = N->getOperand(N->getNumOperands()-1);
4554     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4555     IsUnary = true;
4556     break;
4557   case X86ISD::PSHUFHW:
4558     ImmN = N->getOperand(N->getNumOperands()-1);
4559     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4560     IsUnary = true;
4561     break;
4562   case X86ISD::PSHUFLW:
4563     ImmN = N->getOperand(N->getNumOperands()-1);
4564     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4565     IsUnary = true;
4566     break;
4567   case X86ISD::PSHUFB: {
4568     IsUnary = true;
4569     SDValue MaskNode = N->getOperand(1);
4570     while (MaskNode->getOpcode() == ISD::BITCAST)
4571       MaskNode = MaskNode->getOperand(0);
4572
4573     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4574       // If we have a build-vector, then things are easy.
4575       EVT VT = MaskNode.getValueType();
4576       assert(VT.isVector() &&
4577              "Can't produce a non-vector with a build_vector!");
4578       if (!VT.isInteger())
4579         return false;
4580
4581       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4582
4583       SmallVector<uint64_t, 32> RawMask;
4584       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4585         SDValue Op = MaskNode->getOperand(i);
4586         if (Op->getOpcode() == ISD::UNDEF) {
4587           RawMask.push_back((uint64_t)SM_SentinelUndef);
4588           continue;
4589         }
4590         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4591         if (!CN)
4592           return false;
4593         APInt MaskElement = CN->getAPIntValue();
4594
4595         // We now have to decode the element which could be any integer size and
4596         // extract each byte of it.
4597         for (int j = 0; j < NumBytesPerElement; ++j) {
4598           // Note that this is x86 and so always little endian: the low byte is
4599           // the first byte of the mask.
4600           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4601           MaskElement = MaskElement.lshr(8);
4602         }
4603       }
4604       DecodePSHUFBMask(RawMask, Mask);
4605       break;
4606     }
4607
4608     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4609     if (!MaskLoad)
4610       return false;
4611
4612     SDValue Ptr = MaskLoad->getBasePtr();
4613     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4614         Ptr->getOpcode() == X86ISD::WrapperRIP)
4615       Ptr = Ptr->getOperand(0);
4616
4617     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4618     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4619       return false;
4620
4621     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4622       DecodePSHUFBMask(C, Mask);
4623       if (Mask.empty())
4624         return false;
4625       break;
4626     }
4627
4628     return false;
4629   }
4630   case X86ISD::VPERMI:
4631     ImmN = N->getOperand(N->getNumOperands()-1);
4632     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4633     IsUnary = true;
4634     break;
4635   case X86ISD::MOVSS:
4636   case X86ISD::MOVSD:
4637     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4638     break;
4639   case X86ISD::VPERM2X128:
4640     ImmN = N->getOperand(N->getNumOperands()-1);
4641     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4642     if (Mask.empty()) return false;
4643     // Mask only contains negative index if an element is zero.
4644     if (std::any_of(Mask.begin(), Mask.end(),
4645                     [](int M){ return M == SM_SentinelZero; }))
4646       return false;
4647     break;
4648   case X86ISD::MOVSLDUP:
4649     DecodeMOVSLDUPMask(VT, Mask);
4650     IsUnary = true;
4651     break;
4652   case X86ISD::MOVSHDUP:
4653     DecodeMOVSHDUPMask(VT, Mask);
4654     IsUnary = true;
4655     break;
4656   case X86ISD::MOVDDUP:
4657     DecodeMOVDDUPMask(VT, Mask);
4658     IsUnary = true;
4659     break;
4660   case X86ISD::MOVLHPD:
4661   case X86ISD::MOVLPD:
4662   case X86ISD::MOVLPS:
4663     // Not yet implemented
4664     return false;
4665   case X86ISD::VPERMV: {
4666     IsUnary = true;
4667     SDValue MaskNode = N->getOperand(0);
4668     while (MaskNode->getOpcode() == ISD::BITCAST)
4669       MaskNode = MaskNode->getOperand(0);
4670
4671     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4672     SmallVector<uint64_t, 32> RawMask;
4673     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4674       // If we have a build-vector, then things are easy.
4675       assert(MaskNode.getValueType().isInteger() &&
4676              MaskNode.getValueType().getVectorNumElements() ==
4677              VT.getVectorNumElements());
4678
4679       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4680         SDValue Op = MaskNode->getOperand(i);
4681         if (Op->getOpcode() == ISD::UNDEF)
4682           RawMask.push_back((uint64_t)SM_SentinelUndef);
4683         else if (isa<ConstantSDNode>(Op)) {
4684           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4685           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4686         } else
4687           return false;
4688       }
4689       DecodeVPERMVMask(RawMask, Mask);
4690       break;
4691     }
4692     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4693       unsigned NumEltsInMask = MaskNode->getNumOperands();
4694       MaskNode = MaskNode->getOperand(0);
4695       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4696       if (CN) {
4697         APInt MaskEltValue = CN->getAPIntValue();
4698         for (unsigned i = 0; i < NumEltsInMask; ++i)
4699           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4700         DecodeVPERMVMask(RawMask, Mask);
4701         break;
4702       }
4703       // It may be a scalar load
4704     }
4705
4706     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4707     if (!MaskLoad)
4708       return false;
4709
4710     SDValue Ptr = MaskLoad->getBasePtr();
4711     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4712         Ptr->getOpcode() == X86ISD::WrapperRIP)
4713       Ptr = Ptr->getOperand(0);
4714
4715     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4716     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4717       return false;
4718
4719     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4720     if (C) {
4721       DecodeVPERMVMask(C, VT, Mask);
4722       if (Mask.empty())
4723         return false;
4724       break;
4725     }
4726     return false;
4727   }
4728   case X86ISD::VPERMV3: {
4729     IsUnary = false;
4730     SDValue MaskNode = N->getOperand(1);
4731     while (MaskNode->getOpcode() == ISD::BITCAST)
4732       MaskNode = MaskNode->getOperand(1);
4733
4734     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4735       // If we have a build-vector, then things are easy.
4736       assert(MaskNode.getValueType().isInteger() &&
4737              MaskNode.getValueType().getVectorNumElements() ==
4738              VT.getVectorNumElements());
4739
4740       SmallVector<uint64_t, 32> RawMask;
4741       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4742
4743       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4744         SDValue Op = MaskNode->getOperand(i);
4745         if (Op->getOpcode() == ISD::UNDEF)
4746           RawMask.push_back((uint64_t)SM_SentinelUndef);
4747         else {
4748           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4749           if (!CN)
4750             return false;
4751           APInt MaskElement = CN->getAPIntValue();
4752           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4753         }
4754       }
4755       DecodeVPERMV3Mask(RawMask, Mask);
4756       break;
4757     }
4758
4759     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4760     if (!MaskLoad)
4761       return false;
4762
4763     SDValue Ptr = MaskLoad->getBasePtr();
4764     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4765         Ptr->getOpcode() == X86ISD::WrapperRIP)
4766       Ptr = Ptr->getOperand(0);
4767
4768     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4769     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4770       return false;
4771
4772     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4773     if (C) {
4774       DecodeVPERMV3Mask(C, VT, Mask);
4775       if (Mask.empty())
4776         return false;
4777       break;
4778     }
4779     return false;
4780   }
4781   default: llvm_unreachable("unknown target shuffle node");
4782   }
4783
4784   // If we have a fake unary shuffle, the shuffle mask is spread across two
4785   // inputs that are actually the same node. Re-map the mask to always point
4786   // into the first input.
4787   if (IsFakeUnary)
4788     for (int &M : Mask)
4789       if (M >= (int)Mask.size())
4790         M -= Mask.size();
4791
4792   return true;
4793 }
4794
4795 /// Returns the scalar element that will make up the ith
4796 /// element of the result of the vector shuffle.
4797 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4798                                    unsigned Depth) {
4799   if (Depth == 6)
4800     return SDValue();  // Limit search depth.
4801
4802   SDValue V = SDValue(N, 0);
4803   EVT VT = V.getValueType();
4804   unsigned Opcode = V.getOpcode();
4805
4806   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4807   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4808     int Elt = SV->getMaskElt(Index);
4809
4810     if (Elt < 0)
4811       return DAG.getUNDEF(VT.getVectorElementType());
4812
4813     unsigned NumElems = VT.getVectorNumElements();
4814     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4815                                          : SV->getOperand(1);
4816     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4817   }
4818
4819   // Recurse into target specific vector shuffles to find scalars.
4820   if (isTargetShuffle(Opcode)) {
4821     MVT ShufVT = V.getSimpleValueType();
4822     unsigned NumElems = ShufVT.getVectorNumElements();
4823     SmallVector<int, 16> ShuffleMask;
4824     bool IsUnary;
4825
4826     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4827       return SDValue();
4828
4829     int Elt = ShuffleMask[Index];
4830     if (Elt < 0)
4831       return DAG.getUNDEF(ShufVT.getVectorElementType());
4832
4833     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4834                                          : N->getOperand(1);
4835     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4836                                Depth+1);
4837   }
4838
4839   // Actual nodes that may contain scalar elements
4840   if (Opcode == ISD::BITCAST) {
4841     V = V.getOperand(0);
4842     EVT SrcVT = V.getValueType();
4843     unsigned NumElems = VT.getVectorNumElements();
4844
4845     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4846       return SDValue();
4847   }
4848
4849   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4850     return (Index == 0) ? V.getOperand(0)
4851                         : DAG.getUNDEF(VT.getVectorElementType());
4852
4853   if (V.getOpcode() == ISD::BUILD_VECTOR)
4854     return V.getOperand(Index);
4855
4856   return SDValue();
4857 }
4858
4859 /// Custom lower build_vector of v16i8.
4860 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4861                                        unsigned NumNonZero, unsigned NumZero,
4862                                        SelectionDAG &DAG,
4863                                        const X86Subtarget* Subtarget,
4864                                        const TargetLowering &TLI) {
4865   if (NumNonZero > 8)
4866     return SDValue();
4867
4868   SDLoc dl(Op);
4869   SDValue V;
4870   bool First = true;
4871
4872   // SSE4.1 - use PINSRB to insert each byte directly.
4873   if (Subtarget->hasSSE41()) {
4874     for (unsigned i = 0; i < 16; ++i) {
4875       bool isNonZero = (NonZeros & (1 << i)) != 0;
4876       if (isNonZero) {
4877         if (First) {
4878           if (NumZero)
4879             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4880           else
4881             V = DAG.getUNDEF(MVT::v16i8);
4882           First = false;
4883         }
4884         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4885                         MVT::v16i8, V, Op.getOperand(i),
4886                         DAG.getIntPtrConstant(i, dl));
4887       }
4888     }
4889
4890     return V;
4891   }
4892
4893   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4894   for (unsigned i = 0; i < 16; ++i) {
4895     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4896     if (ThisIsNonZero && First) {
4897       if (NumZero)
4898         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4899       else
4900         V = DAG.getUNDEF(MVT::v8i16);
4901       First = false;
4902     }
4903
4904     if ((i & 1) != 0) {
4905       SDValue ThisElt, LastElt;
4906       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4907       if (LastIsNonZero) {
4908         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4909                               MVT::i16, Op.getOperand(i-1));
4910       }
4911       if (ThisIsNonZero) {
4912         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4913         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4914                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4915         if (LastIsNonZero)
4916           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4917       } else
4918         ThisElt = LastElt;
4919
4920       if (ThisElt.getNode())
4921         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4922                         DAG.getIntPtrConstant(i/2, dl));
4923     }
4924   }
4925
4926   return DAG.getBitcast(MVT::v16i8, V);
4927 }
4928
4929 /// Custom lower build_vector of v8i16.
4930 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4931                                      unsigned NumNonZero, unsigned NumZero,
4932                                      SelectionDAG &DAG,
4933                                      const X86Subtarget* Subtarget,
4934                                      const TargetLowering &TLI) {
4935   if (NumNonZero > 4)
4936     return SDValue();
4937
4938   SDLoc dl(Op);
4939   SDValue V;
4940   bool First = true;
4941   for (unsigned i = 0; i < 8; ++i) {
4942     bool isNonZero = (NonZeros & (1 << i)) != 0;
4943     if (isNonZero) {
4944       if (First) {
4945         if (NumZero)
4946           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4947         else
4948           V = DAG.getUNDEF(MVT::v8i16);
4949         First = false;
4950       }
4951       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4952                       MVT::v8i16, V, Op.getOperand(i),
4953                       DAG.getIntPtrConstant(i, dl));
4954     }
4955   }
4956
4957   return V;
4958 }
4959
4960 /// Custom lower build_vector of v4i32 or v4f32.
4961 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4962                                      const X86Subtarget *Subtarget,
4963                                      const TargetLowering &TLI) {
4964   // Find all zeroable elements.
4965   std::bitset<4> Zeroable;
4966   for (int i=0; i < 4; ++i) {
4967     SDValue Elt = Op->getOperand(i);
4968     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4969   }
4970   assert(Zeroable.size() - Zeroable.count() > 1 &&
4971          "We expect at least two non-zero elements!");
4972
4973   // We only know how to deal with build_vector nodes where elements are either
4974   // zeroable or extract_vector_elt with constant index.
4975   SDValue FirstNonZero;
4976   unsigned FirstNonZeroIdx;
4977   for (unsigned i=0; i < 4; ++i) {
4978     if (Zeroable[i])
4979       continue;
4980     SDValue Elt = Op->getOperand(i);
4981     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4982         !isa<ConstantSDNode>(Elt.getOperand(1)))
4983       return SDValue();
4984     // Make sure that this node is extracting from a 128-bit vector.
4985     MVT VT = Elt.getOperand(0).getSimpleValueType();
4986     if (!VT.is128BitVector())
4987       return SDValue();
4988     if (!FirstNonZero.getNode()) {
4989       FirstNonZero = Elt;
4990       FirstNonZeroIdx = i;
4991     }
4992   }
4993
4994   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4995   SDValue V1 = FirstNonZero.getOperand(0);
4996   MVT VT = V1.getSimpleValueType();
4997
4998   // See if this build_vector can be lowered as a blend with zero.
4999   SDValue Elt;
5000   unsigned EltMaskIdx, EltIdx;
5001   int Mask[4];
5002   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5003     if (Zeroable[EltIdx]) {
5004       // The zero vector will be on the right hand side.
5005       Mask[EltIdx] = EltIdx+4;
5006       continue;
5007     }
5008
5009     Elt = Op->getOperand(EltIdx);
5010     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5011     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5012     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5013       break;
5014     Mask[EltIdx] = EltIdx;
5015   }
5016
5017   if (EltIdx == 4) {
5018     // Let the shuffle legalizer deal with blend operations.
5019     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5020     if (V1.getSimpleValueType() != VT)
5021       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5022     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5023   }
5024
5025   // See if we can lower this build_vector to a INSERTPS.
5026   if (!Subtarget->hasSSE41())
5027     return SDValue();
5028
5029   SDValue V2 = Elt.getOperand(0);
5030   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5031     V1 = SDValue();
5032
5033   bool CanFold = true;
5034   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5035     if (Zeroable[i])
5036       continue;
5037
5038     SDValue Current = Op->getOperand(i);
5039     SDValue SrcVector = Current->getOperand(0);
5040     if (!V1.getNode())
5041       V1 = SrcVector;
5042     CanFold = SrcVector == V1 &&
5043       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5044   }
5045
5046   if (!CanFold)
5047     return SDValue();
5048
5049   assert(V1.getNode() && "Expected at least two non-zero elements!");
5050   if (V1.getSimpleValueType() != MVT::v4f32)
5051     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5052   if (V2.getSimpleValueType() != MVT::v4f32)
5053     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5054
5055   // Ok, we can emit an INSERTPS instruction.
5056   unsigned ZMask = Zeroable.to_ulong();
5057
5058   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5059   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5060   SDLoc DL(Op);
5061   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5062                                DAG.getIntPtrConstant(InsertPSMask, DL));
5063   return DAG.getBitcast(VT, Result);
5064 }
5065
5066 /// Return a vector logical shift node.
5067 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5068                          unsigned NumBits, SelectionDAG &DAG,
5069                          const TargetLowering &TLI, SDLoc dl) {
5070   assert(VT.is128BitVector() && "Unknown type for VShift");
5071   MVT ShVT = MVT::v2i64;
5072   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5073   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5074   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5075   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5076   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5077   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5078 }
5079
5080 static SDValue
5081 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5082
5083   // Check if the scalar load can be widened into a vector load. And if
5084   // the address is "base + cst" see if the cst can be "absorbed" into
5085   // the shuffle mask.
5086   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5087     SDValue Ptr = LD->getBasePtr();
5088     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5089       return SDValue();
5090     EVT PVT = LD->getValueType(0);
5091     if (PVT != MVT::i32 && PVT != MVT::f32)
5092       return SDValue();
5093
5094     int FI = -1;
5095     int64_t Offset = 0;
5096     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5097       FI = FINode->getIndex();
5098       Offset = 0;
5099     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5100                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5101       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5102       Offset = Ptr.getConstantOperandVal(1);
5103       Ptr = Ptr.getOperand(0);
5104     } else {
5105       return SDValue();
5106     }
5107
5108     // FIXME: 256-bit vector instructions don't require a strict alignment,
5109     // improve this code to support it better.
5110     unsigned RequiredAlign = VT.getSizeInBits()/8;
5111     SDValue Chain = LD->getChain();
5112     // Make sure the stack object alignment is at least 16 or 32.
5113     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5114     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5115       if (MFI->isFixedObjectIndex(FI)) {
5116         // Can't change the alignment. FIXME: It's possible to compute
5117         // the exact stack offset and reference FI + adjust offset instead.
5118         // If someone *really* cares about this. That's the way to implement it.
5119         return SDValue();
5120       } else {
5121         MFI->setObjectAlignment(FI, RequiredAlign);
5122       }
5123     }
5124
5125     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5126     // Ptr + (Offset & ~15).
5127     if (Offset < 0)
5128       return SDValue();
5129     if ((Offset % RequiredAlign) & 3)
5130       return SDValue();
5131     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5132     if (StartOffset) {
5133       SDLoc DL(Ptr);
5134       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5135                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5136     }
5137
5138     int EltNo = (Offset - StartOffset) >> 2;
5139     unsigned NumElems = VT.getVectorNumElements();
5140
5141     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5142     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5143                              LD->getPointerInfo().getWithOffset(StartOffset),
5144                              false, false, false, 0);
5145
5146     SmallVector<int, 8> Mask(NumElems, EltNo);
5147
5148     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5149   }
5150
5151   return SDValue();
5152 }
5153
5154 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5155 /// elements can be replaced by a single large load which has the same value as
5156 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5157 ///
5158 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5159 ///
5160 /// FIXME: we'd also like to handle the case where the last elements are zero
5161 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5162 /// There's even a handy isZeroNode for that purpose.
5163 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5164                                         SDLoc &DL, SelectionDAG &DAG,
5165                                         bool isAfterLegalize) {
5166   unsigned NumElems = Elts.size();
5167
5168   LoadSDNode *LDBase = nullptr;
5169   unsigned LastLoadedElt = -1U;
5170
5171   // For each element in the initializer, see if we've found a load or an undef.
5172   // If we don't find an initial load element, or later load elements are
5173   // non-consecutive, bail out.
5174   for (unsigned i = 0; i < NumElems; ++i) {
5175     SDValue Elt = Elts[i];
5176     // Look through a bitcast.
5177     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5178       Elt = Elt.getOperand(0);
5179     if (!Elt.getNode() ||
5180         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5181       return SDValue();
5182     if (!LDBase) {
5183       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5184         return SDValue();
5185       LDBase = cast<LoadSDNode>(Elt.getNode());
5186       LastLoadedElt = i;
5187       continue;
5188     }
5189     if (Elt.getOpcode() == ISD::UNDEF)
5190       continue;
5191
5192     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5193     EVT LdVT = Elt.getValueType();
5194     // Each loaded element must be the correct fractional portion of the
5195     // requested vector load.
5196     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5197       return SDValue();
5198     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5199       return SDValue();
5200     LastLoadedElt = i;
5201   }
5202
5203   // If we have found an entire vector of loads and undefs, then return a large
5204   // load of the entire vector width starting at the base pointer.  If we found
5205   // consecutive loads for the low half, generate a vzext_load node.
5206   if (LastLoadedElt == NumElems - 1) {
5207     assert(LDBase && "Did not find base load for merging consecutive loads");
5208     EVT EltVT = LDBase->getValueType(0);
5209     // Ensure that the input vector size for the merged loads matches the
5210     // cumulative size of the input elements.
5211     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5212       return SDValue();
5213
5214     if (isAfterLegalize &&
5215         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5216       return SDValue();
5217
5218     SDValue NewLd = SDValue();
5219
5220     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5221                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5222                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5223                         LDBase->getAlignment());
5224
5225     if (LDBase->hasAnyUseOfValue(1)) {
5226       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5227                                      SDValue(LDBase, 1),
5228                                      SDValue(NewLd.getNode(), 1));
5229       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5230       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5231                              SDValue(NewLd.getNode(), 1));
5232     }
5233
5234     return NewLd;
5235   }
5236
5237   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5238   //of a v4i32 / v4f32. It's probably worth generalizing.
5239   EVT EltVT = VT.getVectorElementType();
5240   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5241       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5242     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5243     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5244     SDValue ResNode =
5245         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5246                                 LDBase->getPointerInfo(),
5247                                 LDBase->getAlignment(),
5248                                 false/*isVolatile*/, true/*ReadMem*/,
5249                                 false/*WriteMem*/);
5250
5251     // Make sure the newly-created LOAD is in the same position as LDBase in
5252     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5253     // update uses of LDBase's output chain to use the TokenFactor.
5254     if (LDBase->hasAnyUseOfValue(1)) {
5255       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5256                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5257       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5258       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5259                              SDValue(ResNode.getNode(), 1));
5260     }
5261
5262     return DAG.getBitcast(VT, ResNode);
5263   }
5264   return SDValue();
5265 }
5266
5267 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5268 /// to generate a splat value for the following cases:
5269 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5270 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5271 /// a scalar load, or a constant.
5272 /// The VBROADCAST node is returned when a pattern is found,
5273 /// or SDValue() otherwise.
5274 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5275                                     SelectionDAG &DAG) {
5276   // VBROADCAST requires AVX.
5277   // TODO: Splats could be generated for non-AVX CPUs using SSE
5278   // instructions, but there's less potential gain for only 128-bit vectors.
5279   if (!Subtarget->hasAVX())
5280     return SDValue();
5281
5282   MVT VT = Op.getSimpleValueType();
5283   SDLoc dl(Op);
5284
5285   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5286          "Unsupported vector type for broadcast.");
5287
5288   SDValue Ld;
5289   bool ConstSplatVal;
5290
5291   switch (Op.getOpcode()) {
5292     default:
5293       // Unknown pattern found.
5294       return SDValue();
5295
5296     case ISD::BUILD_VECTOR: {
5297       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5298       BitVector UndefElements;
5299       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5300
5301       // We need a splat of a single value to use broadcast, and it doesn't
5302       // make any sense if the value is only in one element of the vector.
5303       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5304         return SDValue();
5305
5306       Ld = Splat;
5307       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5308                        Ld.getOpcode() == ISD::ConstantFP);
5309
5310       // Make sure that all of the users of a non-constant load are from the
5311       // BUILD_VECTOR node.
5312       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5313         return SDValue();
5314       break;
5315     }
5316
5317     case ISD::VECTOR_SHUFFLE: {
5318       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5319
5320       // Shuffles must have a splat mask where the first element is
5321       // broadcasted.
5322       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5323         return SDValue();
5324
5325       SDValue Sc = Op.getOperand(0);
5326       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5327           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5328
5329         if (!Subtarget->hasInt256())
5330           return SDValue();
5331
5332         // Use the register form of the broadcast instruction available on AVX2.
5333         if (VT.getSizeInBits() >= 256)
5334           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5335         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5336       }
5337
5338       Ld = Sc.getOperand(0);
5339       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5340                        Ld.getOpcode() == ISD::ConstantFP);
5341
5342       // The scalar_to_vector node and the suspected
5343       // load node must have exactly one user.
5344       // Constants may have multiple users.
5345
5346       // AVX-512 has register version of the broadcast
5347       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5348         Ld.getValueType().getSizeInBits() >= 32;
5349       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5350           !hasRegVer))
5351         return SDValue();
5352       break;
5353     }
5354   }
5355
5356   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5357   bool IsGE256 = (VT.getSizeInBits() >= 256);
5358
5359   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5360   // instruction to save 8 or more bytes of constant pool data.
5361   // TODO: If multiple splats are generated to load the same constant,
5362   // it may be detrimental to overall size. There needs to be a way to detect
5363   // that condition to know if this is truly a size win.
5364   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5365
5366   // Handle broadcasting a single constant scalar from the constant pool
5367   // into a vector.
5368   // On Sandybridge (no AVX2), it is still better to load a constant vector
5369   // from the constant pool and not to broadcast it from a scalar.
5370   // But override that restriction when optimizing for size.
5371   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5372   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5373     EVT CVT = Ld.getValueType();
5374     assert(!CVT.isVector() && "Must not broadcast a vector type");
5375
5376     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5377     // For size optimization, also splat v2f64 and v2i64, and for size opt
5378     // with AVX2, also splat i8 and i16.
5379     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5380     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5381         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5382       const Constant *C = nullptr;
5383       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5384         C = CI->getConstantIntValue();
5385       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5386         C = CF->getConstantFPValue();
5387
5388       assert(C && "Invalid constant type");
5389
5390       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5391       SDValue CP =
5392           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5393       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5394       Ld = DAG.getLoad(
5395           CVT, dl, DAG.getEntryNode(), CP,
5396           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5397           false, false, Alignment);
5398
5399       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5400     }
5401   }
5402
5403   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5404
5405   // Handle AVX2 in-register broadcasts.
5406   if (!IsLoad && Subtarget->hasInt256() &&
5407       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5408     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5409
5410   // The scalar source must be a normal load.
5411   if (!IsLoad)
5412     return SDValue();
5413
5414   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5415       (Subtarget->hasVLX() && ScalarSize == 64))
5416     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5417
5418   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5419   // double since there is no vbroadcastsd xmm
5420   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5421     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5422       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5423   }
5424
5425   // Unsupported broadcast.
5426   return SDValue();
5427 }
5428
5429 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5430 /// underlying vector and index.
5431 ///
5432 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5433 /// index.
5434 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5435                                          SDValue ExtIdx) {
5436   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5437   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5438     return Idx;
5439
5440   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5441   // lowered this:
5442   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5443   // to:
5444   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5445   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5446   //                           undef)
5447   //                       Constant<0>)
5448   // In this case the vector is the extract_subvector expression and the index
5449   // is 2, as specified by the shuffle.
5450   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5451   SDValue ShuffleVec = SVOp->getOperand(0);
5452   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5453   assert(ShuffleVecVT.getVectorElementType() ==
5454          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5455
5456   int ShuffleIdx = SVOp->getMaskElt(Idx);
5457   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5458     ExtractedFromVec = ShuffleVec;
5459     return ShuffleIdx;
5460   }
5461   return Idx;
5462 }
5463
5464 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5465   MVT VT = Op.getSimpleValueType();
5466
5467   // Skip if insert_vec_elt is not supported.
5468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5469   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5470     return SDValue();
5471
5472   SDLoc DL(Op);
5473   unsigned NumElems = Op.getNumOperands();
5474
5475   SDValue VecIn1;
5476   SDValue VecIn2;
5477   SmallVector<unsigned, 4> InsertIndices;
5478   SmallVector<int, 8> Mask(NumElems, -1);
5479
5480   for (unsigned i = 0; i != NumElems; ++i) {
5481     unsigned Opc = Op.getOperand(i).getOpcode();
5482
5483     if (Opc == ISD::UNDEF)
5484       continue;
5485
5486     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5487       // Quit if more than 1 elements need inserting.
5488       if (InsertIndices.size() > 1)
5489         return SDValue();
5490
5491       InsertIndices.push_back(i);
5492       continue;
5493     }
5494
5495     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5496     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5497     // Quit if non-constant index.
5498     if (!isa<ConstantSDNode>(ExtIdx))
5499       return SDValue();
5500     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5501
5502     // Quit if extracted from vector of different type.
5503     if (ExtractedFromVec.getValueType() != VT)
5504       return SDValue();
5505
5506     if (!VecIn1.getNode())
5507       VecIn1 = ExtractedFromVec;
5508     else if (VecIn1 != ExtractedFromVec) {
5509       if (!VecIn2.getNode())
5510         VecIn2 = ExtractedFromVec;
5511       else if (VecIn2 != ExtractedFromVec)
5512         // Quit if more than 2 vectors to shuffle
5513         return SDValue();
5514     }
5515
5516     if (ExtractedFromVec == VecIn1)
5517       Mask[i] = Idx;
5518     else if (ExtractedFromVec == VecIn2)
5519       Mask[i] = Idx + NumElems;
5520   }
5521
5522   if (!VecIn1.getNode())
5523     return SDValue();
5524
5525   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5526   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5527   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5528     unsigned Idx = InsertIndices[i];
5529     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5530                      DAG.getIntPtrConstant(Idx, DL));
5531   }
5532
5533   return NV;
5534 }
5535
5536 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5537   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5538          Op.getScalarValueSizeInBits() == 1 &&
5539          "Can not convert non-constant vector");
5540   uint64_t Immediate = 0;
5541   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5542     SDValue In = Op.getOperand(idx);
5543     if (In.getOpcode() != ISD::UNDEF)
5544       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5545   }
5546   SDLoc dl(Op);
5547   MVT VT =
5548    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5549   return DAG.getConstant(Immediate, dl, VT);
5550 }
5551 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5552 SDValue
5553 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5554
5555   MVT VT = Op.getSimpleValueType();
5556   assert((VT.getVectorElementType() == MVT::i1) &&
5557          "Unexpected type in LowerBUILD_VECTORvXi1!");
5558
5559   SDLoc dl(Op);
5560   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5561     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5562     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5563     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5564   }
5565
5566   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5567     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5568     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5569     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5570   }
5571
5572   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5573     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5574     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5575       return DAG.getBitcast(VT, Imm);
5576     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5577     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5578                         DAG.getIntPtrConstant(0, dl));
5579   }
5580
5581   // Vector has one or more non-const elements
5582   uint64_t Immediate = 0;
5583   SmallVector<unsigned, 16> NonConstIdx;
5584   bool IsSplat = true;
5585   bool HasConstElts = false;
5586   int SplatIdx = -1;
5587   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5588     SDValue In = Op.getOperand(idx);
5589     if (In.getOpcode() == ISD::UNDEF)
5590       continue;
5591     if (!isa<ConstantSDNode>(In))
5592       NonConstIdx.push_back(idx);
5593     else {
5594       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5595       HasConstElts = true;
5596     }
5597     if (SplatIdx == -1)
5598       SplatIdx = idx;
5599     else if (In != Op.getOperand(SplatIdx))
5600       IsSplat = false;
5601   }
5602
5603   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5604   if (IsSplat)
5605     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5606                        DAG.getConstant(1, dl, VT),
5607                        DAG.getConstant(0, dl, VT));
5608
5609   // insert elements one by one
5610   SDValue DstVec;
5611   SDValue Imm;
5612   if (Immediate) {
5613     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5614     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5615   }
5616   else if (HasConstElts)
5617     Imm = DAG.getConstant(0, dl, VT);
5618   else
5619     Imm = DAG.getUNDEF(VT);
5620   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5621     DstVec = DAG.getBitcast(VT, Imm);
5622   else {
5623     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5624     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5625                          DAG.getIntPtrConstant(0, dl));
5626   }
5627
5628   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5629     unsigned InsertIdx = NonConstIdx[i];
5630     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5631                          Op.getOperand(InsertIdx),
5632                          DAG.getIntPtrConstant(InsertIdx, dl));
5633   }
5634   return DstVec;
5635 }
5636
5637 /// \brief Return true if \p N implements a horizontal binop and return the
5638 /// operands for the horizontal binop into V0 and V1.
5639 ///
5640 /// This is a helper function of LowerToHorizontalOp().
5641 /// This function checks that the build_vector \p N in input implements a
5642 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5643 /// operation to match.
5644 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5645 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5646 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5647 /// arithmetic sub.
5648 ///
5649 /// This function only analyzes elements of \p N whose indices are
5650 /// in range [BaseIdx, LastIdx).
5651 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5652                               SelectionDAG &DAG,
5653                               unsigned BaseIdx, unsigned LastIdx,
5654                               SDValue &V0, SDValue &V1) {
5655   EVT VT = N->getValueType(0);
5656
5657   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5658   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5659          "Invalid Vector in input!");
5660
5661   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5662   bool CanFold = true;
5663   unsigned ExpectedVExtractIdx = BaseIdx;
5664   unsigned NumElts = LastIdx - BaseIdx;
5665   V0 = DAG.getUNDEF(VT);
5666   V1 = DAG.getUNDEF(VT);
5667
5668   // Check if N implements a horizontal binop.
5669   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5670     SDValue Op = N->getOperand(i + BaseIdx);
5671
5672     // Skip UNDEFs.
5673     if (Op->getOpcode() == ISD::UNDEF) {
5674       // Update the expected vector extract index.
5675       if (i * 2 == NumElts)
5676         ExpectedVExtractIdx = BaseIdx;
5677       ExpectedVExtractIdx += 2;
5678       continue;
5679     }
5680
5681     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5682
5683     if (!CanFold)
5684       break;
5685
5686     SDValue Op0 = Op.getOperand(0);
5687     SDValue Op1 = Op.getOperand(1);
5688
5689     // Try to match the following pattern:
5690     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5691     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5692         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5693         Op0.getOperand(0) == Op1.getOperand(0) &&
5694         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5695         isa<ConstantSDNode>(Op1.getOperand(1)));
5696     if (!CanFold)
5697       break;
5698
5699     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5700     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5701
5702     if (i * 2 < NumElts) {
5703       if (V0.getOpcode() == ISD::UNDEF) {
5704         V0 = Op0.getOperand(0);
5705         if (V0.getValueType() != VT)
5706           return false;
5707       }
5708     } else {
5709       if (V1.getOpcode() == ISD::UNDEF) {
5710         V1 = Op0.getOperand(0);
5711         if (V1.getValueType() != VT)
5712           return false;
5713       }
5714       if (i * 2 == NumElts)
5715         ExpectedVExtractIdx = BaseIdx;
5716     }
5717
5718     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5719     if (I0 == ExpectedVExtractIdx)
5720       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5721     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5722       // Try to match the following dag sequence:
5723       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5724       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5725     } else
5726       CanFold = false;
5727
5728     ExpectedVExtractIdx += 2;
5729   }
5730
5731   return CanFold;
5732 }
5733
5734 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5735 /// a concat_vector.
5736 ///
5737 /// This is a helper function of LowerToHorizontalOp().
5738 /// This function expects two 256-bit vectors called V0 and V1.
5739 /// At first, each vector is split into two separate 128-bit vectors.
5740 /// Then, the resulting 128-bit vectors are used to implement two
5741 /// horizontal binary operations.
5742 ///
5743 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5744 ///
5745 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5746 /// the two new horizontal binop.
5747 /// When Mode is set, the first horizontal binop dag node would take as input
5748 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5749 /// horizontal binop dag node would take as input the lower 128-bit of V1
5750 /// and the upper 128-bit of V1.
5751 ///   Example:
5752 ///     HADD V0_LO, V0_HI
5753 ///     HADD V1_LO, V1_HI
5754 ///
5755 /// Otherwise, the first horizontal binop dag node takes as input the lower
5756 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5757 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5758 ///   Example:
5759 ///     HADD V0_LO, V1_LO
5760 ///     HADD V0_HI, V1_HI
5761 ///
5762 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5763 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5764 /// the upper 128-bits of the result.
5765 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5766                                      SDLoc DL, SelectionDAG &DAG,
5767                                      unsigned X86Opcode, bool Mode,
5768                                      bool isUndefLO, bool isUndefHI) {
5769   EVT VT = V0.getValueType();
5770   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5771          "Invalid nodes in input!");
5772
5773   unsigned NumElts = VT.getVectorNumElements();
5774   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5775   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5776   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5777   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5778   EVT NewVT = V0_LO.getValueType();
5779
5780   SDValue LO = DAG.getUNDEF(NewVT);
5781   SDValue HI = DAG.getUNDEF(NewVT);
5782
5783   if (Mode) {
5784     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5785     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5786       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5787     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5788       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5789   } else {
5790     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5791     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5792                        V1_LO->getOpcode() != ISD::UNDEF))
5793       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5794
5795     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5796                        V1_HI->getOpcode() != ISD::UNDEF))
5797       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5798   }
5799
5800   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5801 }
5802
5803 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5804 /// node.
5805 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5806                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5807   EVT VT = BV->getValueType(0);
5808   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5809       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5810     return SDValue();
5811
5812   SDLoc DL(BV);
5813   unsigned NumElts = VT.getVectorNumElements();
5814   SDValue InVec0 = DAG.getUNDEF(VT);
5815   SDValue InVec1 = DAG.getUNDEF(VT);
5816
5817   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5818           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5819
5820   // Odd-numbered elements in the input build vector are obtained from
5821   // adding two integer/float elements.
5822   // Even-numbered elements in the input build vector are obtained from
5823   // subtracting two integer/float elements.
5824   unsigned ExpectedOpcode = ISD::FSUB;
5825   unsigned NextExpectedOpcode = ISD::FADD;
5826   bool AddFound = false;
5827   bool SubFound = false;
5828
5829   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5830     SDValue Op = BV->getOperand(i);
5831
5832     // Skip 'undef' values.
5833     unsigned Opcode = Op.getOpcode();
5834     if (Opcode == ISD::UNDEF) {
5835       std::swap(ExpectedOpcode, NextExpectedOpcode);
5836       continue;
5837     }
5838
5839     // Early exit if we found an unexpected opcode.
5840     if (Opcode != ExpectedOpcode)
5841       return SDValue();
5842
5843     SDValue Op0 = Op.getOperand(0);
5844     SDValue Op1 = Op.getOperand(1);
5845
5846     // Try to match the following pattern:
5847     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5848     // Early exit if we cannot match that sequence.
5849     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5850         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5851         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5852         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5853         Op0.getOperand(1) != Op1.getOperand(1))
5854       return SDValue();
5855
5856     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5857     if (I0 != i)
5858       return SDValue();
5859
5860     // We found a valid add/sub node. Update the information accordingly.
5861     if (i & 1)
5862       AddFound = true;
5863     else
5864       SubFound = true;
5865
5866     // Update InVec0 and InVec1.
5867     if (InVec0.getOpcode() == ISD::UNDEF) {
5868       InVec0 = Op0.getOperand(0);
5869       if (InVec0.getValueType() != VT)
5870         return SDValue();
5871     }
5872     if (InVec1.getOpcode() == ISD::UNDEF) {
5873       InVec1 = Op1.getOperand(0);
5874       if (InVec1.getValueType() != VT)
5875         return SDValue();
5876     }
5877
5878     // Make sure that operands in input to each add/sub node always
5879     // come from a same pair of vectors.
5880     if (InVec0 != Op0.getOperand(0)) {
5881       if (ExpectedOpcode == ISD::FSUB)
5882         return SDValue();
5883
5884       // FADD is commutable. Try to commute the operands
5885       // and then test again.
5886       std::swap(Op0, Op1);
5887       if (InVec0 != Op0.getOperand(0))
5888         return SDValue();
5889     }
5890
5891     if (InVec1 != Op1.getOperand(0))
5892       return SDValue();
5893
5894     // Update the pair of expected opcodes.
5895     std::swap(ExpectedOpcode, NextExpectedOpcode);
5896   }
5897
5898   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5899   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5900       InVec1.getOpcode() != ISD::UNDEF)
5901     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5902
5903   return SDValue();
5904 }
5905
5906 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5907 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5908                                    const X86Subtarget *Subtarget,
5909                                    SelectionDAG &DAG) {
5910   EVT VT = BV->getValueType(0);
5911   unsigned NumElts = VT.getVectorNumElements();
5912   unsigned NumUndefsLO = 0;
5913   unsigned NumUndefsHI = 0;
5914   unsigned Half = NumElts/2;
5915
5916   // Count the number of UNDEF operands in the build_vector in input.
5917   for (unsigned i = 0, e = Half; i != e; ++i)
5918     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5919       NumUndefsLO++;
5920
5921   for (unsigned i = Half, e = NumElts; i != e; ++i)
5922     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5923       NumUndefsHI++;
5924
5925   // Early exit if this is either a build_vector of all UNDEFs or all the
5926   // operands but one are UNDEF.
5927   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5928     return SDValue();
5929
5930   SDLoc DL(BV);
5931   SDValue InVec0, InVec1;
5932   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5933     // Try to match an SSE3 float HADD/HSUB.
5934     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5935       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5936
5937     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5938       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5939   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5940     // Try to match an SSSE3 integer HADD/HSUB.
5941     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5942       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5943
5944     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5945       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5946   }
5947
5948   if (!Subtarget->hasAVX())
5949     return SDValue();
5950
5951   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5952     // Try to match an AVX horizontal add/sub of packed single/double
5953     // precision floating point values from 256-bit vectors.
5954     SDValue InVec2, InVec3;
5955     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5956         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5957         ((InVec0.getOpcode() == ISD::UNDEF ||
5958           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5959         ((InVec1.getOpcode() == ISD::UNDEF ||
5960           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5961       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5962
5963     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5964         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5965         ((InVec0.getOpcode() == ISD::UNDEF ||
5966           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5967         ((InVec1.getOpcode() == ISD::UNDEF ||
5968           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5969       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5970   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5971     // Try to match an AVX2 horizontal add/sub of signed integers.
5972     SDValue InVec2, InVec3;
5973     unsigned X86Opcode;
5974     bool CanFold = true;
5975
5976     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5977         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5978         ((InVec0.getOpcode() == ISD::UNDEF ||
5979           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5980         ((InVec1.getOpcode() == ISD::UNDEF ||
5981           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5982       X86Opcode = X86ISD::HADD;
5983     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5984         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5985         ((InVec0.getOpcode() == ISD::UNDEF ||
5986           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5987         ((InVec1.getOpcode() == ISD::UNDEF ||
5988           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5989       X86Opcode = X86ISD::HSUB;
5990     else
5991       CanFold = false;
5992
5993     if (CanFold) {
5994       // Fold this build_vector into a single horizontal add/sub.
5995       // Do this only if the target has AVX2.
5996       if (Subtarget->hasAVX2())
5997         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5998
5999       // Do not try to expand this build_vector into a pair of horizontal
6000       // add/sub if we can emit a pair of scalar add/sub.
6001       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6002         return SDValue();
6003
6004       // Convert this build_vector into a pair of horizontal binop followed by
6005       // a concat vector.
6006       bool isUndefLO = NumUndefsLO == Half;
6007       bool isUndefHI = NumUndefsHI == Half;
6008       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6009                                    isUndefLO, isUndefHI);
6010     }
6011   }
6012
6013   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6014        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6015     unsigned X86Opcode;
6016     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6017       X86Opcode = X86ISD::HADD;
6018     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6019       X86Opcode = X86ISD::HSUB;
6020     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6021       X86Opcode = X86ISD::FHADD;
6022     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6023       X86Opcode = X86ISD::FHSUB;
6024     else
6025       return SDValue();
6026
6027     // Don't try to expand this build_vector into a pair of horizontal add/sub
6028     // if we can simply emit a pair of scalar add/sub.
6029     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6030       return SDValue();
6031
6032     // Convert this build_vector into two horizontal add/sub followed by
6033     // a concat vector.
6034     bool isUndefLO = NumUndefsLO == Half;
6035     bool isUndefHI = NumUndefsHI == Half;
6036     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6037                                  isUndefLO, isUndefHI);
6038   }
6039
6040   return SDValue();
6041 }
6042
6043 SDValue
6044 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6045   SDLoc dl(Op);
6046
6047   MVT VT = Op.getSimpleValueType();
6048   MVT ExtVT = VT.getVectorElementType();
6049   unsigned NumElems = Op.getNumOperands();
6050
6051   // Generate vectors for predicate vectors.
6052   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6053     return LowerBUILD_VECTORvXi1(Op, DAG);
6054
6055   // Vectors containing all zeros can be matched by pxor and xorps later
6056   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6057     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6058     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6059     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6060       return Op;
6061
6062     return getZeroVector(VT, Subtarget, DAG, dl);
6063   }
6064
6065   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6066   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6067   // vpcmpeqd on 256-bit vectors.
6068   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6069     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6070       return Op;
6071
6072     if (!VT.is512BitVector())
6073       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6074   }
6075
6076   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6077   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6078     return AddSub;
6079   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6080     return HorizontalOp;
6081   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6082     return Broadcast;
6083
6084   unsigned EVTBits = ExtVT.getSizeInBits();
6085
6086   unsigned NumZero  = 0;
6087   unsigned NumNonZero = 0;
6088   unsigned NonZeros = 0;
6089   bool IsAllConstants = true;
6090   SmallSet<SDValue, 8> Values;
6091   for (unsigned i = 0; i < NumElems; ++i) {
6092     SDValue Elt = Op.getOperand(i);
6093     if (Elt.getOpcode() == ISD::UNDEF)
6094       continue;
6095     Values.insert(Elt);
6096     if (Elt.getOpcode() != ISD::Constant &&
6097         Elt.getOpcode() != ISD::ConstantFP)
6098       IsAllConstants = false;
6099     if (X86::isZeroNode(Elt))
6100       NumZero++;
6101     else {
6102       NonZeros |= (1 << i);
6103       NumNonZero++;
6104     }
6105   }
6106
6107   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6108   if (NumNonZero == 0)
6109     return DAG.getUNDEF(VT);
6110
6111   // Special case for single non-zero, non-undef, element.
6112   if (NumNonZero == 1) {
6113     unsigned Idx = countTrailingZeros(NonZeros);
6114     SDValue Item = Op.getOperand(Idx);
6115
6116     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6117     // the value are obviously zero, truncate the value to i32 and do the
6118     // insertion that way.  Only do this if the value is non-constant or if the
6119     // value is a constant being inserted into element 0.  It is cheaper to do
6120     // a constant pool load than it is to do a movd + shuffle.
6121     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6122         (!IsAllConstants || Idx == 0)) {
6123       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6124         // Handle SSE only.
6125         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6126         EVT VecVT = MVT::v4i32;
6127
6128         // Truncate the value (which may itself be a constant) to i32, and
6129         // convert it to a vector with movd (S2V+shuffle to zero extend).
6130         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6131         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6132         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6133                                       Item, Idx * 2, true, Subtarget, DAG));
6134       }
6135     }
6136
6137     // If we have a constant or non-constant insertion into the low element of
6138     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6139     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6140     // depending on what the source datatype is.
6141     if (Idx == 0) {
6142       if (NumZero == 0)
6143         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6144
6145       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6146           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6147         if (VT.is512BitVector()) {
6148           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6149           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6150                              Item, DAG.getIntPtrConstant(0, dl));
6151         }
6152         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6153                "Expected an SSE value type!");
6154         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6155         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6156         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6157       }
6158
6159       // We can't directly insert an i8 or i16 into a vector, so zero extend
6160       // it to i32 first.
6161       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6162         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6163         if (VT.is256BitVector()) {
6164           if (Subtarget->hasAVX()) {
6165             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6166             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6167           } else {
6168             // Without AVX, we need to extend to a 128-bit vector and then
6169             // insert into the 256-bit vector.
6170             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6171             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6172             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6173           }
6174         } else {
6175           assert(VT.is128BitVector() && "Expected an SSE value type!");
6176           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6177           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6178         }
6179         return DAG.getBitcast(VT, Item);
6180       }
6181     }
6182
6183     // Is it a vector logical left shift?
6184     if (NumElems == 2 && Idx == 1 &&
6185         X86::isZeroNode(Op.getOperand(0)) &&
6186         !X86::isZeroNode(Op.getOperand(1))) {
6187       unsigned NumBits = VT.getSizeInBits();
6188       return getVShift(true, VT,
6189                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6190                                    VT, Op.getOperand(1)),
6191                        NumBits/2, DAG, *this, dl);
6192     }
6193
6194     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6195       return SDValue();
6196
6197     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6198     // is a non-constant being inserted into an element other than the low one,
6199     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6200     // movd/movss) to move this into the low element, then shuffle it into
6201     // place.
6202     if (EVTBits == 32) {
6203       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6204       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6205     }
6206   }
6207
6208   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6209   if (Values.size() == 1) {
6210     if (EVTBits == 32) {
6211       // Instead of a shuffle like this:
6212       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6213       // Check if it's possible to issue this instead.
6214       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6215       unsigned Idx = countTrailingZeros(NonZeros);
6216       SDValue Item = Op.getOperand(Idx);
6217       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6218         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6219     }
6220     return SDValue();
6221   }
6222
6223   // A vector full of immediates; various special cases are already
6224   // handled, so this is best done with a single constant-pool load.
6225   if (IsAllConstants)
6226     return SDValue();
6227
6228   // For AVX-length vectors, see if we can use a vector load to get all of the
6229   // elements, otherwise build the individual 128-bit pieces and use
6230   // shuffles to put them in place.
6231   if (VT.is256BitVector() || VT.is512BitVector()) {
6232     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6233
6234     // Check for a build vector of consecutive loads.
6235     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6236       return LD;
6237
6238     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6239
6240     // Build both the lower and upper subvector.
6241     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6242                                 makeArrayRef(&V[0], NumElems/2));
6243     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6244                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6245
6246     // Recreate the wider vector with the lower and upper part.
6247     if (VT.is256BitVector())
6248       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6249     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6250   }
6251
6252   // Let legalizer expand 2-wide build_vectors.
6253   if (EVTBits == 64) {
6254     if (NumNonZero == 1) {
6255       // One half is zero or undef.
6256       unsigned Idx = countTrailingZeros(NonZeros);
6257       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6258                                  Op.getOperand(Idx));
6259       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6260     }
6261     return SDValue();
6262   }
6263
6264   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6265   if (EVTBits == 8 && NumElems == 16)
6266     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6267                                         Subtarget, *this))
6268       return V;
6269
6270   if (EVTBits == 16 && NumElems == 8)
6271     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6272                                       Subtarget, *this))
6273       return V;
6274
6275   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6276   if (EVTBits == 32 && NumElems == 4)
6277     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6278       return V;
6279
6280   // If element VT is == 32 bits, turn it into a number of shuffles.
6281   SmallVector<SDValue, 8> V(NumElems);
6282   if (NumElems == 4 && NumZero > 0) {
6283     for (unsigned i = 0; i < 4; ++i) {
6284       bool isZero = !(NonZeros & (1 << i));
6285       if (isZero)
6286         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6287       else
6288         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6289     }
6290
6291     for (unsigned i = 0; i < 2; ++i) {
6292       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6293         default: break;
6294         case 0:
6295           V[i] = V[i*2];  // Must be a zero vector.
6296           break;
6297         case 1:
6298           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6299           break;
6300         case 2:
6301           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6302           break;
6303         case 3:
6304           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6305           break;
6306       }
6307     }
6308
6309     bool Reverse1 = (NonZeros & 0x3) == 2;
6310     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6311     int MaskVec[] = {
6312       Reverse1 ? 1 : 0,
6313       Reverse1 ? 0 : 1,
6314       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6315       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6316     };
6317     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6318   }
6319
6320   if (Values.size() > 1 && VT.is128BitVector()) {
6321     // Check for a build vector of consecutive loads.
6322     for (unsigned i = 0; i < NumElems; ++i)
6323       V[i] = Op.getOperand(i);
6324
6325     // Check for elements which are consecutive loads.
6326     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6327       return LD;
6328
6329     // Check for a build vector from mostly shuffle plus few inserting.
6330     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6331       return Sh;
6332
6333     // For SSE 4.1, use insertps to put the high elements into the low element.
6334     if (Subtarget->hasSSE41()) {
6335       SDValue Result;
6336       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6337         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6338       else
6339         Result = DAG.getUNDEF(VT);
6340
6341       for (unsigned i = 1; i < NumElems; ++i) {
6342         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6343         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6344                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6345       }
6346       return Result;
6347     }
6348
6349     // Otherwise, expand into a number of unpckl*, start by extending each of
6350     // our (non-undef) elements to the full vector width with the element in the
6351     // bottom slot of the vector (which generates no code for SSE).
6352     for (unsigned i = 0; i < NumElems; ++i) {
6353       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6354         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6355       else
6356         V[i] = DAG.getUNDEF(VT);
6357     }
6358
6359     // Next, we iteratively mix elements, e.g. for v4f32:
6360     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6361     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6362     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6363     unsigned EltStride = NumElems >> 1;
6364     while (EltStride != 0) {
6365       for (unsigned i = 0; i < EltStride; ++i) {
6366         // If V[i+EltStride] is undef and this is the first round of mixing,
6367         // then it is safe to just drop this shuffle: V[i] is already in the
6368         // right place, the one element (since it's the first round) being
6369         // inserted as undef can be dropped.  This isn't safe for successive
6370         // rounds because they will permute elements within both vectors.
6371         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6372             EltStride == NumElems/2)
6373           continue;
6374
6375         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6376       }
6377       EltStride >>= 1;
6378     }
6379     return V[0];
6380   }
6381   return SDValue();
6382 }
6383
6384 // 256-bit AVX can use the vinsertf128 instruction
6385 // to create 256-bit vectors from two other 128-bit ones.
6386 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6387   SDLoc dl(Op);
6388   MVT ResVT = Op.getSimpleValueType();
6389
6390   assert((ResVT.is256BitVector() ||
6391           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6392
6393   SDValue V1 = Op.getOperand(0);
6394   SDValue V2 = Op.getOperand(1);
6395   unsigned NumElems = ResVT.getVectorNumElements();
6396   if (ResVT.is256BitVector())
6397     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6398
6399   if (Op.getNumOperands() == 4) {
6400     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6401                                 ResVT.getVectorNumElements()/2);
6402     SDValue V3 = Op.getOperand(2);
6403     SDValue V4 = Op.getOperand(3);
6404     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6405       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6406   }
6407   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6408 }
6409
6410 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6411                                        const X86Subtarget *Subtarget,
6412                                        SelectionDAG & DAG) {
6413   SDLoc dl(Op);
6414   MVT ResVT = Op.getSimpleValueType();
6415   unsigned NumOfOperands = Op.getNumOperands();
6416
6417   assert(isPowerOf2_32(NumOfOperands) &&
6418          "Unexpected number of operands in CONCAT_VECTORS");
6419
6420   if (NumOfOperands > 2) {
6421     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6422                                   ResVT.getVectorNumElements()/2);
6423     SmallVector<SDValue, 2> Ops;
6424     for (unsigned i = 0; i < NumOfOperands/2; i++)
6425       Ops.push_back(Op.getOperand(i));
6426     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6427     Ops.clear();
6428     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6429       Ops.push_back(Op.getOperand(i));
6430     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6431     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6432   }
6433
6434   SDValue V1 = Op.getOperand(0);
6435   SDValue V2 = Op.getOperand(1);
6436   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6437   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6438
6439   if (IsZeroV1 && IsZeroV2)
6440     return getZeroVector(ResVT, Subtarget, DAG, dl);
6441
6442   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6443   SDValue Undef = DAG.getUNDEF(ResVT);
6444   unsigned NumElems = ResVT.getVectorNumElements();
6445   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6446
6447   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6448   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6449   if (IsZeroV1)
6450     return V2;
6451
6452   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6453   // Zero the upper bits of V1
6454   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6455   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6456   if (IsZeroV2)
6457     return V1;
6458   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6459 }
6460
6461 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6462                                    const X86Subtarget *Subtarget,
6463                                    SelectionDAG &DAG) {
6464   MVT VT = Op.getSimpleValueType();
6465   if (VT.getVectorElementType() == MVT::i1)
6466     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6467
6468   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6469          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6470           Op.getNumOperands() == 4)));
6471
6472   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6473   // from two other 128-bit ones.
6474
6475   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6476   return LowerAVXCONCAT_VECTORS(Op, DAG);
6477 }
6478
6479
6480 //===----------------------------------------------------------------------===//
6481 // Vector shuffle lowering
6482 //
6483 // This is an experimental code path for lowering vector shuffles on x86. It is
6484 // designed to handle arbitrary vector shuffles and blends, gracefully
6485 // degrading performance as necessary. It works hard to recognize idiomatic
6486 // shuffles and lower them to optimal instruction patterns without leaving
6487 // a framework that allows reasonably efficient handling of all vector shuffle
6488 // patterns.
6489 //===----------------------------------------------------------------------===//
6490
6491 /// \brief Tiny helper function to identify a no-op mask.
6492 ///
6493 /// This is a somewhat boring predicate function. It checks whether the mask
6494 /// array input, which is assumed to be a single-input shuffle mask of the kind
6495 /// used by the X86 shuffle instructions (not a fully general
6496 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6497 /// in-place shuffle are 'no-op's.
6498 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6499   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6500     if (Mask[i] != -1 && Mask[i] != i)
6501       return false;
6502   return true;
6503 }
6504
6505 /// \brief Helper function to classify a mask as a single-input mask.
6506 ///
6507 /// This isn't a generic single-input test because in the vector shuffle
6508 /// lowering we canonicalize single inputs to be the first input operand. This
6509 /// means we can more quickly test for a single input by only checking whether
6510 /// an input from the second operand exists. We also assume that the size of
6511 /// mask corresponds to the size of the input vectors which isn't true in the
6512 /// fully general case.
6513 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6514   for (int M : Mask)
6515     if (M >= (int)Mask.size())
6516       return false;
6517   return true;
6518 }
6519
6520 /// \brief Test whether there are elements crossing 128-bit lanes in this
6521 /// shuffle mask.
6522 ///
6523 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6524 /// and we routinely test for these.
6525 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6526   int LaneSize = 128 / VT.getScalarSizeInBits();
6527   int Size = Mask.size();
6528   for (int i = 0; i < Size; ++i)
6529     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6530       return true;
6531   return false;
6532 }
6533
6534 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6535 ///
6536 /// This checks a shuffle mask to see if it is performing the same
6537 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6538 /// that it is also not lane-crossing. It may however involve a blend from the
6539 /// same lane of a second vector.
6540 ///
6541 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6542 /// non-trivial to compute in the face of undef lanes. The representation is
6543 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6544 /// entries from both V1 and V2 inputs to the wider mask.
6545 static bool
6546 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6547                                 SmallVectorImpl<int> &RepeatedMask) {
6548   int LaneSize = 128 / VT.getScalarSizeInBits();
6549   RepeatedMask.resize(LaneSize, -1);
6550   int Size = Mask.size();
6551   for (int i = 0; i < Size; ++i) {
6552     if (Mask[i] < 0)
6553       continue;
6554     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6555       // This entry crosses lanes, so there is no way to model this shuffle.
6556       return false;
6557
6558     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6559     if (RepeatedMask[i % LaneSize] == -1)
6560       // This is the first non-undef entry in this slot of a 128-bit lane.
6561       RepeatedMask[i % LaneSize] =
6562           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6563     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6564       // Found a mismatch with the repeated mask.
6565       return false;
6566   }
6567   return true;
6568 }
6569
6570 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6571 /// arguments.
6572 ///
6573 /// This is a fast way to test a shuffle mask against a fixed pattern:
6574 ///
6575 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6576 ///
6577 /// It returns true if the mask is exactly as wide as the argument list, and
6578 /// each element of the mask is either -1 (signifying undef) or the value given
6579 /// in the argument.
6580 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6581                                 ArrayRef<int> ExpectedMask) {
6582   if (Mask.size() != ExpectedMask.size())
6583     return false;
6584
6585   int Size = Mask.size();
6586
6587   // If the values are build vectors, we can look through them to find
6588   // equivalent inputs that make the shuffles equivalent.
6589   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6590   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6591
6592   for (int i = 0; i < Size; ++i)
6593     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6594       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6595       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6596       if (!MaskBV || !ExpectedBV ||
6597           MaskBV->getOperand(Mask[i] % Size) !=
6598               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6599         return false;
6600     }
6601
6602   return true;
6603 }
6604
6605 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6606 ///
6607 /// This helper function produces an 8-bit shuffle immediate corresponding to
6608 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6609 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6610 /// example.
6611 ///
6612 /// NB: We rely heavily on "undef" masks preserving the input lane.
6613 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6614                                           SelectionDAG &DAG) {
6615   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6616   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6617   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6618   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6619   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6620
6621   unsigned Imm = 0;
6622   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6623   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6624   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6625   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6626   return DAG.getConstant(Imm, DL, MVT::i8);
6627 }
6628
6629 /// \brief Compute whether each element of a shuffle is zeroable.
6630 ///
6631 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6632 /// Either it is an undef element in the shuffle mask, the element of the input
6633 /// referenced is undef, or the element of the input referenced is known to be
6634 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6635 /// as many lanes with this technique as possible to simplify the remaining
6636 /// shuffle.
6637 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6638                                                      SDValue V1, SDValue V2) {
6639   SmallBitVector Zeroable(Mask.size(), false);
6640
6641   while (V1.getOpcode() == ISD::BITCAST)
6642     V1 = V1->getOperand(0);
6643   while (V2.getOpcode() == ISD::BITCAST)
6644     V2 = V2->getOperand(0);
6645
6646   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6647   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6648
6649   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6650     int M = Mask[i];
6651     // Handle the easy cases.
6652     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6653       Zeroable[i] = true;
6654       continue;
6655     }
6656
6657     // If this is an index into a build_vector node (which has the same number
6658     // of elements), dig out the input value and use it.
6659     SDValue V = M < Size ? V1 : V2;
6660     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6661       continue;
6662
6663     SDValue Input = V.getOperand(M % Size);
6664     // The UNDEF opcode check really should be dead code here, but not quite
6665     // worth asserting on (it isn't invalid, just unexpected).
6666     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6667       Zeroable[i] = true;
6668   }
6669
6670   return Zeroable;
6671 }
6672
6673 // X86 has dedicated unpack instructions that can handle specific blend
6674 // operations: UNPCKH and UNPCKL.
6675 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6676                                            SDValue V1, SDValue V2,
6677                                            SelectionDAG &DAG) {
6678   int NumElts = VT.getVectorNumElements();
6679   bool Unpckl = true;
6680   bool Unpckh = true;
6681   bool UnpcklSwapped = true;
6682   bool UnpckhSwapped = true;
6683   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6684
6685   for (int i = 0; i < NumElts; ++i) {
6686     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6687
6688     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6689     int HiPos = LoPos + NumEltsInLane / 2;
6690     int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6691     int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6692
6693     if (Mask[i] == -1)
6694       continue;
6695     if (Mask[i] != LoPos)
6696       Unpckl = false;
6697     if (Mask[i] != HiPos)
6698       Unpckh = false;
6699     if (Mask[i] != LoPosSwapped)
6700       UnpcklSwapped = false;
6701     if (Mask[i] != HiPosSwapped)
6702       UnpckhSwapped = false;
6703     if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6704       return SDValue();
6705   }
6706   if (Unpckl)
6707     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6708   if (Unpckh)
6709     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6710   if (UnpcklSwapped)
6711     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6712   if (UnpckhSwapped)
6713     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6714
6715   llvm_unreachable("Unexpected result of UNPCK mask analysis");
6716   return SDValue();
6717 }
6718
6719 /// \brief Try to emit a bitmask instruction for a shuffle.
6720 ///
6721 /// This handles cases where we can model a blend exactly as a bitmask due to
6722 /// one of the inputs being zeroable.
6723 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6724                                            SDValue V2, ArrayRef<int> Mask,
6725                                            SelectionDAG &DAG) {
6726   MVT EltVT = VT.getScalarType();
6727   int NumEltBits = EltVT.getSizeInBits();
6728   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6729   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6730   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6731                                     IntEltVT);
6732   if (EltVT.isFloatingPoint()) {
6733     Zero = DAG.getBitcast(EltVT, Zero);
6734     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6735   }
6736   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6737   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6738   SDValue V;
6739   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6740     if (Zeroable[i])
6741       continue;
6742     if (Mask[i] % Size != i)
6743       return SDValue(); // Not a blend.
6744     if (!V)
6745       V = Mask[i] < Size ? V1 : V2;
6746     else if (V != (Mask[i] < Size ? V1 : V2))
6747       return SDValue(); // Can only let one input through the mask.
6748
6749     VMaskOps[i] = AllOnes;
6750   }
6751   if (!V)
6752     return SDValue(); // No non-zeroable elements!
6753
6754   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6755   V = DAG.getNode(VT.isFloatingPoint()
6756                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6757                   DL, VT, V, VMask);
6758   return V;
6759 }
6760
6761 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6762 ///
6763 /// This is used as a fallback approach when first class blend instructions are
6764 /// unavailable. Currently it is only suitable for integer vectors, but could
6765 /// be generalized for floating point vectors if desirable.
6766 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6767                                             SDValue V2, ArrayRef<int> Mask,
6768                                             SelectionDAG &DAG) {
6769   assert(VT.isInteger() && "Only supports integer vector types!");
6770   MVT EltVT = VT.getScalarType();
6771   int NumEltBits = EltVT.getSizeInBits();
6772   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6773   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6774                                     EltVT);
6775   SmallVector<SDValue, 16> MaskOps;
6776   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6777     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6778       return SDValue(); // Shuffled input!
6779     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6780   }
6781
6782   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6783   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6784   // We have to cast V2 around.
6785   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6786   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6787                                       DAG.getBitcast(MaskVT, V1Mask),
6788                                       DAG.getBitcast(MaskVT, V2)));
6789   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6790 }
6791
6792 /// \brief Try to emit a blend instruction for a shuffle.
6793 ///
6794 /// This doesn't do any checks for the availability of instructions for blending
6795 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6796 /// be matched in the backend with the type given. What it does check for is
6797 /// that the shuffle mask is in fact a blend.
6798 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6799                                          SDValue V2, ArrayRef<int> Mask,
6800                                          const X86Subtarget *Subtarget,
6801                                          SelectionDAG &DAG) {
6802   unsigned BlendMask = 0;
6803   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6804     if (Mask[i] >= Size) {
6805       if (Mask[i] != i + Size)
6806         return SDValue(); // Shuffled V2 input!
6807       BlendMask |= 1u << i;
6808       continue;
6809     }
6810     if (Mask[i] >= 0 && Mask[i] != i)
6811       return SDValue(); // Shuffled V1 input!
6812   }
6813   switch (VT.SimpleTy) {
6814   case MVT::v2f64:
6815   case MVT::v4f32:
6816   case MVT::v4f64:
6817   case MVT::v8f32:
6818     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6819                        DAG.getConstant(BlendMask, DL, MVT::i8));
6820
6821   case MVT::v4i64:
6822   case MVT::v8i32:
6823     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6824     // FALLTHROUGH
6825   case MVT::v2i64:
6826   case MVT::v4i32:
6827     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6828     // that instruction.
6829     if (Subtarget->hasAVX2()) {
6830       // Scale the blend by the number of 32-bit dwords per element.
6831       int Scale =  VT.getScalarSizeInBits() / 32;
6832       BlendMask = 0;
6833       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6834         if (Mask[i] >= Size)
6835           for (int j = 0; j < Scale; ++j)
6836             BlendMask |= 1u << (i * Scale + j);
6837
6838       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6839       V1 = DAG.getBitcast(BlendVT, V1);
6840       V2 = DAG.getBitcast(BlendVT, V2);
6841       return DAG.getBitcast(
6842           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6843                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6844     }
6845     // FALLTHROUGH
6846   case MVT::v8i16: {
6847     // For integer shuffles we need to expand the mask and cast the inputs to
6848     // v8i16s prior to blending.
6849     int Scale = 8 / VT.getVectorNumElements();
6850     BlendMask = 0;
6851     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6852       if (Mask[i] >= Size)
6853         for (int j = 0; j < Scale; ++j)
6854           BlendMask |= 1u << (i * Scale + j);
6855
6856     V1 = DAG.getBitcast(MVT::v8i16, V1);
6857     V2 = DAG.getBitcast(MVT::v8i16, V2);
6858     return DAG.getBitcast(VT,
6859                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6860                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6861   }
6862
6863   case MVT::v16i16: {
6864     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6865     SmallVector<int, 8> RepeatedMask;
6866     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6867       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6868       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6869       BlendMask = 0;
6870       for (int i = 0; i < 8; ++i)
6871         if (RepeatedMask[i] >= 16)
6872           BlendMask |= 1u << i;
6873       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6874                          DAG.getConstant(BlendMask, DL, MVT::i8));
6875     }
6876   }
6877     // FALLTHROUGH
6878   case MVT::v16i8:
6879   case MVT::v32i8: {
6880     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6881            "256-bit byte-blends require AVX2 support!");
6882
6883     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6884     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6885       return Masked;
6886
6887     // Scale the blend by the number of bytes per element.
6888     int Scale = VT.getScalarSizeInBits() / 8;
6889
6890     // This form of blend is always done on bytes. Compute the byte vector
6891     // type.
6892     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6893
6894     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6895     // mix of LLVM's code generator and the x86 backend. We tell the code
6896     // generator that boolean values in the elements of an x86 vector register
6897     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6898     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6899     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6900     // of the element (the remaining are ignored) and 0 in that high bit would
6901     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6902     // the LLVM model for boolean values in vector elements gets the relevant
6903     // bit set, it is set backwards and over constrained relative to x86's
6904     // actual model.
6905     SmallVector<SDValue, 32> VSELECTMask;
6906     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6907       for (int j = 0; j < Scale; ++j)
6908         VSELECTMask.push_back(
6909             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6910                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6911                                           MVT::i8));
6912
6913     V1 = DAG.getBitcast(BlendVT, V1);
6914     V2 = DAG.getBitcast(BlendVT, V2);
6915     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6916                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6917                                                       BlendVT, VSELECTMask),
6918                                           V1, V2));
6919   }
6920
6921   default:
6922     llvm_unreachable("Not a supported integer vector type!");
6923   }
6924 }
6925
6926 /// \brief Try to lower as a blend of elements from two inputs followed by
6927 /// a single-input permutation.
6928 ///
6929 /// This matches the pattern where we can blend elements from two inputs and
6930 /// then reduce the shuffle to a single-input permutation.
6931 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6932                                                    SDValue V2,
6933                                                    ArrayRef<int> Mask,
6934                                                    SelectionDAG &DAG) {
6935   // We build up the blend mask while checking whether a blend is a viable way
6936   // to reduce the shuffle.
6937   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6938   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6939
6940   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6941     if (Mask[i] < 0)
6942       continue;
6943
6944     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6945
6946     if (BlendMask[Mask[i] % Size] == -1)
6947       BlendMask[Mask[i] % Size] = Mask[i];
6948     else if (BlendMask[Mask[i] % Size] != Mask[i])
6949       return SDValue(); // Can't blend in the needed input!
6950
6951     PermuteMask[i] = Mask[i] % Size;
6952   }
6953
6954   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6955   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6956 }
6957
6958 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6959 /// blends and permutes.
6960 ///
6961 /// This matches the extremely common pattern for handling combined
6962 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6963 /// operations. It will try to pick the best arrangement of shuffles and
6964 /// blends.
6965 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6966                                                           SDValue V1,
6967                                                           SDValue V2,
6968                                                           ArrayRef<int> Mask,
6969                                                           SelectionDAG &DAG) {
6970   // Shuffle the input elements into the desired positions in V1 and V2 and
6971   // blend them together.
6972   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6973   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6974   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6975   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6976     if (Mask[i] >= 0 && Mask[i] < Size) {
6977       V1Mask[i] = Mask[i];
6978       BlendMask[i] = i;
6979     } else if (Mask[i] >= Size) {
6980       V2Mask[i] = Mask[i] - Size;
6981       BlendMask[i] = i + Size;
6982     }
6983
6984   // Try to lower with the simpler initial blend strategy unless one of the
6985   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6986   // shuffle may be able to fold with a load or other benefit. However, when
6987   // we'll have to do 2x as many shuffles in order to achieve this, blending
6988   // first is a better strategy.
6989   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6990     if (SDValue BlendPerm =
6991             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6992       return BlendPerm;
6993
6994   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6995   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6996   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6997 }
6998
6999 /// \brief Try to lower a vector shuffle as a byte rotation.
7000 ///
7001 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7002 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7003 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7004 /// try to generically lower a vector shuffle through such an pattern. It
7005 /// does not check for the profitability of lowering either as PALIGNR or
7006 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7007 /// This matches shuffle vectors that look like:
7008 ///
7009 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7010 ///
7011 /// Essentially it concatenates V1 and V2, shifts right by some number of
7012 /// elements, and takes the low elements as the result. Note that while this is
7013 /// specified as a *right shift* because x86 is little-endian, it is a *left
7014 /// rotate* of the vector lanes.
7015 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7016                                               SDValue V2,
7017                                               ArrayRef<int> Mask,
7018                                               const X86Subtarget *Subtarget,
7019                                               SelectionDAG &DAG) {
7020   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7021
7022   int NumElts = Mask.size();
7023   int NumLanes = VT.getSizeInBits() / 128;
7024   int NumLaneElts = NumElts / NumLanes;
7025
7026   // We need to detect various ways of spelling a rotation:
7027   //   [11, 12, 13, 14, 15,  0,  1,  2]
7028   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7029   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7030   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7031   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7032   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7033   int Rotation = 0;
7034   SDValue Lo, Hi;
7035   for (int l = 0; l < NumElts; l += NumLaneElts) {
7036     for (int i = 0; i < NumLaneElts; ++i) {
7037       if (Mask[l + i] == -1)
7038         continue;
7039       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7040
7041       // Get the mod-Size index and lane correct it.
7042       int LaneIdx = (Mask[l + i] % NumElts) - l;
7043       // Make sure it was in this lane.
7044       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7045         return SDValue();
7046
7047       // Determine where a rotated vector would have started.
7048       int StartIdx = i - LaneIdx;
7049       if (StartIdx == 0)
7050         // The identity rotation isn't interesting, stop.
7051         return SDValue();
7052
7053       // If we found the tail of a vector the rotation must be the missing
7054       // front. If we found the head of a vector, it must be how much of the
7055       // head.
7056       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7057
7058       if (Rotation == 0)
7059         Rotation = CandidateRotation;
7060       else if (Rotation != CandidateRotation)
7061         // The rotations don't match, so we can't match this mask.
7062         return SDValue();
7063
7064       // Compute which value this mask is pointing at.
7065       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7066
7067       // Compute which of the two target values this index should be assigned
7068       // to. This reflects whether the high elements are remaining or the low
7069       // elements are remaining.
7070       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7071
7072       // Either set up this value if we've not encountered it before, or check
7073       // that it remains consistent.
7074       if (!TargetV)
7075         TargetV = MaskV;
7076       else if (TargetV != MaskV)
7077         // This may be a rotation, but it pulls from the inputs in some
7078         // unsupported interleaving.
7079         return SDValue();
7080     }
7081   }
7082
7083   // Check that we successfully analyzed the mask, and normalize the results.
7084   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7085   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7086   if (!Lo)
7087     Lo = Hi;
7088   else if (!Hi)
7089     Hi = Lo;
7090
7091   // The actual rotate instruction rotates bytes, so we need to scale the
7092   // rotation based on how many bytes are in the vector lane.
7093   int Scale = 16 / NumLaneElts;
7094
7095   // SSSE3 targets can use the palignr instruction.
7096   if (Subtarget->hasSSSE3()) {
7097     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7098     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7099     Lo = DAG.getBitcast(AlignVT, Lo);
7100     Hi = DAG.getBitcast(AlignVT, Hi);
7101
7102     return DAG.getBitcast(
7103         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7104                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7105   }
7106
7107   assert(VT.getSizeInBits() == 128 &&
7108          "Rotate-based lowering only supports 128-bit lowering!");
7109   assert(Mask.size() <= 16 &&
7110          "Can shuffle at most 16 bytes in a 128-bit vector!");
7111
7112   // Default SSE2 implementation
7113   int LoByteShift = 16 - Rotation * Scale;
7114   int HiByteShift = Rotation * Scale;
7115
7116   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7117   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7118   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7119
7120   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7121                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7122   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7123                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7124   return DAG.getBitcast(VT,
7125                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7126 }
7127
7128 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7129 ///
7130 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7131 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7132 /// matches elements from one of the input vectors shuffled to the left or
7133 /// right with zeroable elements 'shifted in'. It handles both the strictly
7134 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7135 /// quad word lane.
7136 ///
7137 /// PSHL : (little-endian) left bit shift.
7138 /// [ zz, 0, zz,  2 ]
7139 /// [ -1, 4, zz, -1 ]
7140 /// PSRL : (little-endian) right bit shift.
7141 /// [  1, zz,  3, zz]
7142 /// [ -1, -1,  7, zz]
7143 /// PSLLDQ : (little-endian) left byte shift
7144 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7145 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7146 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7147 /// PSRLDQ : (little-endian) right byte shift
7148 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7149 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7150 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7151 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7152                                          SDValue V2, ArrayRef<int> Mask,
7153                                          SelectionDAG &DAG) {
7154   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7155
7156   int Size = Mask.size();
7157   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7158
7159   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7160     for (int i = 0; i < Size; i += Scale)
7161       for (int j = 0; j < Shift; ++j)
7162         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7163           return false;
7164
7165     return true;
7166   };
7167
7168   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7169     for (int i = 0; i != Size; i += Scale) {
7170       unsigned Pos = Left ? i + Shift : i;
7171       unsigned Low = Left ? i : i + Shift;
7172       unsigned Len = Scale - Shift;
7173       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7174                                       Low + (V == V1 ? 0 : Size)))
7175         return SDValue();
7176     }
7177
7178     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7179     bool ByteShift = ShiftEltBits > 64;
7180     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7181                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7182     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7183
7184     // Normalize the scale for byte shifts to still produce an i64 element
7185     // type.
7186     Scale = ByteShift ? Scale / 2 : Scale;
7187
7188     // We need to round trip through the appropriate type for the shift.
7189     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7190     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7191     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7192            "Illegal integer vector type");
7193     V = DAG.getBitcast(ShiftVT, V);
7194
7195     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7196                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7197     return DAG.getBitcast(VT, V);
7198   };
7199
7200   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7201   // keep doubling the size of the integer elements up to that. We can
7202   // then shift the elements of the integer vector by whole multiples of
7203   // their width within the elements of the larger integer vector. Test each
7204   // multiple to see if we can find a match with the moved element indices
7205   // and that the shifted in elements are all zeroable.
7206   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7207     for (int Shift = 1; Shift != Scale; ++Shift)
7208       for (bool Left : {true, false})
7209         if (CheckZeros(Shift, Scale, Left))
7210           for (SDValue V : {V1, V2})
7211             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7212               return Match;
7213
7214   // no match
7215   return SDValue();
7216 }
7217
7218 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7219 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7220                                            SDValue V2, ArrayRef<int> Mask,
7221                                            SelectionDAG &DAG) {
7222   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7223   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7224
7225   int Size = Mask.size();
7226   int HalfSize = Size / 2;
7227   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7228
7229   // Upper half must be undefined.
7230   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7231     return SDValue();
7232
7233   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7234   // Remainder of lower half result is zero and upper half is all undef.
7235   auto LowerAsEXTRQ = [&]() {
7236     // Determine the extraction length from the part of the
7237     // lower half that isn't zeroable.
7238     int Len = HalfSize;
7239     for (; Len >= 0; --Len)
7240       if (!Zeroable[Len - 1])
7241         break;
7242     assert(Len > 0 && "Zeroable shuffle mask");
7243
7244     // Attempt to match first Len sequential elements from the lower half.
7245     SDValue Src;
7246     int Idx = -1;
7247     for (int i = 0; i != Len; ++i) {
7248       int M = Mask[i];
7249       if (M < 0)
7250         continue;
7251       SDValue &V = (M < Size ? V1 : V2);
7252       M = M % Size;
7253
7254       // All mask elements must be in the lower half.
7255       if (M > HalfSize)
7256         return SDValue();
7257
7258       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7259         Src = V;
7260         Idx = M - i;
7261         continue;
7262       }
7263       return SDValue();
7264     }
7265
7266     if (Idx < 0)
7267       return SDValue();
7268
7269     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7270     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7271     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7272     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7273                        DAG.getConstant(BitLen, DL, MVT::i8),
7274                        DAG.getConstant(BitIdx, DL, MVT::i8));
7275   };
7276
7277   if (SDValue ExtrQ = LowerAsEXTRQ())
7278     return ExtrQ;
7279
7280   // INSERTQ: Extract lowest Len elements from lower half of second source and
7281   // insert over first source, starting at Idx.
7282   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7283   auto LowerAsInsertQ = [&]() {
7284     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7285       SDValue Base;
7286
7287       // Attempt to match first source from mask before insertion point.
7288       if (isUndefInRange(Mask, 0, Idx)) {
7289         /* EMPTY */
7290       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7291         Base = V1;
7292       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7293         Base = V2;
7294       } else {
7295         continue;
7296       }
7297
7298       // Extend the extraction length looking to match both the insertion of
7299       // the second source and the remaining elements of the first.
7300       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7301         SDValue Insert;
7302         int Len = Hi - Idx;
7303
7304         // Match insertion.
7305         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7306           Insert = V1;
7307         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7308           Insert = V2;
7309         } else {
7310           continue;
7311         }
7312
7313         // Match the remaining elements of the lower half.
7314         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7315           /* EMPTY */
7316         } else if ((!Base || (Base == V1)) &&
7317                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7318           Base = V1;
7319         } else if ((!Base || (Base == V2)) &&
7320                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7321                                               Size + Hi)) {
7322           Base = V2;
7323         } else {
7324           continue;
7325         }
7326
7327         // We may not have a base (first source) - this can safely be undefined.
7328         if (!Base)
7329           Base = DAG.getUNDEF(VT);
7330
7331         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7332         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7333         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7334                            DAG.getConstant(BitLen, DL, MVT::i8),
7335                            DAG.getConstant(BitIdx, DL, MVT::i8));
7336       }
7337     }
7338
7339     return SDValue();
7340   };
7341
7342   if (SDValue InsertQ = LowerAsInsertQ())
7343     return InsertQ;
7344
7345   return SDValue();
7346 }
7347
7348 /// \brief Lower a vector shuffle as a zero or any extension.
7349 ///
7350 /// Given a specific number of elements, element bit width, and extension
7351 /// stride, produce either a zero or any extension based on the available
7352 /// features of the subtarget.
7353 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7354     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7355     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7356   assert(Scale > 1 && "Need a scale to extend.");
7357   int NumElements = VT.getVectorNumElements();
7358   int EltBits = VT.getScalarSizeInBits();
7359   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7360          "Only 8, 16, and 32 bit elements can be extended.");
7361   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7362
7363   // Found a valid zext mask! Try various lowering strategies based on the
7364   // input type and available ISA extensions.
7365   if (Subtarget->hasSSE41()) {
7366     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7367                                  NumElements / Scale);
7368     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7369   }
7370
7371   // For any extends we can cheat for larger element sizes and use shuffle
7372   // instructions that can fold with a load and/or copy.
7373   if (AnyExt && EltBits == 32) {
7374     int PSHUFDMask[4] = {0, -1, 1, -1};
7375     return DAG.getBitcast(
7376         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7377                         DAG.getBitcast(MVT::v4i32, InputV),
7378                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7379   }
7380   if (AnyExt && EltBits == 16 && Scale > 2) {
7381     int PSHUFDMask[4] = {0, -1, 0, -1};
7382     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7383                          DAG.getBitcast(MVT::v4i32, InputV),
7384                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7385     int PSHUFHWMask[4] = {1, -1, -1, -1};
7386     return DAG.getBitcast(
7387         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7388                         DAG.getBitcast(MVT::v8i16, InputV),
7389                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7390   }
7391
7392   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7393   // to 64-bits.
7394   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7395     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7396     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7397
7398     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7399                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7400                                          DAG.getConstant(EltBits, DL, MVT::i8),
7401                                          DAG.getConstant(0, DL, MVT::i8)));
7402     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7403       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7404
7405     SDValue Hi =
7406         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7407                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7408                                 DAG.getConstant(EltBits, DL, MVT::i8),
7409                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7410     return DAG.getNode(ISD::BITCAST, DL, VT,
7411                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7412   }
7413
7414   // If this would require more than 2 unpack instructions to expand, use
7415   // pshufb when available. We can only use more than 2 unpack instructions
7416   // when zero extending i8 elements which also makes it easier to use pshufb.
7417   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7418     assert(NumElements == 16 && "Unexpected byte vector width!");
7419     SDValue PSHUFBMask[16];
7420     for (int i = 0; i < 16; ++i)
7421       PSHUFBMask[i] =
7422           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7423     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7424     return DAG.getBitcast(VT,
7425                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7426                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7427                                                   MVT::v16i8, PSHUFBMask)));
7428   }
7429
7430   // Otherwise emit a sequence of unpacks.
7431   do {
7432     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7433     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7434                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7435     InputV = DAG.getBitcast(InputVT, InputV);
7436     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7437     Scale /= 2;
7438     EltBits *= 2;
7439     NumElements /= 2;
7440   } while (Scale > 1);
7441   return DAG.getBitcast(VT, InputV);
7442 }
7443
7444 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7445 ///
7446 /// This routine will try to do everything in its power to cleverly lower
7447 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7448 /// check for the profitability of this lowering,  it tries to aggressively
7449 /// match this pattern. It will use all of the micro-architectural details it
7450 /// can to emit an efficient lowering. It handles both blends with all-zero
7451 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7452 /// masking out later).
7453 ///
7454 /// The reason we have dedicated lowering for zext-style shuffles is that they
7455 /// are both incredibly common and often quite performance sensitive.
7456 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7457     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7458     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7459   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7460
7461   int Bits = VT.getSizeInBits();
7462   int NumElements = VT.getVectorNumElements();
7463   assert(VT.getScalarSizeInBits() <= 32 &&
7464          "Exceeds 32-bit integer zero extension limit");
7465   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7466
7467   // Define a helper function to check a particular ext-scale and lower to it if
7468   // valid.
7469   auto Lower = [&](int Scale) -> SDValue {
7470     SDValue InputV;
7471     bool AnyExt = true;
7472     for (int i = 0; i < NumElements; ++i) {
7473       if (Mask[i] == -1)
7474         continue; // Valid anywhere but doesn't tell us anything.
7475       if (i % Scale != 0) {
7476         // Each of the extended elements need to be zeroable.
7477         if (!Zeroable[i])
7478           return SDValue();
7479
7480         // We no longer are in the anyext case.
7481         AnyExt = false;
7482         continue;
7483       }
7484
7485       // Each of the base elements needs to be consecutive indices into the
7486       // same input vector.
7487       SDValue V = Mask[i] < NumElements ? V1 : V2;
7488       if (!InputV)
7489         InputV = V;
7490       else if (InputV != V)
7491         return SDValue(); // Flip-flopping inputs.
7492
7493       if (Mask[i] % NumElements != i / Scale)
7494         return SDValue(); // Non-consecutive strided elements.
7495     }
7496
7497     // If we fail to find an input, we have a zero-shuffle which should always
7498     // have already been handled.
7499     // FIXME: Maybe handle this here in case during blending we end up with one?
7500     if (!InputV)
7501       return SDValue();
7502
7503     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7504         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7505   };
7506
7507   // The widest scale possible for extending is to a 64-bit integer.
7508   assert(Bits % 64 == 0 &&
7509          "The number of bits in a vector must be divisible by 64 on x86!");
7510   int NumExtElements = Bits / 64;
7511
7512   // Each iteration, try extending the elements half as much, but into twice as
7513   // many elements.
7514   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7515     assert(NumElements % NumExtElements == 0 &&
7516            "The input vector size must be divisible by the extended size.");
7517     if (SDValue V = Lower(NumElements / NumExtElements))
7518       return V;
7519   }
7520
7521   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7522   if (Bits != 128)
7523     return SDValue();
7524
7525   // Returns one of the source operands if the shuffle can be reduced to a
7526   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7527   auto CanZExtLowHalf = [&]() {
7528     for (int i = NumElements / 2; i != NumElements; ++i)
7529       if (!Zeroable[i])
7530         return SDValue();
7531     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7532       return V1;
7533     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7534       return V2;
7535     return SDValue();
7536   };
7537
7538   if (SDValue V = CanZExtLowHalf()) {
7539     V = DAG.getBitcast(MVT::v2i64, V);
7540     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7541     return DAG.getBitcast(VT, V);
7542   }
7543
7544   // No viable ext lowering found.
7545   return SDValue();
7546 }
7547
7548 /// \brief Try to get a scalar value for a specific element of a vector.
7549 ///
7550 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7551 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7552                                               SelectionDAG &DAG) {
7553   MVT VT = V.getSimpleValueType();
7554   MVT EltVT = VT.getVectorElementType();
7555   while (V.getOpcode() == ISD::BITCAST)
7556     V = V.getOperand(0);
7557   // If the bitcasts shift the element size, we can't extract an equivalent
7558   // element from it.
7559   MVT NewVT = V.getSimpleValueType();
7560   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7561     return SDValue();
7562
7563   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7564       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7565     // Ensure the scalar operand is the same size as the destination.
7566     // FIXME: Add support for scalar truncation where possible.
7567     SDValue S = V.getOperand(Idx);
7568     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7569       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7570   }
7571
7572   return SDValue();
7573 }
7574
7575 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7576 ///
7577 /// This is particularly important because the set of instructions varies
7578 /// significantly based on whether the operand is a load or not.
7579 static bool isShuffleFoldableLoad(SDValue V) {
7580   while (V.getOpcode() == ISD::BITCAST)
7581     V = V.getOperand(0);
7582
7583   return ISD::isNON_EXTLoad(V.getNode());
7584 }
7585
7586 /// \brief Try to lower insertion of a single element into a zero vector.
7587 ///
7588 /// This is a common pattern that we have especially efficient patterns to lower
7589 /// across all subtarget feature sets.
7590 static SDValue lowerVectorShuffleAsElementInsertion(
7591     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7592     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7593   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7594   MVT ExtVT = VT;
7595   MVT EltVT = VT.getVectorElementType();
7596
7597   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7598                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7599                 Mask.begin();
7600   bool IsV1Zeroable = true;
7601   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7602     if (i != V2Index && !Zeroable[i]) {
7603       IsV1Zeroable = false;
7604       break;
7605     }
7606
7607   // Check for a single input from a SCALAR_TO_VECTOR node.
7608   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7609   // all the smarts here sunk into that routine. However, the current
7610   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7611   // vector shuffle lowering is dead.
7612   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7613                                                DAG);
7614   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7615     // We need to zext the scalar if it is smaller than an i32.
7616     V2S = DAG.getBitcast(EltVT, V2S);
7617     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7618       // Using zext to expand a narrow element won't work for non-zero
7619       // insertions.
7620       if (!IsV1Zeroable)
7621         return SDValue();
7622
7623       // Zero-extend directly to i32.
7624       ExtVT = MVT::v4i32;
7625       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7626     }
7627     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7628   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7629              EltVT == MVT::i16) {
7630     // Either not inserting from the low element of the input or the input
7631     // element size is too small to use VZEXT_MOVL to clear the high bits.
7632     return SDValue();
7633   }
7634
7635   if (!IsV1Zeroable) {
7636     // If V1 can't be treated as a zero vector we have fewer options to lower
7637     // this. We can't support integer vectors or non-zero targets cheaply, and
7638     // the V1 elements can't be permuted in any way.
7639     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7640     if (!VT.isFloatingPoint() || V2Index != 0)
7641       return SDValue();
7642     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7643     V1Mask[V2Index] = -1;
7644     if (!isNoopShuffleMask(V1Mask))
7645       return SDValue();
7646     // This is essentially a special case blend operation, but if we have
7647     // general purpose blend operations, they are always faster. Bail and let
7648     // the rest of the lowering handle these as blends.
7649     if (Subtarget->hasSSE41())
7650       return SDValue();
7651
7652     // Otherwise, use MOVSD or MOVSS.
7653     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7654            "Only two types of floating point element types to handle!");
7655     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7656                        ExtVT, V1, V2);
7657   }
7658
7659   // This lowering only works for the low element with floating point vectors.
7660   if (VT.isFloatingPoint() && V2Index != 0)
7661     return SDValue();
7662
7663   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7664   if (ExtVT != VT)
7665     V2 = DAG.getBitcast(VT, V2);
7666
7667   if (V2Index != 0) {
7668     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7669     // the desired position. Otherwise it is more efficient to do a vector
7670     // shift left. We know that we can do a vector shift left because all
7671     // the inputs are zero.
7672     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7673       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7674       V2Shuffle[V2Index] = 0;
7675       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7676     } else {
7677       V2 = DAG.getBitcast(MVT::v2i64, V2);
7678       V2 = DAG.getNode(
7679           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7680           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7681                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7682                               DAG.getDataLayout(), VT)));
7683       V2 = DAG.getBitcast(VT, V2);
7684     }
7685   }
7686   return V2;
7687 }
7688
7689 /// \brief Try to lower broadcast of a single element.
7690 ///
7691 /// For convenience, this code also bundles all of the subtarget feature set
7692 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7693 /// a convenient way to factor it out.
7694 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7695                                              ArrayRef<int> Mask,
7696                                              const X86Subtarget *Subtarget,
7697                                              SelectionDAG &DAG) {
7698   if (!Subtarget->hasAVX())
7699     return SDValue();
7700   if (VT.isInteger() && !Subtarget->hasAVX2())
7701     return SDValue();
7702
7703   // Check that the mask is a broadcast.
7704   int BroadcastIdx = -1;
7705   for (int M : Mask)
7706     if (M >= 0 && BroadcastIdx == -1)
7707       BroadcastIdx = M;
7708     else if (M >= 0 && M != BroadcastIdx)
7709       return SDValue();
7710
7711   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7712                                             "a sorted mask where the broadcast "
7713                                             "comes from V1.");
7714
7715   // Go up the chain of (vector) values to find a scalar load that we can
7716   // combine with the broadcast.
7717   for (;;) {
7718     switch (V.getOpcode()) {
7719     case ISD::CONCAT_VECTORS: {
7720       int OperandSize = Mask.size() / V.getNumOperands();
7721       V = V.getOperand(BroadcastIdx / OperandSize);
7722       BroadcastIdx %= OperandSize;
7723       continue;
7724     }
7725
7726     case ISD::INSERT_SUBVECTOR: {
7727       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7728       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7729       if (!ConstantIdx)
7730         break;
7731
7732       int BeginIdx = (int)ConstantIdx->getZExtValue();
7733       int EndIdx =
7734           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7735       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7736         BroadcastIdx -= BeginIdx;
7737         V = VInner;
7738       } else {
7739         V = VOuter;
7740       }
7741       continue;
7742     }
7743     }
7744     break;
7745   }
7746
7747   // Check if this is a broadcast of a scalar. We special case lowering
7748   // for scalars so that we can more effectively fold with loads.
7749   // First, look through bitcast: if the original value has a larger element
7750   // type than the shuffle, the broadcast element is in essence truncated.
7751   // Make that explicit to ease folding.
7752   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7753     EVT EltVT = VT.getVectorElementType();
7754     SDValue V0 = V.getOperand(0);
7755     EVT V0VT = V0.getValueType();
7756
7757     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7758         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7759          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7760       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7761       BroadcastIdx = 0;
7762     }
7763   }
7764
7765   // Also check the simpler case, where we can directly reuse the scalar.
7766   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7767       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7768     V = V.getOperand(BroadcastIdx);
7769
7770     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7771     // Only AVX2 has register broadcasts.
7772     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7773       return SDValue();
7774   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7775     // We can't broadcast from a vector register without AVX2, and we can only
7776     // broadcast from the zero-element of a vector register.
7777     return SDValue();
7778   }
7779
7780   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7781 }
7782
7783 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7784 // INSERTPS when the V1 elements are already in the correct locations
7785 // because otherwise we can just always use two SHUFPS instructions which
7786 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7787 // perform INSERTPS if a single V1 element is out of place and all V2
7788 // elements are zeroable.
7789 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7790                                             ArrayRef<int> Mask,
7791                                             SelectionDAG &DAG) {
7792   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7793   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7794   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7795   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7796
7797   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7798
7799   unsigned ZMask = 0;
7800   int V1DstIndex = -1;
7801   int V2DstIndex = -1;
7802   bool V1UsedInPlace = false;
7803
7804   for (int i = 0; i < 4; ++i) {
7805     // Synthesize a zero mask from the zeroable elements (includes undefs).
7806     if (Zeroable[i]) {
7807       ZMask |= 1 << i;
7808       continue;
7809     }
7810
7811     // Flag if we use any V1 inputs in place.
7812     if (i == Mask[i]) {
7813       V1UsedInPlace = true;
7814       continue;
7815     }
7816
7817     // We can only insert a single non-zeroable element.
7818     if (V1DstIndex != -1 || V2DstIndex != -1)
7819       return SDValue();
7820
7821     if (Mask[i] < 4) {
7822       // V1 input out of place for insertion.
7823       V1DstIndex = i;
7824     } else {
7825       // V2 input for insertion.
7826       V2DstIndex = i;
7827     }
7828   }
7829
7830   // Don't bother if we have no (non-zeroable) element for insertion.
7831   if (V1DstIndex == -1 && V2DstIndex == -1)
7832     return SDValue();
7833
7834   // Determine element insertion src/dst indices. The src index is from the
7835   // start of the inserted vector, not the start of the concatenated vector.
7836   unsigned V2SrcIndex = 0;
7837   if (V1DstIndex != -1) {
7838     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7839     // and don't use the original V2 at all.
7840     V2SrcIndex = Mask[V1DstIndex];
7841     V2DstIndex = V1DstIndex;
7842     V2 = V1;
7843   } else {
7844     V2SrcIndex = Mask[V2DstIndex] - 4;
7845   }
7846
7847   // If no V1 inputs are used in place, then the result is created only from
7848   // the zero mask and the V2 insertion - so remove V1 dependency.
7849   if (!V1UsedInPlace)
7850     V1 = DAG.getUNDEF(MVT::v4f32);
7851
7852   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7853   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7854
7855   // Insert the V2 element into the desired position.
7856   SDLoc DL(Op);
7857   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7858                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7859 }
7860
7861 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7862 /// UNPCK instruction.
7863 ///
7864 /// This specifically targets cases where we end up with alternating between
7865 /// the two inputs, and so can permute them into something that feeds a single
7866 /// UNPCK instruction. Note that this routine only targets integer vectors
7867 /// because for floating point vectors we have a generalized SHUFPS lowering
7868 /// strategy that handles everything that doesn't *exactly* match an unpack,
7869 /// making this clever lowering unnecessary.
7870 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7871                                           SDValue V2, ArrayRef<int> Mask,
7872                                           SelectionDAG &DAG) {
7873   assert(!VT.isFloatingPoint() &&
7874          "This routine only supports integer vectors.");
7875   assert(!isSingleInputShuffleMask(Mask) &&
7876          "This routine should only be used when blending two inputs.");
7877   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7878
7879   int Size = Mask.size();
7880
7881   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7882     return M >= 0 && M % Size < Size / 2;
7883   });
7884   int NumHiInputs = std::count_if(
7885       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7886
7887   bool UnpackLo = NumLoInputs >= NumHiInputs;
7888
7889   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7890     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7891     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7892
7893     for (int i = 0; i < Size; ++i) {
7894       if (Mask[i] < 0)
7895         continue;
7896
7897       // Each element of the unpack contains Scale elements from this mask.
7898       int UnpackIdx = i / Scale;
7899
7900       // We only handle the case where V1 feeds the first slots of the unpack.
7901       // We rely on canonicalization to ensure this is the case.
7902       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7903         return SDValue();
7904
7905       // Setup the mask for this input. The indexing is tricky as we have to
7906       // handle the unpack stride.
7907       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7908       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7909           Mask[i] % Size;
7910     }
7911
7912     // If we will have to shuffle both inputs to use the unpack, check whether
7913     // we can just unpack first and shuffle the result. If so, skip this unpack.
7914     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7915         !isNoopShuffleMask(V2Mask))
7916       return SDValue();
7917
7918     // Shuffle the inputs into place.
7919     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7920     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7921
7922     // Cast the inputs to the type we will use to unpack them.
7923     V1 = DAG.getBitcast(UnpackVT, V1);
7924     V2 = DAG.getBitcast(UnpackVT, V2);
7925
7926     // Unpack the inputs and cast the result back to the desired type.
7927     return DAG.getBitcast(
7928         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7929                         UnpackVT, V1, V2));
7930   };
7931
7932   // We try each unpack from the largest to the smallest to try and find one
7933   // that fits this mask.
7934   int OrigNumElements = VT.getVectorNumElements();
7935   int OrigScalarSize = VT.getScalarSizeInBits();
7936   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7937     int Scale = ScalarSize / OrigScalarSize;
7938     int NumElements = OrigNumElements / Scale;
7939     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7940     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7941       return Unpack;
7942   }
7943
7944   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7945   // initial unpack.
7946   if (NumLoInputs == 0 || NumHiInputs == 0) {
7947     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7948            "We have to have *some* inputs!");
7949     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7950
7951     // FIXME: We could consider the total complexity of the permute of each
7952     // possible unpacking. Or at the least we should consider how many
7953     // half-crossings are created.
7954     // FIXME: We could consider commuting the unpacks.
7955
7956     SmallVector<int, 32> PermMask;
7957     PermMask.assign(Size, -1);
7958     for (int i = 0; i < Size; ++i) {
7959       if (Mask[i] < 0)
7960         continue;
7961
7962       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7963
7964       PermMask[i] =
7965           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7966     }
7967     return DAG.getVectorShuffle(
7968         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7969                             DL, VT, V1, V2),
7970         DAG.getUNDEF(VT), PermMask);
7971   }
7972
7973   return SDValue();
7974 }
7975
7976 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7977 ///
7978 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7979 /// support for floating point shuffles but not integer shuffles. These
7980 /// instructions will incur a domain crossing penalty on some chips though so
7981 /// it is better to avoid lowering through this for integer vectors where
7982 /// possible.
7983 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7984                                        const X86Subtarget *Subtarget,
7985                                        SelectionDAG &DAG) {
7986   SDLoc DL(Op);
7987   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7988   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7989   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7990   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7991   ArrayRef<int> Mask = SVOp->getMask();
7992   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7993
7994   if (isSingleInputShuffleMask(Mask)) {
7995     // Use low duplicate instructions for masks that match their pattern.
7996     if (Subtarget->hasSSE3())
7997       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7998         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7999
8000     // Straight shuffle of a single input vector. Simulate this by using the
8001     // single input as both of the "inputs" to this instruction..
8002     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8003
8004     if (Subtarget->hasAVX()) {
8005       // If we have AVX, we can use VPERMILPS which will allow folding a load
8006       // into the shuffle.
8007       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8008                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8009     }
8010
8011     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8012                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8013   }
8014   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8015   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8016
8017   // If we have a single input, insert that into V1 if we can do so cheaply.
8018   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8019     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8020             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8021       return Insertion;
8022     // Try inverting the insertion since for v2 masks it is easy to do and we
8023     // can't reliably sort the mask one way or the other.
8024     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8025                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8026     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8027             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8028       return Insertion;
8029   }
8030
8031   // Try to use one of the special instruction patterns to handle two common
8032   // blend patterns if a zero-blend above didn't work.
8033   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8034       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8035     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8036       // We can either use a special instruction to load over the low double or
8037       // to move just the low double.
8038       return DAG.getNode(
8039           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8040           DL, MVT::v2f64, V2,
8041           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8042
8043   if (Subtarget->hasSSE41())
8044     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8045                                                   Subtarget, DAG))
8046       return Blend;
8047
8048   // Use dedicated unpack instructions for masks that match their pattern.
8049   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8050     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8051   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8052     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8053
8054   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8055   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8056                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8057 }
8058
8059 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8060 ///
8061 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8062 /// the integer unit to minimize domain crossing penalties. However, for blends
8063 /// it falls back to the floating point shuffle operation with appropriate bit
8064 /// casting.
8065 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8066                                        const X86Subtarget *Subtarget,
8067                                        SelectionDAG &DAG) {
8068   SDLoc DL(Op);
8069   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8070   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8071   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8072   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8073   ArrayRef<int> Mask = SVOp->getMask();
8074   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8075
8076   if (isSingleInputShuffleMask(Mask)) {
8077     // Check for being able to broadcast a single element.
8078     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8079                                                           Mask, Subtarget, DAG))
8080       return Broadcast;
8081
8082     // Straight shuffle of a single input vector. For everything from SSE2
8083     // onward this has a single fast instruction with no scary immediates.
8084     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8085     V1 = DAG.getBitcast(MVT::v4i32, V1);
8086     int WidenedMask[4] = {
8087         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8088         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8089     return DAG.getBitcast(
8090         MVT::v2i64,
8091         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8092                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8093   }
8094   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8095   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8096   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8097   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8098
8099   // If we have a blend of two PACKUS operations an the blend aligns with the
8100   // low and half halves, we can just merge the PACKUS operations. This is
8101   // particularly important as it lets us merge shuffles that this routine itself
8102   // creates.
8103   auto GetPackNode = [](SDValue V) {
8104     while (V.getOpcode() == ISD::BITCAST)
8105       V = V.getOperand(0);
8106
8107     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8108   };
8109   if (SDValue V1Pack = GetPackNode(V1))
8110     if (SDValue V2Pack = GetPackNode(V2))
8111       return DAG.getBitcast(MVT::v2i64,
8112                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8113                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8114                                                      : V1Pack.getOperand(1),
8115                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8116                                                      : V2Pack.getOperand(1)));
8117
8118   // Try to use shift instructions.
8119   if (SDValue Shift =
8120           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8121     return Shift;
8122
8123   // When loading a scalar and then shuffling it into a vector we can often do
8124   // the insertion cheaply.
8125   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8126           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8127     return Insertion;
8128   // Try inverting the insertion since for v2 masks it is easy to do and we
8129   // can't reliably sort the mask one way or the other.
8130   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8131   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8132           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8133     return Insertion;
8134
8135   // We have different paths for blend lowering, but they all must use the
8136   // *exact* same predicate.
8137   bool IsBlendSupported = Subtarget->hasSSE41();
8138   if (IsBlendSupported)
8139     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8140                                                   Subtarget, DAG))
8141       return Blend;
8142
8143   // Use dedicated unpack instructions for masks that match their pattern.
8144   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8145     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8146   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8147     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8148
8149   // Try to use byte rotation instructions.
8150   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8151   if (Subtarget->hasSSSE3())
8152     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8153             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8154       return Rotate;
8155
8156   // If we have direct support for blends, we should lower by decomposing into
8157   // a permute. That will be faster than the domain cross.
8158   if (IsBlendSupported)
8159     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8160                                                       Mask, DAG);
8161
8162   // We implement this with SHUFPD which is pretty lame because it will likely
8163   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8164   // However, all the alternatives are still more cycles and newer chips don't
8165   // have this problem. It would be really nice if x86 had better shuffles here.
8166   V1 = DAG.getBitcast(MVT::v2f64, V1);
8167   V2 = DAG.getBitcast(MVT::v2f64, V2);
8168   return DAG.getBitcast(MVT::v2i64,
8169                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8170 }
8171
8172 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8173 ///
8174 /// This is used to disable more specialized lowerings when the shufps lowering
8175 /// will happen to be efficient.
8176 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8177   // This routine only handles 128-bit shufps.
8178   assert(Mask.size() == 4 && "Unsupported mask size!");
8179
8180   // To lower with a single SHUFPS we need to have the low half and high half
8181   // each requiring a single input.
8182   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8183     return false;
8184   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8185     return false;
8186
8187   return true;
8188 }
8189
8190 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8191 ///
8192 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8193 /// It makes no assumptions about whether this is the *best* lowering, it simply
8194 /// uses it.
8195 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8196                                             ArrayRef<int> Mask, SDValue V1,
8197                                             SDValue V2, SelectionDAG &DAG) {
8198   SDValue LowV = V1, HighV = V2;
8199   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8200
8201   int NumV2Elements =
8202       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8203
8204   if (NumV2Elements == 1) {
8205     int V2Index =
8206         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8207         Mask.begin();
8208
8209     // Compute the index adjacent to V2Index and in the same half by toggling
8210     // the low bit.
8211     int V2AdjIndex = V2Index ^ 1;
8212
8213     if (Mask[V2AdjIndex] == -1) {
8214       // Handles all the cases where we have a single V2 element and an undef.
8215       // This will only ever happen in the high lanes because we commute the
8216       // vector otherwise.
8217       if (V2Index < 2)
8218         std::swap(LowV, HighV);
8219       NewMask[V2Index] -= 4;
8220     } else {
8221       // Handle the case where the V2 element ends up adjacent to a V1 element.
8222       // To make this work, blend them together as the first step.
8223       int V1Index = V2AdjIndex;
8224       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8225       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8226                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8227
8228       // Now proceed to reconstruct the final blend as we have the necessary
8229       // high or low half formed.
8230       if (V2Index < 2) {
8231         LowV = V2;
8232         HighV = V1;
8233       } else {
8234         HighV = V2;
8235       }
8236       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8237       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8238     }
8239   } else if (NumV2Elements == 2) {
8240     if (Mask[0] < 4 && Mask[1] < 4) {
8241       // Handle the easy case where we have V1 in the low lanes and V2 in the
8242       // high lanes.
8243       NewMask[2] -= 4;
8244       NewMask[3] -= 4;
8245     } else if (Mask[2] < 4 && Mask[3] < 4) {
8246       // We also handle the reversed case because this utility may get called
8247       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8248       // arrange things in the right direction.
8249       NewMask[0] -= 4;
8250       NewMask[1] -= 4;
8251       HighV = V1;
8252       LowV = V2;
8253     } else {
8254       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8255       // trying to place elements directly, just blend them and set up the final
8256       // shuffle to place them.
8257
8258       // The first two blend mask elements are for V1, the second two are for
8259       // V2.
8260       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8261                           Mask[2] < 4 ? Mask[2] : Mask[3],
8262                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8263                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8264       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8265                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8266
8267       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8268       // a blend.
8269       LowV = HighV = V1;
8270       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8271       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8272       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8273       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8274     }
8275   }
8276   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8277                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8278 }
8279
8280 /// \brief Lower 4-lane 32-bit floating point shuffles.
8281 ///
8282 /// Uses instructions exclusively from the floating point unit to minimize
8283 /// domain crossing penalties, as these are sufficient to implement all v4f32
8284 /// shuffles.
8285 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8286                                        const X86Subtarget *Subtarget,
8287                                        SelectionDAG &DAG) {
8288   SDLoc DL(Op);
8289   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8290   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8291   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8292   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8293   ArrayRef<int> Mask = SVOp->getMask();
8294   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8295
8296   int NumV2Elements =
8297       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8298
8299   if (NumV2Elements == 0) {
8300     // Check for being able to broadcast a single element.
8301     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8302                                                           Mask, Subtarget, DAG))
8303       return Broadcast;
8304
8305     // Use even/odd duplicate instructions for masks that match their pattern.
8306     if (Subtarget->hasSSE3()) {
8307       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8308         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8309       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8310         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8311     }
8312
8313     if (Subtarget->hasAVX()) {
8314       // If we have AVX, we can use VPERMILPS which will allow folding a load
8315       // into the shuffle.
8316       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8317                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8318     }
8319
8320     // Otherwise, use a straight shuffle of a single input vector. We pass the
8321     // input vector to both operands to simulate this with a SHUFPS.
8322     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8323                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8324   }
8325
8326   // There are special ways we can lower some single-element blends. However, we
8327   // have custom ways we can lower more complex single-element blends below that
8328   // we defer to if both this and BLENDPS fail to match, so restrict this to
8329   // when the V2 input is targeting element 0 of the mask -- that is the fast
8330   // case here.
8331   if (NumV2Elements == 1 && Mask[0] >= 4)
8332     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8333                                                          Mask, Subtarget, DAG))
8334       return V;
8335
8336   if (Subtarget->hasSSE41()) {
8337     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8338                                                   Subtarget, DAG))
8339       return Blend;
8340
8341     // Use INSERTPS if we can complete the shuffle efficiently.
8342     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8343       return V;
8344
8345     if (!isSingleSHUFPSMask(Mask))
8346       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8347               DL, MVT::v4f32, V1, V2, Mask, DAG))
8348         return BlendPerm;
8349   }
8350
8351   // Use dedicated unpack instructions for masks that match their pattern.
8352   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8353     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8354   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8355     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8356   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8357     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8358   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8359     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8360
8361   // Otherwise fall back to a SHUFPS lowering strategy.
8362   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8363 }
8364
8365 /// \brief Lower 4-lane i32 vector shuffles.
8366 ///
8367 /// We try to handle these with integer-domain shuffles where we can, but for
8368 /// blends we use the floating point domain blend instructions.
8369 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8370                                        const X86Subtarget *Subtarget,
8371                                        SelectionDAG &DAG) {
8372   SDLoc DL(Op);
8373   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8374   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8375   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8376   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8377   ArrayRef<int> Mask = SVOp->getMask();
8378   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8379
8380   // Whenever we can lower this as a zext, that instruction is strictly faster
8381   // than any alternative. It also allows us to fold memory operands into the
8382   // shuffle in many cases.
8383   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8384                                                          Mask, Subtarget, DAG))
8385     return ZExt;
8386
8387   int NumV2Elements =
8388       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8389
8390   if (NumV2Elements == 0) {
8391     // Check for being able to broadcast a single element.
8392     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8393                                                           Mask, Subtarget, DAG))
8394       return Broadcast;
8395
8396     // Straight shuffle of a single input vector. For everything from SSE2
8397     // onward this has a single fast instruction with no scary immediates.
8398     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8399     // but we aren't actually going to use the UNPCK instruction because doing
8400     // so prevents folding a load into this instruction or making a copy.
8401     const int UnpackLoMask[] = {0, 0, 1, 1};
8402     const int UnpackHiMask[] = {2, 2, 3, 3};
8403     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8404       Mask = UnpackLoMask;
8405     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8406       Mask = UnpackHiMask;
8407
8408     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8409                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8410   }
8411
8412   // Try to use shift instructions.
8413   if (SDValue Shift =
8414           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8415     return Shift;
8416
8417   // There are special ways we can lower some single-element blends.
8418   if (NumV2Elements == 1)
8419     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8420                                                          Mask, Subtarget, DAG))
8421       return V;
8422
8423   // We have different paths for blend lowering, but they all must use the
8424   // *exact* same predicate.
8425   bool IsBlendSupported = Subtarget->hasSSE41();
8426   if (IsBlendSupported)
8427     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8428                                                   Subtarget, DAG))
8429       return Blend;
8430
8431   if (SDValue Masked =
8432           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8433     return Masked;
8434
8435   // Use dedicated unpack instructions for masks that match their pattern.
8436   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8437     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8438   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8439     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8440   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8441     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8442   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8443     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8444
8445   // Try to use byte rotation instructions.
8446   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8447   if (Subtarget->hasSSSE3())
8448     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8449             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8450       return Rotate;
8451
8452   // If we have direct support for blends, we should lower by decomposing into
8453   // a permute. That will be faster than the domain cross.
8454   if (IsBlendSupported)
8455     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8456                                                       Mask, DAG);
8457
8458   // Try to lower by permuting the inputs into an unpack instruction.
8459   if (SDValue Unpack =
8460           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8461     return Unpack;
8462
8463   // We implement this with SHUFPS because it can blend from two vectors.
8464   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8465   // up the inputs, bypassing domain shift penalties that we would encur if we
8466   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8467   // relevant.
8468   return DAG.getBitcast(
8469       MVT::v4i32,
8470       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8471                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8472 }
8473
8474 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8475 /// shuffle lowering, and the most complex part.
8476 ///
8477 /// The lowering strategy is to try to form pairs of input lanes which are
8478 /// targeted at the same half of the final vector, and then use a dword shuffle
8479 /// to place them onto the right half, and finally unpack the paired lanes into
8480 /// their final position.
8481 ///
8482 /// The exact breakdown of how to form these dword pairs and align them on the
8483 /// correct sides is really tricky. See the comments within the function for
8484 /// more of the details.
8485 ///
8486 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8487 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8488 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8489 /// vector, form the analogous 128-bit 8-element Mask.
8490 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8491     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8492     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8493   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8494   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8495
8496   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8497   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8498   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8499
8500   SmallVector<int, 4> LoInputs;
8501   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8502                [](int M) { return M >= 0; });
8503   std::sort(LoInputs.begin(), LoInputs.end());
8504   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8505   SmallVector<int, 4> HiInputs;
8506   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8507                [](int M) { return M >= 0; });
8508   std::sort(HiInputs.begin(), HiInputs.end());
8509   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8510   int NumLToL =
8511       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8512   int NumHToL = LoInputs.size() - NumLToL;
8513   int NumLToH =
8514       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8515   int NumHToH = HiInputs.size() - NumLToH;
8516   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8517   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8518   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8519   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8520
8521   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8522   // such inputs we can swap two of the dwords across the half mark and end up
8523   // with <=2 inputs to each half in each half. Once there, we can fall through
8524   // to the generic code below. For example:
8525   //
8526   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8527   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8528   //
8529   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8530   // and an existing 2-into-2 on the other half. In this case we may have to
8531   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8532   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8533   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8534   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8535   // half than the one we target for fixing) will be fixed when we re-enter this
8536   // path. We will also combine away any sequence of PSHUFD instructions that
8537   // result into a single instruction. Here is an example of the tricky case:
8538   //
8539   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8540   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8541   //
8542   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8543   //
8544   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8545   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8546   //
8547   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8548   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8549   //
8550   // The result is fine to be handled by the generic logic.
8551   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8552                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8553                           int AOffset, int BOffset) {
8554     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8555            "Must call this with A having 3 or 1 inputs from the A half.");
8556     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8557            "Must call this with B having 1 or 3 inputs from the B half.");
8558     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8559            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8560
8561     bool ThreeAInputs = AToAInputs.size() == 3;
8562
8563     // Compute the index of dword with only one word among the three inputs in
8564     // a half by taking the sum of the half with three inputs and subtracting
8565     // the sum of the actual three inputs. The difference is the remaining
8566     // slot.
8567     int ADWord, BDWord;
8568     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8569     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8570     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8571     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8572     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8573     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8574     int TripleNonInputIdx =
8575         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8576     TripleDWord = TripleNonInputIdx / 2;
8577
8578     // We use xor with one to compute the adjacent DWord to whichever one the
8579     // OneInput is in.
8580     OneInputDWord = (OneInput / 2) ^ 1;
8581
8582     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8583     // and BToA inputs. If there is also such a problem with the BToB and AToB
8584     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8585     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8586     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8587     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8588       // Compute how many inputs will be flipped by swapping these DWords. We
8589       // need
8590       // to balance this to ensure we don't form a 3-1 shuffle in the other
8591       // half.
8592       int NumFlippedAToBInputs =
8593           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8594           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8595       int NumFlippedBToBInputs =
8596           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8597           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8598       if ((NumFlippedAToBInputs == 1 &&
8599            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8600           (NumFlippedBToBInputs == 1 &&
8601            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8602         // We choose whether to fix the A half or B half based on whether that
8603         // half has zero flipped inputs. At zero, we may not be able to fix it
8604         // with that half. We also bias towards fixing the B half because that
8605         // will more commonly be the high half, and we have to bias one way.
8606         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8607                                                        ArrayRef<int> Inputs) {
8608           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8609           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8610                                          PinnedIdx ^ 1) != Inputs.end();
8611           // Determine whether the free index is in the flipped dword or the
8612           // unflipped dword based on where the pinned index is. We use this bit
8613           // in an xor to conditionally select the adjacent dword.
8614           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8615           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8616                                              FixFreeIdx) != Inputs.end();
8617           if (IsFixIdxInput == IsFixFreeIdxInput)
8618             FixFreeIdx += 1;
8619           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8620                                         FixFreeIdx) != Inputs.end();
8621           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8622                  "We need to be changing the number of flipped inputs!");
8623           int PSHUFHalfMask[] = {0, 1, 2, 3};
8624           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8625           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8626                           MVT::v8i16, V,
8627                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8628
8629           for (int &M : Mask)
8630             if (M != -1 && M == FixIdx)
8631               M = FixFreeIdx;
8632             else if (M != -1 && M == FixFreeIdx)
8633               M = FixIdx;
8634         };
8635         if (NumFlippedBToBInputs != 0) {
8636           int BPinnedIdx =
8637               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8638           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8639         } else {
8640           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8641           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8642           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8643         }
8644       }
8645     }
8646
8647     int PSHUFDMask[] = {0, 1, 2, 3};
8648     PSHUFDMask[ADWord] = BDWord;
8649     PSHUFDMask[BDWord] = ADWord;
8650     V = DAG.getBitcast(
8651         VT,
8652         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8653                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8654
8655     // Adjust the mask to match the new locations of A and B.
8656     for (int &M : Mask)
8657       if (M != -1 && M/2 == ADWord)
8658         M = 2 * BDWord + M % 2;
8659       else if (M != -1 && M/2 == BDWord)
8660         M = 2 * ADWord + M % 2;
8661
8662     // Recurse back into this routine to re-compute state now that this isn't
8663     // a 3 and 1 problem.
8664     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8665                                                      DAG);
8666   };
8667   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8668     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8669   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8670     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8671
8672   // At this point there are at most two inputs to the low and high halves from
8673   // each half. That means the inputs can always be grouped into dwords and
8674   // those dwords can then be moved to the correct half with a dword shuffle.
8675   // We use at most one low and one high word shuffle to collect these paired
8676   // inputs into dwords, and finally a dword shuffle to place them.
8677   int PSHUFLMask[4] = {-1, -1, -1, -1};
8678   int PSHUFHMask[4] = {-1, -1, -1, -1};
8679   int PSHUFDMask[4] = {-1, -1, -1, -1};
8680
8681   // First fix the masks for all the inputs that are staying in their
8682   // original halves. This will then dictate the targets of the cross-half
8683   // shuffles.
8684   auto fixInPlaceInputs =
8685       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8686                     MutableArrayRef<int> SourceHalfMask,
8687                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8688     if (InPlaceInputs.empty())
8689       return;
8690     if (InPlaceInputs.size() == 1) {
8691       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8692           InPlaceInputs[0] - HalfOffset;
8693       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8694       return;
8695     }
8696     if (IncomingInputs.empty()) {
8697       // Just fix all of the in place inputs.
8698       for (int Input : InPlaceInputs) {
8699         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8700         PSHUFDMask[Input / 2] = Input / 2;
8701       }
8702       return;
8703     }
8704
8705     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8706     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8707         InPlaceInputs[0] - HalfOffset;
8708     // Put the second input next to the first so that they are packed into
8709     // a dword. We find the adjacent index by toggling the low bit.
8710     int AdjIndex = InPlaceInputs[0] ^ 1;
8711     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8712     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8713     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8714   };
8715   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8716   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8717
8718   // Now gather the cross-half inputs and place them into a free dword of
8719   // their target half.
8720   // FIXME: This operation could almost certainly be simplified dramatically to
8721   // look more like the 3-1 fixing operation.
8722   auto moveInputsToRightHalf = [&PSHUFDMask](
8723       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8724       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8725       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8726       int DestOffset) {
8727     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8728       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8729     };
8730     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8731                                                int Word) {
8732       int LowWord = Word & ~1;
8733       int HighWord = Word | 1;
8734       return isWordClobbered(SourceHalfMask, LowWord) ||
8735              isWordClobbered(SourceHalfMask, HighWord);
8736     };
8737
8738     if (IncomingInputs.empty())
8739       return;
8740
8741     if (ExistingInputs.empty()) {
8742       // Map any dwords with inputs from them into the right half.
8743       for (int Input : IncomingInputs) {
8744         // If the source half mask maps over the inputs, turn those into
8745         // swaps and use the swapped lane.
8746         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8747           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8748             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8749                 Input - SourceOffset;
8750             // We have to swap the uses in our half mask in one sweep.
8751             for (int &M : HalfMask)
8752               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8753                 M = Input;
8754               else if (M == Input)
8755                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8756           } else {
8757             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8758                        Input - SourceOffset &&
8759                    "Previous placement doesn't match!");
8760           }
8761           // Note that this correctly re-maps both when we do a swap and when
8762           // we observe the other side of the swap above. We rely on that to
8763           // avoid swapping the members of the input list directly.
8764           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8765         }
8766
8767         // Map the input's dword into the correct half.
8768         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8769           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8770         else
8771           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8772                      Input / 2 &&
8773                  "Previous placement doesn't match!");
8774       }
8775
8776       // And just directly shift any other-half mask elements to be same-half
8777       // as we will have mirrored the dword containing the element into the
8778       // same position within that half.
8779       for (int &M : HalfMask)
8780         if (M >= SourceOffset && M < SourceOffset + 4) {
8781           M = M - SourceOffset + DestOffset;
8782           assert(M >= 0 && "This should never wrap below zero!");
8783         }
8784       return;
8785     }
8786
8787     // Ensure we have the input in a viable dword of its current half. This
8788     // is particularly tricky because the original position may be clobbered
8789     // by inputs being moved and *staying* in that half.
8790     if (IncomingInputs.size() == 1) {
8791       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8792         int InputFixed = std::find(std::begin(SourceHalfMask),
8793                                    std::end(SourceHalfMask), -1) -
8794                          std::begin(SourceHalfMask) + SourceOffset;
8795         SourceHalfMask[InputFixed - SourceOffset] =
8796             IncomingInputs[0] - SourceOffset;
8797         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8798                      InputFixed);
8799         IncomingInputs[0] = InputFixed;
8800       }
8801     } else if (IncomingInputs.size() == 2) {
8802       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8803           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8804         // We have two non-adjacent or clobbered inputs we need to extract from
8805         // the source half. To do this, we need to map them into some adjacent
8806         // dword slot in the source mask.
8807         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8808                               IncomingInputs[1] - SourceOffset};
8809
8810         // If there is a free slot in the source half mask adjacent to one of
8811         // the inputs, place the other input in it. We use (Index XOR 1) to
8812         // compute an adjacent index.
8813         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8814             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8815           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8816           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8817           InputsFixed[1] = InputsFixed[0] ^ 1;
8818         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8819                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8820           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8821           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8822           InputsFixed[0] = InputsFixed[1] ^ 1;
8823         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8824                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8825           // The two inputs are in the same DWord but it is clobbered and the
8826           // adjacent DWord isn't used at all. Move both inputs to the free
8827           // slot.
8828           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8829           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8830           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8831           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8832         } else {
8833           // The only way we hit this point is if there is no clobbering
8834           // (because there are no off-half inputs to this half) and there is no
8835           // free slot adjacent to one of the inputs. In this case, we have to
8836           // swap an input with a non-input.
8837           for (int i = 0; i < 4; ++i)
8838             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8839                    "We can't handle any clobbers here!");
8840           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8841                  "Cannot have adjacent inputs here!");
8842
8843           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8844           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8845
8846           // We also have to update the final source mask in this case because
8847           // it may need to undo the above swap.
8848           for (int &M : FinalSourceHalfMask)
8849             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8850               M = InputsFixed[1] + SourceOffset;
8851             else if (M == InputsFixed[1] + SourceOffset)
8852               M = (InputsFixed[0] ^ 1) + SourceOffset;
8853
8854           InputsFixed[1] = InputsFixed[0] ^ 1;
8855         }
8856
8857         // Point everything at the fixed inputs.
8858         for (int &M : HalfMask)
8859           if (M == IncomingInputs[0])
8860             M = InputsFixed[0] + SourceOffset;
8861           else if (M == IncomingInputs[1])
8862             M = InputsFixed[1] + SourceOffset;
8863
8864         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8865         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8866       }
8867     } else {
8868       llvm_unreachable("Unhandled input size!");
8869     }
8870
8871     // Now hoist the DWord down to the right half.
8872     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8873     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8874     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8875     for (int &M : HalfMask)
8876       for (int Input : IncomingInputs)
8877         if (M == Input)
8878           M = FreeDWord * 2 + Input % 2;
8879   };
8880   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8881                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8882   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8883                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8884
8885   // Now enact all the shuffles we've computed to move the inputs into their
8886   // target half.
8887   if (!isNoopShuffleMask(PSHUFLMask))
8888     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8889                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8890   if (!isNoopShuffleMask(PSHUFHMask))
8891     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8892                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8893   if (!isNoopShuffleMask(PSHUFDMask))
8894     V = DAG.getBitcast(
8895         VT,
8896         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8897                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8898
8899   // At this point, each half should contain all its inputs, and we can then
8900   // just shuffle them into their final position.
8901   assert(std::count_if(LoMask.begin(), LoMask.end(),
8902                        [](int M) { return M >= 4; }) == 0 &&
8903          "Failed to lift all the high half inputs to the low mask!");
8904   assert(std::count_if(HiMask.begin(), HiMask.end(),
8905                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8906          "Failed to lift all the low half inputs to the high mask!");
8907
8908   // Do a half shuffle for the low mask.
8909   if (!isNoopShuffleMask(LoMask))
8910     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8911                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8912
8913   // Do a half shuffle with the high mask after shifting its values down.
8914   for (int &M : HiMask)
8915     if (M >= 0)
8916       M -= 4;
8917   if (!isNoopShuffleMask(HiMask))
8918     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8919                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8920
8921   return V;
8922 }
8923
8924 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8925 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8926                                           SDValue V2, ArrayRef<int> Mask,
8927                                           SelectionDAG &DAG, bool &V1InUse,
8928                                           bool &V2InUse) {
8929   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8930   SDValue V1Mask[16];
8931   SDValue V2Mask[16];
8932   V1InUse = false;
8933   V2InUse = false;
8934
8935   int Size = Mask.size();
8936   int Scale = 16 / Size;
8937   for (int i = 0; i < 16; ++i) {
8938     if (Mask[i / Scale] == -1) {
8939       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8940     } else {
8941       const int ZeroMask = 0x80;
8942       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8943                                           : ZeroMask;
8944       int V2Idx = Mask[i / Scale] < Size
8945                       ? ZeroMask
8946                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8947       if (Zeroable[i / Scale])
8948         V1Idx = V2Idx = ZeroMask;
8949       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8950       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8951       V1InUse |= (ZeroMask != V1Idx);
8952       V2InUse |= (ZeroMask != V2Idx);
8953     }
8954   }
8955
8956   if (V1InUse)
8957     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8958                      DAG.getBitcast(MVT::v16i8, V1),
8959                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8960   if (V2InUse)
8961     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8962                      DAG.getBitcast(MVT::v16i8, V2),
8963                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8964
8965   // If we need shuffled inputs from both, blend the two.
8966   SDValue V;
8967   if (V1InUse && V2InUse)
8968     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8969   else
8970     V = V1InUse ? V1 : V2;
8971
8972   // Cast the result back to the correct type.
8973   return DAG.getBitcast(VT, V);
8974 }
8975
8976 /// \brief Generic lowering of 8-lane i16 shuffles.
8977 ///
8978 /// This handles both single-input shuffles and combined shuffle/blends with
8979 /// two inputs. The single input shuffles are immediately delegated to
8980 /// a dedicated lowering routine.
8981 ///
8982 /// The blends are lowered in one of three fundamental ways. If there are few
8983 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8984 /// of the input is significantly cheaper when lowered as an interleaving of
8985 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8986 /// halves of the inputs separately (making them have relatively few inputs)
8987 /// and then concatenate them.
8988 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8989                                        const X86Subtarget *Subtarget,
8990                                        SelectionDAG &DAG) {
8991   SDLoc DL(Op);
8992   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8993   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8994   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8995   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8996   ArrayRef<int> OrigMask = SVOp->getMask();
8997   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8998                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8999   MutableArrayRef<int> Mask(MaskStorage);
9000
9001   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9002
9003   // Whenever we can lower this as a zext, that instruction is strictly faster
9004   // than any alternative.
9005   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9006           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9007     return ZExt;
9008
9009   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9010   (void)isV1;
9011   auto isV2 = [](int M) { return M >= 8; };
9012
9013   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9014
9015   if (NumV2Inputs == 0) {
9016     // Check for being able to broadcast a single element.
9017     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9018                                                           Mask, Subtarget, DAG))
9019       return Broadcast;
9020
9021     // Try to use shift instructions.
9022     if (SDValue Shift =
9023             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9024       return Shift;
9025
9026     // Use dedicated unpack instructions for masks that match their pattern.
9027     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9028       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9029     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9030       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9031
9032     // Try to use byte rotation instructions.
9033     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9034                                                         Mask, Subtarget, DAG))
9035       return Rotate;
9036
9037     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9038                                                      Subtarget, DAG);
9039   }
9040
9041   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9042          "All single-input shuffles should be canonicalized to be V1-input "
9043          "shuffles.");
9044
9045   // Try to use shift instructions.
9046   if (SDValue Shift =
9047           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9048     return Shift;
9049
9050   // See if we can use SSE4A Extraction / Insertion.
9051   if (Subtarget->hasSSE4A())
9052     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9053       return V;
9054
9055   // There are special ways we can lower some single-element blends.
9056   if (NumV2Inputs == 1)
9057     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9058                                                          Mask, Subtarget, DAG))
9059       return V;
9060
9061   // We have different paths for blend lowering, but they all must use the
9062   // *exact* same predicate.
9063   bool IsBlendSupported = Subtarget->hasSSE41();
9064   if (IsBlendSupported)
9065     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9066                                                   Subtarget, DAG))
9067       return Blend;
9068
9069   if (SDValue Masked =
9070           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9071     return Masked;
9072
9073   // Use dedicated unpack instructions for masks that match their pattern.
9074   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9075     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9076   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9077     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9078
9079   // Try to use byte rotation instructions.
9080   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9081           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9082     return Rotate;
9083
9084   if (SDValue BitBlend =
9085           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9086     return BitBlend;
9087
9088   if (SDValue Unpack =
9089           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
9090     return Unpack;
9091
9092   // If we can't directly blend but can use PSHUFB, that will be better as it
9093   // can both shuffle and set up the inefficient blend.
9094   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9095     bool V1InUse, V2InUse;
9096     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9097                                       V1InUse, V2InUse);
9098   }
9099
9100   // We can always bit-blend if we have to so the fallback strategy is to
9101   // decompose into single-input permutes and blends.
9102   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9103                                                       Mask, DAG);
9104 }
9105
9106 /// \brief Check whether a compaction lowering can be done by dropping even
9107 /// elements and compute how many times even elements must be dropped.
9108 ///
9109 /// This handles shuffles which take every Nth element where N is a power of
9110 /// two. Example shuffle masks:
9111 ///
9112 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9113 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9114 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9115 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9116 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9117 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9118 ///
9119 /// Any of these lanes can of course be undef.
9120 ///
9121 /// This routine only supports N <= 3.
9122 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9123 /// for larger N.
9124 ///
9125 /// \returns N above, or the number of times even elements must be dropped if
9126 /// there is such a number. Otherwise returns zero.
9127 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9128   // Figure out whether we're looping over two inputs or just one.
9129   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9130
9131   // The modulus for the shuffle vector entries is based on whether this is
9132   // a single input or not.
9133   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9134   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9135          "We should only be called with masks with a power-of-2 size!");
9136
9137   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9138
9139   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9140   // and 2^3 simultaneously. This is because we may have ambiguity with
9141   // partially undef inputs.
9142   bool ViableForN[3] = {true, true, true};
9143
9144   for (int i = 0, e = Mask.size(); i < e; ++i) {
9145     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9146     // want.
9147     if (Mask[i] == -1)
9148       continue;
9149
9150     bool IsAnyViable = false;
9151     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9152       if (ViableForN[j]) {
9153         uint64_t N = j + 1;
9154
9155         // The shuffle mask must be equal to (i * 2^N) % M.
9156         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9157           IsAnyViable = true;
9158         else
9159           ViableForN[j] = false;
9160       }
9161     // Early exit if we exhaust the possible powers of two.
9162     if (!IsAnyViable)
9163       break;
9164   }
9165
9166   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9167     if (ViableForN[j])
9168       return j + 1;
9169
9170   // Return 0 as there is no viable power of two.
9171   return 0;
9172 }
9173
9174 /// \brief Generic lowering of v16i8 shuffles.
9175 ///
9176 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9177 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9178 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9179 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9180 /// back together.
9181 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9182                                        const X86Subtarget *Subtarget,
9183                                        SelectionDAG &DAG) {
9184   SDLoc DL(Op);
9185   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9186   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9187   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9188   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9189   ArrayRef<int> Mask = SVOp->getMask();
9190   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9191
9192   // Try to use shift instructions.
9193   if (SDValue Shift =
9194           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9195     return Shift;
9196
9197   // Try to use byte rotation instructions.
9198   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9199           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9200     return Rotate;
9201
9202   // Try to use a zext lowering.
9203   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9204           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9205     return ZExt;
9206
9207   // See if we can use SSE4A Extraction / Insertion.
9208   if (Subtarget->hasSSE4A())
9209     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9210       return V;
9211
9212   int NumV2Elements =
9213       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9214
9215   // For single-input shuffles, there are some nicer lowering tricks we can use.
9216   if (NumV2Elements == 0) {
9217     // Check for being able to broadcast a single element.
9218     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9219                                                           Mask, Subtarget, DAG))
9220       return Broadcast;
9221
9222     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9223     // Notably, this handles splat and partial-splat shuffles more efficiently.
9224     // However, it only makes sense if the pre-duplication shuffle simplifies
9225     // things significantly. Currently, this means we need to be able to
9226     // express the pre-duplication shuffle as an i16 shuffle.
9227     //
9228     // FIXME: We should check for other patterns which can be widened into an
9229     // i16 shuffle as well.
9230     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9231       for (int i = 0; i < 16; i += 2)
9232         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9233           return false;
9234
9235       return true;
9236     };
9237     auto tryToWidenViaDuplication = [&]() -> SDValue {
9238       if (!canWidenViaDuplication(Mask))
9239         return SDValue();
9240       SmallVector<int, 4> LoInputs;
9241       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9242                    [](int M) { return M >= 0 && M < 8; });
9243       std::sort(LoInputs.begin(), LoInputs.end());
9244       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9245                      LoInputs.end());
9246       SmallVector<int, 4> HiInputs;
9247       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9248                    [](int M) { return M >= 8; });
9249       std::sort(HiInputs.begin(), HiInputs.end());
9250       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9251                      HiInputs.end());
9252
9253       bool TargetLo = LoInputs.size() >= HiInputs.size();
9254       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9255       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9256
9257       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9258       SmallDenseMap<int, int, 8> LaneMap;
9259       for (int I : InPlaceInputs) {
9260         PreDupI16Shuffle[I/2] = I/2;
9261         LaneMap[I] = I;
9262       }
9263       int j = TargetLo ? 0 : 4, je = j + 4;
9264       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9265         // Check if j is already a shuffle of this input. This happens when
9266         // there are two adjacent bytes after we move the low one.
9267         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9268           // If we haven't yet mapped the input, search for a slot into which
9269           // we can map it.
9270           while (j < je && PreDupI16Shuffle[j] != -1)
9271             ++j;
9272
9273           if (j == je)
9274             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9275             return SDValue();
9276
9277           // Map this input with the i16 shuffle.
9278           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9279         }
9280
9281         // Update the lane map based on the mapping we ended up with.
9282         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9283       }
9284       V1 = DAG.getBitcast(
9285           MVT::v16i8,
9286           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9287                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9288
9289       // Unpack the bytes to form the i16s that will be shuffled into place.
9290       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9291                        MVT::v16i8, V1, V1);
9292
9293       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9294       for (int i = 0; i < 16; ++i)
9295         if (Mask[i] != -1) {
9296           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9297           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9298           if (PostDupI16Shuffle[i / 2] == -1)
9299             PostDupI16Shuffle[i / 2] = MappedMask;
9300           else
9301             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9302                    "Conflicting entrties in the original shuffle!");
9303         }
9304       return DAG.getBitcast(
9305           MVT::v16i8,
9306           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9307                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9308     };
9309     if (SDValue V = tryToWidenViaDuplication())
9310       return V;
9311   }
9312
9313   if (SDValue Masked =
9314           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9315     return Masked;
9316
9317   // Use dedicated unpack instructions for masks that match their pattern.
9318   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9319                                          0, 16, 1, 17, 2, 18, 3, 19,
9320                                          // High half.
9321                                          4, 20, 5, 21, 6, 22, 7, 23}))
9322     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9323   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9324                                          8, 24, 9, 25, 10, 26, 11, 27,
9325                                          // High half.
9326                                          12, 28, 13, 29, 14, 30, 15, 31}))
9327     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9328
9329   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9330   // with PSHUFB. It is important to do this before we attempt to generate any
9331   // blends but after all of the single-input lowerings. If the single input
9332   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9333   // want to preserve that and we can DAG combine any longer sequences into
9334   // a PSHUFB in the end. But once we start blending from multiple inputs,
9335   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9336   // and there are *very* few patterns that would actually be faster than the
9337   // PSHUFB approach because of its ability to zero lanes.
9338   //
9339   // FIXME: The only exceptions to the above are blends which are exact
9340   // interleavings with direct instructions supporting them. We currently don't
9341   // handle those well here.
9342   if (Subtarget->hasSSSE3()) {
9343     bool V1InUse = false;
9344     bool V2InUse = false;
9345
9346     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9347                                                 DAG, V1InUse, V2InUse);
9348
9349     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9350     // do so. This avoids using them to handle blends-with-zero which is
9351     // important as a single pshufb is significantly faster for that.
9352     if (V1InUse && V2InUse) {
9353       if (Subtarget->hasSSE41())
9354         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9355                                                       Mask, Subtarget, DAG))
9356           return Blend;
9357
9358       // We can use an unpack to do the blending rather than an or in some
9359       // cases. Even though the or may be (very minorly) more efficient, we
9360       // preference this lowering because there are common cases where part of
9361       // the complexity of the shuffles goes away when we do the final blend as
9362       // an unpack.
9363       // FIXME: It might be worth trying to detect if the unpack-feeding
9364       // shuffles will both be pshufb, in which case we shouldn't bother with
9365       // this.
9366       if (SDValue Unpack =
9367               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9368         return Unpack;
9369     }
9370
9371     return PSHUFB;
9372   }
9373
9374   // There are special ways we can lower some single-element blends.
9375   if (NumV2Elements == 1)
9376     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9377                                                          Mask, Subtarget, DAG))
9378       return V;
9379
9380   if (SDValue BitBlend =
9381           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9382     return BitBlend;
9383
9384   // Check whether a compaction lowering can be done. This handles shuffles
9385   // which take every Nth element for some even N. See the helper function for
9386   // details.
9387   //
9388   // We special case these as they can be particularly efficiently handled with
9389   // the PACKUSB instruction on x86 and they show up in common patterns of
9390   // rearranging bytes to truncate wide elements.
9391   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9392     // NumEvenDrops is the power of two stride of the elements. Another way of
9393     // thinking about it is that we need to drop the even elements this many
9394     // times to get the original input.
9395     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9396
9397     // First we need to zero all the dropped bytes.
9398     assert(NumEvenDrops <= 3 &&
9399            "No support for dropping even elements more than 3 times.");
9400     // We use the mask type to pick which bytes are preserved based on how many
9401     // elements are dropped.
9402     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9403     SDValue ByteClearMask = DAG.getBitcast(
9404         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9405     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9406     if (!IsSingleInput)
9407       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9408
9409     // Now pack things back together.
9410     V1 = DAG.getBitcast(MVT::v8i16, V1);
9411     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9412     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9413     for (int i = 1; i < NumEvenDrops; ++i) {
9414       Result = DAG.getBitcast(MVT::v8i16, Result);
9415       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9416     }
9417
9418     return Result;
9419   }
9420
9421   // Handle multi-input cases by blending single-input shuffles.
9422   if (NumV2Elements > 0)
9423     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9424                                                       Mask, DAG);
9425
9426   // The fallback path for single-input shuffles widens this into two v8i16
9427   // vectors with unpacks, shuffles those, and then pulls them back together
9428   // with a pack.
9429   SDValue V = V1;
9430
9431   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9432   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9433   for (int i = 0; i < 16; ++i)
9434     if (Mask[i] >= 0)
9435       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9436
9437   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9438
9439   SDValue VLoHalf, VHiHalf;
9440   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9441   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9442   // i16s.
9443   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9444                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9445       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9446                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9447     // Use a mask to drop the high bytes.
9448     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9449     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9450                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9451
9452     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9453     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9454
9455     // Squash the masks to point directly into VLoHalf.
9456     for (int &M : LoBlendMask)
9457       if (M >= 0)
9458         M /= 2;
9459     for (int &M : HiBlendMask)
9460       if (M >= 0)
9461         M /= 2;
9462   } else {
9463     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9464     // VHiHalf so that we can blend them as i16s.
9465     VLoHalf = DAG.getBitcast(
9466         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9467     VHiHalf = DAG.getBitcast(
9468         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9469   }
9470
9471   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9472   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9473
9474   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9475 }
9476
9477 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9478 ///
9479 /// This routine breaks down the specific type of 128-bit shuffle and
9480 /// dispatches to the lowering routines accordingly.
9481 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9482                                         MVT VT, const X86Subtarget *Subtarget,
9483                                         SelectionDAG &DAG) {
9484   switch (VT.SimpleTy) {
9485   case MVT::v2i64:
9486     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9487   case MVT::v2f64:
9488     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9489   case MVT::v4i32:
9490     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9491   case MVT::v4f32:
9492     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9493   case MVT::v8i16:
9494     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9495   case MVT::v16i8:
9496     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9497
9498   default:
9499     llvm_unreachable("Unimplemented!");
9500   }
9501 }
9502
9503 /// \brief Helper function to test whether a shuffle mask could be
9504 /// simplified by widening the elements being shuffled.
9505 ///
9506 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9507 /// leaves it in an unspecified state.
9508 ///
9509 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9510 /// shuffle masks. The latter have the special property of a '-2' representing
9511 /// a zero-ed lane of a vector.
9512 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9513                                     SmallVectorImpl<int> &WidenedMask) {
9514   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9515     // If both elements are undef, its trivial.
9516     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9517       WidenedMask.push_back(SM_SentinelUndef);
9518       continue;
9519     }
9520
9521     // Check for an undef mask and a mask value properly aligned to fit with
9522     // a pair of values. If we find such a case, use the non-undef mask's value.
9523     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9524       WidenedMask.push_back(Mask[i + 1] / 2);
9525       continue;
9526     }
9527     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9528       WidenedMask.push_back(Mask[i] / 2);
9529       continue;
9530     }
9531
9532     // When zeroing, we need to spread the zeroing across both lanes to widen.
9533     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9534       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9535           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9536         WidenedMask.push_back(SM_SentinelZero);
9537         continue;
9538       }
9539       return false;
9540     }
9541
9542     // Finally check if the two mask values are adjacent and aligned with
9543     // a pair.
9544     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9545       WidenedMask.push_back(Mask[i] / 2);
9546       continue;
9547     }
9548
9549     // Otherwise we can't safely widen the elements used in this shuffle.
9550     return false;
9551   }
9552   assert(WidenedMask.size() == Mask.size() / 2 &&
9553          "Incorrect size of mask after widening the elements!");
9554
9555   return true;
9556 }
9557
9558 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9559 ///
9560 /// This routine just extracts two subvectors, shuffles them independently, and
9561 /// then concatenates them back together. This should work effectively with all
9562 /// AVX vector shuffle types.
9563 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9564                                           SDValue V2, ArrayRef<int> Mask,
9565                                           SelectionDAG &DAG) {
9566   assert(VT.getSizeInBits() >= 256 &&
9567          "Only for 256-bit or wider vector shuffles!");
9568   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9569   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9570
9571   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9572   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9573
9574   int NumElements = VT.getVectorNumElements();
9575   int SplitNumElements = NumElements / 2;
9576   MVT ScalarVT = VT.getScalarType();
9577   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9578
9579   // Rather than splitting build-vectors, just build two narrower build
9580   // vectors. This helps shuffling with splats and zeros.
9581   auto SplitVector = [&](SDValue V) {
9582     while (V.getOpcode() == ISD::BITCAST)
9583       V = V->getOperand(0);
9584
9585     MVT OrigVT = V.getSimpleValueType();
9586     int OrigNumElements = OrigVT.getVectorNumElements();
9587     int OrigSplitNumElements = OrigNumElements / 2;
9588     MVT OrigScalarVT = OrigVT.getScalarType();
9589     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9590
9591     SDValue LoV, HiV;
9592
9593     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9594     if (!BV) {
9595       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9596                         DAG.getIntPtrConstant(0, DL));
9597       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9598                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9599     } else {
9600
9601       SmallVector<SDValue, 16> LoOps, HiOps;
9602       for (int i = 0; i < OrigSplitNumElements; ++i) {
9603         LoOps.push_back(BV->getOperand(i));
9604         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9605       }
9606       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9607       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9608     }
9609     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9610                           DAG.getBitcast(SplitVT, HiV));
9611   };
9612
9613   SDValue LoV1, HiV1, LoV2, HiV2;
9614   std::tie(LoV1, HiV1) = SplitVector(V1);
9615   std::tie(LoV2, HiV2) = SplitVector(V2);
9616
9617   // Now create two 4-way blends of these half-width vectors.
9618   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9619     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9620     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9621     for (int i = 0; i < SplitNumElements; ++i) {
9622       int M = HalfMask[i];
9623       if (M >= NumElements) {
9624         if (M >= NumElements + SplitNumElements)
9625           UseHiV2 = true;
9626         else
9627           UseLoV2 = true;
9628         V2BlendMask.push_back(M - NumElements);
9629         V1BlendMask.push_back(-1);
9630         BlendMask.push_back(SplitNumElements + i);
9631       } else if (M >= 0) {
9632         if (M >= SplitNumElements)
9633           UseHiV1 = true;
9634         else
9635           UseLoV1 = true;
9636         V2BlendMask.push_back(-1);
9637         V1BlendMask.push_back(M);
9638         BlendMask.push_back(i);
9639       } else {
9640         V2BlendMask.push_back(-1);
9641         V1BlendMask.push_back(-1);
9642         BlendMask.push_back(-1);
9643       }
9644     }
9645
9646     // Because the lowering happens after all combining takes place, we need to
9647     // manually combine these blend masks as much as possible so that we create
9648     // a minimal number of high-level vector shuffle nodes.
9649
9650     // First try just blending the halves of V1 or V2.
9651     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9652       return DAG.getUNDEF(SplitVT);
9653     if (!UseLoV2 && !UseHiV2)
9654       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9655     if (!UseLoV1 && !UseHiV1)
9656       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9657
9658     SDValue V1Blend, V2Blend;
9659     if (UseLoV1 && UseHiV1) {
9660       V1Blend =
9661         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9662     } else {
9663       // We only use half of V1 so map the usage down into the final blend mask.
9664       V1Blend = UseLoV1 ? LoV1 : HiV1;
9665       for (int i = 0; i < SplitNumElements; ++i)
9666         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9667           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9668     }
9669     if (UseLoV2 && UseHiV2) {
9670       V2Blend =
9671         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9672     } else {
9673       // We only use half of V2 so map the usage down into the final blend mask.
9674       V2Blend = UseLoV2 ? LoV2 : HiV2;
9675       for (int i = 0; i < SplitNumElements; ++i)
9676         if (BlendMask[i] >= SplitNumElements)
9677           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9678     }
9679     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9680   };
9681   SDValue Lo = HalfBlend(LoMask);
9682   SDValue Hi = HalfBlend(HiMask);
9683   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9684 }
9685
9686 /// \brief Either split a vector in halves or decompose the shuffles and the
9687 /// blend.
9688 ///
9689 /// This is provided as a good fallback for many lowerings of non-single-input
9690 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9691 /// between splitting the shuffle into 128-bit components and stitching those
9692 /// back together vs. extracting the single-input shuffles and blending those
9693 /// results.
9694 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9695                                                 SDValue V2, ArrayRef<int> Mask,
9696                                                 SelectionDAG &DAG) {
9697   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9698                                             "lower single-input shuffles as it "
9699                                             "could then recurse on itself.");
9700   int Size = Mask.size();
9701
9702   // If this can be modeled as a broadcast of two elements followed by a blend,
9703   // prefer that lowering. This is especially important because broadcasts can
9704   // often fold with memory operands.
9705   auto DoBothBroadcast = [&] {
9706     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9707     for (int M : Mask)
9708       if (M >= Size) {
9709         if (V2BroadcastIdx == -1)
9710           V2BroadcastIdx = M - Size;
9711         else if (M - Size != V2BroadcastIdx)
9712           return false;
9713       } else if (M >= 0) {
9714         if (V1BroadcastIdx == -1)
9715           V1BroadcastIdx = M;
9716         else if (M != V1BroadcastIdx)
9717           return false;
9718       }
9719     return true;
9720   };
9721   if (DoBothBroadcast())
9722     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9723                                                       DAG);
9724
9725   // If the inputs all stem from a single 128-bit lane of each input, then we
9726   // split them rather than blending because the split will decompose to
9727   // unusually few instructions.
9728   int LaneCount = VT.getSizeInBits() / 128;
9729   int LaneSize = Size / LaneCount;
9730   SmallBitVector LaneInputs[2];
9731   LaneInputs[0].resize(LaneCount, false);
9732   LaneInputs[1].resize(LaneCount, false);
9733   for (int i = 0; i < Size; ++i)
9734     if (Mask[i] >= 0)
9735       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9736   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9737     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9738
9739   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9740   // that the decomposed single-input shuffles don't end up here.
9741   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9742 }
9743
9744 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9745 /// a permutation and blend of those lanes.
9746 ///
9747 /// This essentially blends the out-of-lane inputs to each lane into the lane
9748 /// from a permuted copy of the vector. This lowering strategy results in four
9749 /// instructions in the worst case for a single-input cross lane shuffle which
9750 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9751 /// of. Special cases for each particular shuffle pattern should be handled
9752 /// prior to trying this lowering.
9753 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9754                                                        SDValue V1, SDValue V2,
9755                                                        ArrayRef<int> Mask,
9756                                                        SelectionDAG &DAG) {
9757   // FIXME: This should probably be generalized for 512-bit vectors as well.
9758   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9759   int LaneSize = Mask.size() / 2;
9760
9761   // If there are only inputs from one 128-bit lane, splitting will in fact be
9762   // less expensive. The flags track whether the given lane contains an element
9763   // that crosses to another lane.
9764   bool LaneCrossing[2] = {false, false};
9765   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9766     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9767       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9768   if (!LaneCrossing[0] || !LaneCrossing[1])
9769     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9770
9771   if (isSingleInputShuffleMask(Mask)) {
9772     SmallVector<int, 32> FlippedBlendMask;
9773     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9774       FlippedBlendMask.push_back(
9775           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9776                                   ? Mask[i]
9777                                   : Mask[i] % LaneSize +
9778                                         (i / LaneSize) * LaneSize + Size));
9779
9780     // Flip the vector, and blend the results which should now be in-lane. The
9781     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9782     // 5 for the high source. The value 3 selects the high half of source 2 and
9783     // the value 2 selects the low half of source 2. We only use source 2 to
9784     // allow folding it into a memory operand.
9785     unsigned PERMMask = 3 | 2 << 4;
9786     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9787                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9788     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9789   }
9790
9791   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9792   // will be handled by the above logic and a blend of the results, much like
9793   // other patterns in AVX.
9794   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9795 }
9796
9797 /// \brief Handle lowering 2-lane 128-bit shuffles.
9798 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9799                                         SDValue V2, ArrayRef<int> Mask,
9800                                         const X86Subtarget *Subtarget,
9801                                         SelectionDAG &DAG) {
9802   // TODO: If minimizing size and one of the inputs is a zero vector and the
9803   // the zero vector has only one use, we could use a VPERM2X128 to save the
9804   // instruction bytes needed to explicitly generate the zero vector.
9805
9806   // Blends are faster and handle all the non-lane-crossing cases.
9807   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9808                                                 Subtarget, DAG))
9809     return Blend;
9810
9811   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9812   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9813
9814   // If either input operand is a zero vector, use VPERM2X128 because its mask
9815   // allows us to replace the zero input with an implicit zero.
9816   if (!IsV1Zero && !IsV2Zero) {
9817     // Check for patterns which can be matched with a single insert of a 128-bit
9818     // subvector.
9819     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9820     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9821       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9822                                    VT.getVectorNumElements() / 2);
9823       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9824                                 DAG.getIntPtrConstant(0, DL));
9825       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9826                                 OnlyUsesV1 ? V1 : V2,
9827                                 DAG.getIntPtrConstant(0, DL));
9828       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9829     }
9830   }
9831
9832   // Otherwise form a 128-bit permutation. After accounting for undefs,
9833   // convert the 64-bit shuffle mask selection values into 128-bit
9834   // selection bits by dividing the indexes by 2 and shifting into positions
9835   // defined by a vperm2*128 instruction's immediate control byte.
9836
9837   // The immediate permute control byte looks like this:
9838   //    [1:0] - select 128 bits from sources for low half of destination
9839   //    [2]   - ignore
9840   //    [3]   - zero low half of destination
9841   //    [5:4] - select 128 bits from sources for high half of destination
9842   //    [6]   - ignore
9843   //    [7]   - zero high half of destination
9844
9845   int MaskLO = Mask[0];
9846   if (MaskLO == SM_SentinelUndef)
9847     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9848
9849   int MaskHI = Mask[2];
9850   if (MaskHI == SM_SentinelUndef)
9851     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9852
9853   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9854
9855   // If either input is a zero vector, replace it with an undef input.
9856   // Shuffle mask values <  4 are selecting elements of V1.
9857   // Shuffle mask values >= 4 are selecting elements of V2.
9858   // Adjust each half of the permute mask by clearing the half that was
9859   // selecting the zero vector and setting the zero mask bit.
9860   if (IsV1Zero) {
9861     V1 = DAG.getUNDEF(VT);
9862     if (MaskLO < 4)
9863       PermMask = (PermMask & 0xf0) | 0x08;
9864     if (MaskHI < 4)
9865       PermMask = (PermMask & 0x0f) | 0x80;
9866   }
9867   if (IsV2Zero) {
9868     V2 = DAG.getUNDEF(VT);
9869     if (MaskLO >= 4)
9870       PermMask = (PermMask & 0xf0) | 0x08;
9871     if (MaskHI >= 4)
9872       PermMask = (PermMask & 0x0f) | 0x80;
9873   }
9874
9875   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9876                      DAG.getConstant(PermMask, DL, MVT::i8));
9877 }
9878
9879 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9880 /// shuffling each lane.
9881 ///
9882 /// This will only succeed when the result of fixing the 128-bit lanes results
9883 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9884 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9885 /// the lane crosses early and then use simpler shuffles within each lane.
9886 ///
9887 /// FIXME: It might be worthwhile at some point to support this without
9888 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9889 /// in x86 only floating point has interesting non-repeating shuffles, and even
9890 /// those are still *marginally* more expensive.
9891 static SDValue lowerVectorShuffleByMerging128BitLanes(
9892     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9893     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9894   assert(!isSingleInputShuffleMask(Mask) &&
9895          "This is only useful with multiple inputs.");
9896
9897   int Size = Mask.size();
9898   int LaneSize = 128 / VT.getScalarSizeInBits();
9899   int NumLanes = Size / LaneSize;
9900   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9901
9902   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9903   // check whether the in-128-bit lane shuffles share a repeating pattern.
9904   SmallVector<int, 4> Lanes;
9905   Lanes.resize(NumLanes, -1);
9906   SmallVector<int, 4> InLaneMask;
9907   InLaneMask.resize(LaneSize, -1);
9908   for (int i = 0; i < Size; ++i) {
9909     if (Mask[i] < 0)
9910       continue;
9911
9912     int j = i / LaneSize;
9913
9914     if (Lanes[j] < 0) {
9915       // First entry we've seen for this lane.
9916       Lanes[j] = Mask[i] / LaneSize;
9917     } else if (Lanes[j] != Mask[i] / LaneSize) {
9918       // This doesn't match the lane selected previously!
9919       return SDValue();
9920     }
9921
9922     // Check that within each lane we have a consistent shuffle mask.
9923     int k = i % LaneSize;
9924     if (InLaneMask[k] < 0) {
9925       InLaneMask[k] = Mask[i] % LaneSize;
9926     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9927       // This doesn't fit a repeating in-lane mask.
9928       return SDValue();
9929     }
9930   }
9931
9932   // First shuffle the lanes into place.
9933   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9934                                 VT.getSizeInBits() / 64);
9935   SmallVector<int, 8> LaneMask;
9936   LaneMask.resize(NumLanes * 2, -1);
9937   for (int i = 0; i < NumLanes; ++i)
9938     if (Lanes[i] >= 0) {
9939       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9940       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9941     }
9942
9943   V1 = DAG.getBitcast(LaneVT, V1);
9944   V2 = DAG.getBitcast(LaneVT, V2);
9945   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9946
9947   // Cast it back to the type we actually want.
9948   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9949
9950   // Now do a simple shuffle that isn't lane crossing.
9951   SmallVector<int, 8> NewMask;
9952   NewMask.resize(Size, -1);
9953   for (int i = 0; i < Size; ++i)
9954     if (Mask[i] >= 0)
9955       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9956   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9957          "Must not introduce lane crosses at this point!");
9958
9959   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9960 }
9961
9962 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9963 /// given mask.
9964 ///
9965 /// This returns true if the elements from a particular input are already in the
9966 /// slot required by the given mask and require no permutation.
9967 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9968   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9969   int Size = Mask.size();
9970   for (int i = 0; i < Size; ++i)
9971     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9972       return false;
9973
9974   return true;
9975 }
9976
9977 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9978                                             ArrayRef<int> Mask, SDValue V1,
9979                                             SDValue V2, SelectionDAG &DAG) {
9980
9981   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9982   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9983   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9984   int NumElts = VT.getVectorNumElements();
9985   bool ShufpdMask = true;
9986   bool CommutableMask = true;
9987   unsigned Immediate = 0;
9988   for (int i = 0; i < NumElts; ++i) {
9989     if (Mask[i] < 0)
9990       continue;
9991     int Val = (i & 6) + NumElts * (i & 1);
9992     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9993     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9994       ShufpdMask = false;
9995     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9996       CommutableMask = false;
9997     Immediate |= (Mask[i] % 2) << i;
9998   }
9999   if (ShufpdMask)
10000     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10001                        DAG.getConstant(Immediate, DL, MVT::i8));
10002   if (CommutableMask)
10003     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10004                        DAG.getConstant(Immediate, DL, MVT::i8));
10005   return SDValue();
10006 }
10007
10008 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10009 ///
10010 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10011 /// isn't available.
10012 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10013                                        const X86Subtarget *Subtarget,
10014                                        SelectionDAG &DAG) {
10015   SDLoc DL(Op);
10016   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10017   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10018   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10019   ArrayRef<int> Mask = SVOp->getMask();
10020   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10021
10022   SmallVector<int, 4> WidenedMask;
10023   if (canWidenShuffleElements(Mask, WidenedMask))
10024     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10025                                     DAG);
10026
10027   if (isSingleInputShuffleMask(Mask)) {
10028     // Check for being able to broadcast a single element.
10029     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10030                                                           Mask, Subtarget, DAG))
10031       return Broadcast;
10032
10033     // Use low duplicate instructions for masks that match their pattern.
10034     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10035       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10036
10037     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10038       // Non-half-crossing single input shuffles can be lowerid with an
10039       // interleaved permutation.
10040       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10041                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10042       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10043                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10044     }
10045
10046     // With AVX2 we have direct support for this permutation.
10047     if (Subtarget->hasAVX2())
10048       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10049                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10050
10051     // Otherwise, fall back.
10052     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10053                                                    DAG);
10054   }
10055
10056   // X86 has dedicated unpack instructions that can handle specific blend
10057   // operations: UNPCKH and UNPCKL.
10058   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10059     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10060   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10061     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10062   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10063     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10064   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10065     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10066
10067   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10068                                                 Subtarget, DAG))
10069     return Blend;
10070
10071   // Check if the blend happens to exactly fit that of SHUFPD.
10072   if (SDValue Op =
10073       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10074     return Op;
10075
10076   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10077   // shuffle. However, if we have AVX2 and either inputs are already in place,
10078   // we will be able to shuffle even across lanes the other input in a single
10079   // instruction so skip this pattern.
10080   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10081                                  isShuffleMaskInputInPlace(1, Mask))))
10082     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10083             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10084       return Result;
10085
10086   // If we have AVX2 then we always want to lower with a blend because an v4 we
10087   // can fully permute the elements.
10088   if (Subtarget->hasAVX2())
10089     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10090                                                       Mask, DAG);
10091
10092   // Otherwise fall back on generic lowering.
10093   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10094 }
10095
10096 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10097 ///
10098 /// This routine is only called when we have AVX2 and thus a reasonable
10099 /// instruction set for v4i64 shuffling..
10100 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10101                                        const X86Subtarget *Subtarget,
10102                                        SelectionDAG &DAG) {
10103   SDLoc DL(Op);
10104   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10105   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10106   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10107   ArrayRef<int> Mask = SVOp->getMask();
10108   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10109   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10110
10111   SmallVector<int, 4> WidenedMask;
10112   if (canWidenShuffleElements(Mask, WidenedMask))
10113     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10114                                     DAG);
10115
10116   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10117                                                 Subtarget, DAG))
10118     return Blend;
10119
10120   // Check for being able to broadcast a single element.
10121   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10122                                                         Mask, Subtarget, DAG))
10123     return Broadcast;
10124
10125   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10126   // use lower latency instructions that will operate on both 128-bit lanes.
10127   SmallVector<int, 2> RepeatedMask;
10128   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10129     if (isSingleInputShuffleMask(Mask)) {
10130       int PSHUFDMask[] = {-1, -1, -1, -1};
10131       for (int i = 0; i < 2; ++i)
10132         if (RepeatedMask[i] >= 0) {
10133           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10134           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10135         }
10136       return DAG.getBitcast(
10137           MVT::v4i64,
10138           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10139                       DAG.getBitcast(MVT::v8i32, V1),
10140                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10141     }
10142   }
10143
10144   // AVX2 provides a direct instruction for permuting a single input across
10145   // lanes.
10146   if (isSingleInputShuffleMask(Mask))
10147     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10148                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10149
10150   // Try to use shift instructions.
10151   if (SDValue Shift =
10152           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10153     return Shift;
10154
10155   // Use dedicated unpack instructions for masks that match their pattern.
10156   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10157     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10158   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10159     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10160   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10161     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10162   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10163     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10164
10165   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10166   // shuffle. However, if we have AVX2 and either inputs are already in place,
10167   // we will be able to shuffle even across lanes the other input in a single
10168   // instruction so skip this pattern.
10169   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10170                                  isShuffleMaskInputInPlace(1, Mask))))
10171     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10172             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10173       return Result;
10174
10175   // Otherwise fall back on generic blend lowering.
10176   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10177                                                     Mask, DAG);
10178 }
10179
10180 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10181 ///
10182 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10183 /// isn't available.
10184 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10185                                        const X86Subtarget *Subtarget,
10186                                        SelectionDAG &DAG) {
10187   SDLoc DL(Op);
10188   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10189   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10190   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10191   ArrayRef<int> Mask = SVOp->getMask();
10192   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10193
10194   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10195                                                 Subtarget, DAG))
10196     return Blend;
10197
10198   // Check for being able to broadcast a single element.
10199   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10200                                                         Mask, Subtarget, DAG))
10201     return Broadcast;
10202
10203   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10204   // options to efficiently lower the shuffle.
10205   SmallVector<int, 4> RepeatedMask;
10206   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10207     assert(RepeatedMask.size() == 4 &&
10208            "Repeated masks must be half the mask width!");
10209
10210     // Use even/odd duplicate instructions for masks that match their pattern.
10211     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10212       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10213     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10214       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10215
10216     if (isSingleInputShuffleMask(Mask))
10217       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10218                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10219
10220     // Use dedicated unpack instructions for masks that match their pattern.
10221     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10222       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10223     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10224       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10225     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10226       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10227     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10228       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10229
10230     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10231     // have already handled any direct blends. We also need to squash the
10232     // repeated mask into a simulated v4f32 mask.
10233     for (int i = 0; i < 4; ++i)
10234       if (RepeatedMask[i] >= 8)
10235         RepeatedMask[i] -= 4;
10236     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10237   }
10238
10239   // If we have a single input shuffle with different shuffle patterns in the
10240   // two 128-bit lanes use the variable mask to VPERMILPS.
10241   if (isSingleInputShuffleMask(Mask)) {
10242     SDValue VPermMask[8];
10243     for (int i = 0; i < 8; ++i)
10244       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10245                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10246     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10247       return DAG.getNode(
10248           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10249           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10250
10251     if (Subtarget->hasAVX2())
10252       return DAG.getNode(
10253           X86ISD::VPERMV, DL, MVT::v8f32,
10254           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10255                                                  MVT::v8i32, VPermMask)),
10256           V1);
10257
10258     // Otherwise, fall back.
10259     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10260                                                    DAG);
10261   }
10262
10263   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10264   // shuffle.
10265   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10266           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10267     return Result;
10268
10269   // If we have AVX2 then we always want to lower with a blend because at v8 we
10270   // can fully permute the elements.
10271   if (Subtarget->hasAVX2())
10272     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10273                                                       Mask, DAG);
10274
10275   // Otherwise fall back on generic lowering.
10276   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10277 }
10278
10279 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10280 ///
10281 /// This routine is only called when we have AVX2 and thus a reasonable
10282 /// instruction set for v8i32 shuffling..
10283 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10284                                        const X86Subtarget *Subtarget,
10285                                        SelectionDAG &DAG) {
10286   SDLoc DL(Op);
10287   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10288   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10289   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10290   ArrayRef<int> Mask = SVOp->getMask();
10291   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10292   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10293
10294   // Whenever we can lower this as a zext, that instruction is strictly faster
10295   // than any alternative. It also allows us to fold memory operands into the
10296   // shuffle in many cases.
10297   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10298                                                          Mask, Subtarget, DAG))
10299     return ZExt;
10300
10301   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10302                                                 Subtarget, DAG))
10303     return Blend;
10304
10305   // Check for being able to broadcast a single element.
10306   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10307                                                         Mask, Subtarget, DAG))
10308     return Broadcast;
10309
10310   // If the shuffle mask is repeated in each 128-bit lane we can use more
10311   // efficient instructions that mirror the shuffles across the two 128-bit
10312   // lanes.
10313   SmallVector<int, 4> RepeatedMask;
10314   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10315     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10316     if (isSingleInputShuffleMask(Mask))
10317       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10318                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10319
10320     // Use dedicated unpack instructions for masks that match their pattern.
10321     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10322       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10323     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10324       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10325     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10326       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10327     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10328       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10329   }
10330
10331   // Try to use shift instructions.
10332   if (SDValue Shift =
10333           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10334     return Shift;
10335
10336   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10337           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10338     return Rotate;
10339
10340   // If the shuffle patterns aren't repeated but it is a single input, directly
10341   // generate a cross-lane VPERMD instruction.
10342   if (isSingleInputShuffleMask(Mask)) {
10343     SDValue VPermMask[8];
10344     for (int i = 0; i < 8; ++i)
10345       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10346                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10347     return DAG.getNode(
10348         X86ISD::VPERMV, DL, MVT::v8i32,
10349         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10350   }
10351
10352   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10353   // shuffle.
10354   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10355           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10356     return Result;
10357
10358   // Otherwise fall back on generic blend lowering.
10359   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10360                                                     Mask, DAG);
10361 }
10362
10363 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10364 ///
10365 /// This routine is only called when we have AVX2 and thus a reasonable
10366 /// instruction set for v16i16 shuffling..
10367 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10368                                         const X86Subtarget *Subtarget,
10369                                         SelectionDAG &DAG) {
10370   SDLoc DL(Op);
10371   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10372   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10373   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10374   ArrayRef<int> Mask = SVOp->getMask();
10375   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10376   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10377
10378   // Whenever we can lower this as a zext, that instruction is strictly faster
10379   // than any alternative. It also allows us to fold memory operands into the
10380   // shuffle in many cases.
10381   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10382                                                          Mask, Subtarget, DAG))
10383     return ZExt;
10384
10385   // Check for being able to broadcast a single element.
10386   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10387                                                         Mask, Subtarget, DAG))
10388     return Broadcast;
10389
10390   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10391                                                 Subtarget, DAG))
10392     return Blend;
10393
10394   // Use dedicated unpack instructions for masks that match their pattern.
10395   if (isShuffleEquivalent(V1, V2, Mask,
10396                           {// First 128-bit lane:
10397                            0, 16, 1, 17, 2, 18, 3, 19,
10398                            // Second 128-bit lane:
10399                            8, 24, 9, 25, 10, 26, 11, 27}))
10400     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10401   if (isShuffleEquivalent(V1, V2, Mask,
10402                           {// First 128-bit lane:
10403                            4, 20, 5, 21, 6, 22, 7, 23,
10404                            // Second 128-bit lane:
10405                            12, 28, 13, 29, 14, 30, 15, 31}))
10406     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10407
10408   // Try to use shift instructions.
10409   if (SDValue Shift =
10410           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10411     return Shift;
10412
10413   // Try to use byte rotation instructions.
10414   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10415           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10416     return Rotate;
10417
10418   if (isSingleInputShuffleMask(Mask)) {
10419     // There are no generalized cross-lane shuffle operations available on i16
10420     // element types.
10421     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10422       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10423                                                      Mask, DAG);
10424
10425     SmallVector<int, 8> RepeatedMask;
10426     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10427       // As this is a single-input shuffle, the repeated mask should be
10428       // a strictly valid v8i16 mask that we can pass through to the v8i16
10429       // lowering to handle even the v16 case.
10430       return lowerV8I16GeneralSingleInputVectorShuffle(
10431           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10432     }
10433
10434     SDValue PSHUFBMask[32];
10435     for (int i = 0; i < 16; ++i) {
10436       if (Mask[i] == -1) {
10437         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10438         continue;
10439       }
10440
10441       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10442       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10443       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10444       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10445     }
10446     return DAG.getBitcast(MVT::v16i16,
10447                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10448                                       DAG.getBitcast(MVT::v32i8, V1),
10449                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10450                                                   MVT::v32i8, PSHUFBMask)));
10451   }
10452
10453   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10454   // shuffle.
10455   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10456           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10457     return Result;
10458
10459   // Otherwise fall back on generic lowering.
10460   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10461 }
10462
10463 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10464 ///
10465 /// This routine is only called when we have AVX2 and thus a reasonable
10466 /// instruction set for v32i8 shuffling..
10467 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10468                                        const X86Subtarget *Subtarget,
10469                                        SelectionDAG &DAG) {
10470   SDLoc DL(Op);
10471   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10472   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10473   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10474   ArrayRef<int> Mask = SVOp->getMask();
10475   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10476   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10477
10478   // Whenever we can lower this as a zext, that instruction is strictly faster
10479   // than any alternative. It also allows us to fold memory operands into the
10480   // shuffle in many cases.
10481   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10482                                                          Mask, Subtarget, DAG))
10483     return ZExt;
10484
10485   // Check for being able to broadcast a single element.
10486   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10487                                                         Mask, Subtarget, DAG))
10488     return Broadcast;
10489
10490   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10491                                                 Subtarget, DAG))
10492     return Blend;
10493
10494   // Use dedicated unpack instructions for masks that match their pattern.
10495   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10496   // 256-bit lanes.
10497   if (isShuffleEquivalent(
10498           V1, V2, Mask,
10499           {// First 128-bit lane:
10500            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10501            // Second 128-bit lane:
10502            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10503     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10504   if (isShuffleEquivalent(
10505           V1, V2, Mask,
10506           {// First 128-bit lane:
10507            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10508            // Second 128-bit lane:
10509            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10510     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10511
10512   // Try to use shift instructions.
10513   if (SDValue Shift =
10514           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10515     return Shift;
10516
10517   // Try to use byte rotation instructions.
10518   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10519           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10520     return Rotate;
10521
10522   if (isSingleInputShuffleMask(Mask)) {
10523     // There are no generalized cross-lane shuffle operations available on i8
10524     // element types.
10525     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10526       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10527                                                      Mask, DAG);
10528
10529     SDValue PSHUFBMask[32];
10530     for (int i = 0; i < 32; ++i)
10531       PSHUFBMask[i] =
10532           Mask[i] < 0
10533               ? DAG.getUNDEF(MVT::i8)
10534               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10535                                 MVT::i8);
10536
10537     return DAG.getNode(
10538         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10539         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10540   }
10541
10542   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10543   // shuffle.
10544   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10545           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10546     return Result;
10547
10548   // Otherwise fall back on generic lowering.
10549   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10550 }
10551
10552 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10553 ///
10554 /// This routine either breaks down the specific type of a 256-bit x86 vector
10555 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10556 /// together based on the available instructions.
10557 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10558                                         MVT VT, const X86Subtarget *Subtarget,
10559                                         SelectionDAG &DAG) {
10560   SDLoc DL(Op);
10561   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10562   ArrayRef<int> Mask = SVOp->getMask();
10563
10564   // If we have a single input to the zero element, insert that into V1 if we
10565   // can do so cheaply.
10566   int NumElts = VT.getVectorNumElements();
10567   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10568     return M >= NumElts;
10569   });
10570
10571   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10572     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10573                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10574       return Insertion;
10575
10576   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10577   // check for those subtargets here and avoid much of the subtarget querying in
10578   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10579   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10580   // floating point types there eventually, just immediately cast everything to
10581   // a float and operate entirely in that domain.
10582   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10583     int ElementBits = VT.getScalarSizeInBits();
10584     if (ElementBits < 32)
10585       // No floating point type available, decompose into 128-bit vectors.
10586       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10587
10588     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10589                                 VT.getVectorNumElements());
10590     V1 = DAG.getBitcast(FpVT, V1);
10591     V2 = DAG.getBitcast(FpVT, V2);
10592     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10593   }
10594
10595   switch (VT.SimpleTy) {
10596   case MVT::v4f64:
10597     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10598   case MVT::v4i64:
10599     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10600   case MVT::v8f32:
10601     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10602   case MVT::v8i32:
10603     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10604   case MVT::v16i16:
10605     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10606   case MVT::v32i8:
10607     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10608
10609   default:
10610     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10611   }
10612 }
10613
10614 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10615                                            ArrayRef<int> Mask, SDValue V1,
10616                                            SDValue V2, SelectionDAG &DAG) {
10617
10618   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10619
10620   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10621   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10622
10623   SmallVector<SDValue, 32>  VPermMask;
10624   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10625     VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10626                         DAG.getConstant(Mask[i], DL, MaskEltVT));
10627   SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10628                                  VPermMask);
10629   if (isSingleInputShuffleMask(Mask))
10630     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10631
10632   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10633 }
10634
10635 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10636 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10637                                        const X86Subtarget *Subtarget,
10638                                        SelectionDAG &DAG) {
10639   SDLoc DL(Op);
10640   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10641   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10642   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10643   ArrayRef<int> Mask = SVOp->getMask();
10644   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10645
10646   if (SDValue Unpck =
10647           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10648     return Unpck;
10649
10650   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10651 }
10652
10653 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10654 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10655                                        const X86Subtarget *Subtarget,
10656                                        SelectionDAG &DAG) {
10657   SDLoc DL(Op);
10658   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10659   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10660   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10661   ArrayRef<int> Mask = SVOp->getMask();
10662   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10663
10664   if (SDValue Unpck =
10665           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10666     return Unpck;
10667
10668   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10669 }
10670
10671 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10672 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10673                                        const X86Subtarget *Subtarget,
10674                                        SelectionDAG &DAG) {
10675   SDLoc DL(Op);
10676   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10677   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10678   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10679   ArrayRef<int> Mask = SVOp->getMask();
10680   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10681
10682   if (SDValue Unpck =
10683           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10684     return Unpck;
10685
10686   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10687 }
10688
10689 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10690 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10691                                        const X86Subtarget *Subtarget,
10692                                        SelectionDAG &DAG) {
10693   SDLoc DL(Op);
10694   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10695   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10696   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10697   ArrayRef<int> Mask = SVOp->getMask();
10698   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10699
10700   if (SDValue Unpck =
10701           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10702     return Unpck;
10703
10704   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10705 }
10706
10707 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10708 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10709                                         const X86Subtarget *Subtarget,
10710                                         SelectionDAG &DAG) {
10711   SDLoc DL(Op);
10712   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10713   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10714   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10715   ArrayRef<int> Mask = SVOp->getMask();
10716   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10717   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10718
10719   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10720 }
10721
10722 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10723 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10724                                        const X86Subtarget *Subtarget,
10725                                        SelectionDAG &DAG) {
10726   SDLoc DL(Op);
10727   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10728   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10729   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10730   ArrayRef<int> Mask = SVOp->getMask();
10731   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10732   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10733
10734   // FIXME: Implement direct support for this type!
10735   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10736 }
10737
10738 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10739 ///
10740 /// This routine either breaks down the specific type of a 512-bit x86 vector
10741 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10742 /// together based on the available instructions.
10743 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10744                                         MVT VT, const X86Subtarget *Subtarget,
10745                                         SelectionDAG &DAG) {
10746   SDLoc DL(Op);
10747   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10748   ArrayRef<int> Mask = SVOp->getMask();
10749   assert(Subtarget->hasAVX512() &&
10750          "Cannot lower 512-bit vectors w/ basic ISA!");
10751
10752   // Check for being able to broadcast a single element.
10753   if (SDValue Broadcast =
10754           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10755     return Broadcast;
10756
10757   // Dispatch to each element type for lowering. If we don't have supprot for
10758   // specific element type shuffles at 512 bits, immediately split them and
10759   // lower them. Each lowering routine of a given type is allowed to assume that
10760   // the requisite ISA extensions for that element type are available.
10761   switch (VT.SimpleTy) {
10762   case MVT::v8f64:
10763     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10764   case MVT::v16f32:
10765     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10766   case MVT::v8i64:
10767     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10768   case MVT::v16i32:
10769     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10770   case MVT::v32i16:
10771     if (Subtarget->hasBWI())
10772       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10773     break;
10774   case MVT::v64i8:
10775     if (Subtarget->hasBWI())
10776       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10777     break;
10778
10779   default:
10780     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10781   }
10782
10783   // Otherwise fall back on splitting.
10784   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10785 }
10786
10787 /// \brief Top-level lowering for x86 vector shuffles.
10788 ///
10789 /// This handles decomposition, canonicalization, and lowering of all x86
10790 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10791 /// above in helper routines. The canonicalization attempts to widen shuffles
10792 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10793 /// s.t. only one of the two inputs needs to be tested, etc.
10794 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10795                                   SelectionDAG &DAG) {
10796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10797   ArrayRef<int> Mask = SVOp->getMask();
10798   SDValue V1 = Op.getOperand(0);
10799   SDValue V2 = Op.getOperand(1);
10800   MVT VT = Op.getSimpleValueType();
10801   int NumElements = VT.getVectorNumElements();
10802   SDLoc dl(Op);
10803
10804   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10805
10806   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10807   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10808   if (V1IsUndef && V2IsUndef)
10809     return DAG.getUNDEF(VT);
10810
10811   // When we create a shuffle node we put the UNDEF node to second operand,
10812   // but in some cases the first operand may be transformed to UNDEF.
10813   // In this case we should just commute the node.
10814   if (V1IsUndef)
10815     return DAG.getCommutedVectorShuffle(*SVOp);
10816
10817   // Check for non-undef masks pointing at an undef vector and make the masks
10818   // undef as well. This makes it easier to match the shuffle based solely on
10819   // the mask.
10820   if (V2IsUndef)
10821     for (int M : Mask)
10822       if (M >= NumElements) {
10823         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10824         for (int &M : NewMask)
10825           if (M >= NumElements)
10826             M = -1;
10827         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10828       }
10829
10830   // We actually see shuffles that are entirely re-arrangements of a set of
10831   // zero inputs. This mostly happens while decomposing complex shuffles into
10832   // simple ones. Directly lower these as a buildvector of zeros.
10833   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10834   if (Zeroable.all())
10835     return getZeroVector(VT, Subtarget, DAG, dl);
10836
10837   // Try to collapse shuffles into using a vector type with fewer elements but
10838   // wider element types. We cap this to not form integers or floating point
10839   // elements wider than 64 bits, but it might be interesting to form i128
10840   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10841   SmallVector<int, 16> WidenedMask;
10842   if (VT.getScalarSizeInBits() < 64 &&
10843       canWidenShuffleElements(Mask, WidenedMask)) {
10844     MVT NewEltVT = VT.isFloatingPoint()
10845                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10846                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10847     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10848     // Make sure that the new vector type is legal. For example, v2f64 isn't
10849     // legal on SSE1.
10850     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10851       V1 = DAG.getBitcast(NewVT, V1);
10852       V2 = DAG.getBitcast(NewVT, V2);
10853       return DAG.getBitcast(
10854           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10855     }
10856   }
10857
10858   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10859   for (int M : SVOp->getMask())
10860     if (M < 0)
10861       ++NumUndefElements;
10862     else if (M < NumElements)
10863       ++NumV1Elements;
10864     else
10865       ++NumV2Elements;
10866
10867   // Commute the shuffle as needed such that more elements come from V1 than
10868   // V2. This allows us to match the shuffle pattern strictly on how many
10869   // elements come from V1 without handling the symmetric cases.
10870   if (NumV2Elements > NumV1Elements)
10871     return DAG.getCommutedVectorShuffle(*SVOp);
10872
10873   // When the number of V1 and V2 elements are the same, try to minimize the
10874   // number of uses of V2 in the low half of the vector. When that is tied,
10875   // ensure that the sum of indices for V1 is equal to or lower than the sum
10876   // indices for V2. When those are equal, try to ensure that the number of odd
10877   // indices for V1 is lower than the number of odd indices for V2.
10878   if (NumV1Elements == NumV2Elements) {
10879     int LowV1Elements = 0, LowV2Elements = 0;
10880     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10881       if (M >= NumElements)
10882         ++LowV2Elements;
10883       else if (M >= 0)
10884         ++LowV1Elements;
10885     if (LowV2Elements > LowV1Elements) {
10886       return DAG.getCommutedVectorShuffle(*SVOp);
10887     } else if (LowV2Elements == LowV1Elements) {
10888       int SumV1Indices = 0, SumV2Indices = 0;
10889       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10890         if (SVOp->getMask()[i] >= NumElements)
10891           SumV2Indices += i;
10892         else if (SVOp->getMask()[i] >= 0)
10893           SumV1Indices += i;
10894       if (SumV2Indices < SumV1Indices) {
10895         return DAG.getCommutedVectorShuffle(*SVOp);
10896       } else if (SumV2Indices == SumV1Indices) {
10897         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10898         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10899           if (SVOp->getMask()[i] >= NumElements)
10900             NumV2OddIndices += i % 2;
10901           else if (SVOp->getMask()[i] >= 0)
10902             NumV1OddIndices += i % 2;
10903         if (NumV2OddIndices < NumV1OddIndices)
10904           return DAG.getCommutedVectorShuffle(*SVOp);
10905       }
10906     }
10907   }
10908
10909   // For each vector width, delegate to a specialized lowering routine.
10910   if (VT.getSizeInBits() == 128)
10911     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10912
10913   if (VT.getSizeInBits() == 256)
10914     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10915
10916   if (VT.getSizeInBits() == 512)
10917     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10918
10919   llvm_unreachable("Unimplemented!");
10920 }
10921
10922 // This function assumes its argument is a BUILD_VECTOR of constants or
10923 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10924 // true.
10925 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10926                                     unsigned &MaskValue) {
10927   MaskValue = 0;
10928   unsigned NumElems = BuildVector->getNumOperands();
10929   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10930   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10931   unsigned NumElemsInLane = NumElems / NumLanes;
10932
10933   // Blend for v16i16 should be symmetric for the both lanes.
10934   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10935     SDValue EltCond = BuildVector->getOperand(i);
10936     SDValue SndLaneEltCond =
10937         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10938
10939     int Lane1Cond = -1, Lane2Cond = -1;
10940     if (isa<ConstantSDNode>(EltCond))
10941       Lane1Cond = !isZero(EltCond);
10942     if (isa<ConstantSDNode>(SndLaneEltCond))
10943       Lane2Cond = !isZero(SndLaneEltCond);
10944
10945     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10946       // Lane1Cond != 0, means we want the first argument.
10947       // Lane1Cond == 0, means we want the second argument.
10948       // The encoding of this argument is 0 for the first argument, 1
10949       // for the second. Therefore, invert the condition.
10950       MaskValue |= !Lane1Cond << i;
10951     else if (Lane1Cond < 0)
10952       MaskValue |= !Lane2Cond << i;
10953     else
10954       return false;
10955   }
10956   return true;
10957 }
10958
10959 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10960 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10961                                            const X86Subtarget *Subtarget,
10962                                            SelectionDAG &DAG) {
10963   SDValue Cond = Op.getOperand(0);
10964   SDValue LHS = Op.getOperand(1);
10965   SDValue RHS = Op.getOperand(2);
10966   SDLoc dl(Op);
10967   MVT VT = Op.getSimpleValueType();
10968
10969   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10970     return SDValue();
10971   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10972
10973   // Only non-legal VSELECTs reach this lowering, convert those into generic
10974   // shuffles and re-use the shuffle lowering path for blends.
10975   SmallVector<int, 32> Mask;
10976   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10977     SDValue CondElt = CondBV->getOperand(i);
10978     Mask.push_back(
10979         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10980   }
10981   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10982 }
10983
10984 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10985   // A vselect where all conditions and data are constants can be optimized into
10986   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10987   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10988       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10989       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10990     return SDValue();
10991
10992   // Try to lower this to a blend-style vector shuffle. This can handle all
10993   // constant condition cases.
10994   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10995     return BlendOp;
10996
10997   // Variable blends are only legal from SSE4.1 onward.
10998   if (!Subtarget->hasSSE41())
10999     return SDValue();
11000
11001   // Only some types will be legal on some subtargets. If we can emit a legal
11002   // VSELECT-matching blend, return Op, and but if we need to expand, return
11003   // a null value.
11004   switch (Op.getSimpleValueType().SimpleTy) {
11005   default:
11006     // Most of the vector types have blends past SSE4.1.
11007     return Op;
11008
11009   case MVT::v32i8:
11010     // The byte blends for AVX vectors were introduced only in AVX2.
11011     if (Subtarget->hasAVX2())
11012       return Op;
11013
11014     return SDValue();
11015
11016   case MVT::v8i16:
11017   case MVT::v16i16:
11018     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11019     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11020       return Op;
11021
11022     // FIXME: We should custom lower this by fixing the condition and using i8
11023     // blends.
11024     return SDValue();
11025   }
11026 }
11027
11028 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11029   MVT VT = Op.getSimpleValueType();
11030   SDLoc dl(Op);
11031
11032   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11033     return SDValue();
11034
11035   if (VT.getSizeInBits() == 8) {
11036     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11037                                   Op.getOperand(0), Op.getOperand(1));
11038     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11039                                   DAG.getValueType(VT));
11040     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11041   }
11042
11043   if (VT.getSizeInBits() == 16) {
11044     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11045     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11046     if (Idx == 0)
11047       return DAG.getNode(
11048           ISD::TRUNCATE, dl, MVT::i16,
11049           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11050                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11051                       Op.getOperand(1)));
11052     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11053                                   Op.getOperand(0), Op.getOperand(1));
11054     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11055                                   DAG.getValueType(VT));
11056     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11057   }
11058
11059   if (VT == MVT::f32) {
11060     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11061     // the result back to FR32 register. It's only worth matching if the
11062     // result has a single use which is a store or a bitcast to i32.  And in
11063     // the case of a store, it's not worth it if the index is a constant 0,
11064     // because a MOVSSmr can be used instead, which is smaller and faster.
11065     if (!Op.hasOneUse())
11066       return SDValue();
11067     SDNode *User = *Op.getNode()->use_begin();
11068     if ((User->getOpcode() != ISD::STORE ||
11069          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11070           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11071         (User->getOpcode() != ISD::BITCAST ||
11072          User->getValueType(0) != MVT::i32))
11073       return SDValue();
11074     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11075                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11076                                   Op.getOperand(1));
11077     return DAG.getBitcast(MVT::f32, Extract);
11078   }
11079
11080   if (VT == MVT::i32 || VT == MVT::i64) {
11081     // ExtractPS/pextrq works with constant index.
11082     if (isa<ConstantSDNode>(Op.getOperand(1)))
11083       return Op;
11084   }
11085   return SDValue();
11086 }
11087
11088 /// Extract one bit from mask vector, like v16i1 or v8i1.
11089 /// AVX-512 feature.
11090 SDValue
11091 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11092   SDValue Vec = Op.getOperand(0);
11093   SDLoc dl(Vec);
11094   MVT VecVT = Vec.getSimpleValueType();
11095   SDValue Idx = Op.getOperand(1);
11096   MVT EltVT = Op.getSimpleValueType();
11097
11098   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11099   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11100          "Unexpected vector type in ExtractBitFromMaskVector");
11101
11102   // variable index can't be handled in mask registers,
11103   // extend vector to VR512
11104   if (!isa<ConstantSDNode>(Idx)) {
11105     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11106     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11107     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11108                               ExtVT.getVectorElementType(), Ext, Idx);
11109     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11110   }
11111
11112   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11113   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11114   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11115     rc = getRegClassFor(MVT::v16i1);
11116   unsigned MaxSift = rc->getSize()*8 - 1;
11117   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11118                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11119   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11120                     DAG.getConstant(MaxSift, dl, MVT::i8));
11121   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11122                        DAG.getIntPtrConstant(0, dl));
11123 }
11124
11125 SDValue
11126 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11127                                            SelectionDAG &DAG) const {
11128   SDLoc dl(Op);
11129   SDValue Vec = Op.getOperand(0);
11130   MVT VecVT = Vec.getSimpleValueType();
11131   SDValue Idx = Op.getOperand(1);
11132
11133   if (Op.getSimpleValueType() == MVT::i1)
11134     return ExtractBitFromMaskVector(Op, DAG);
11135
11136   if (!isa<ConstantSDNode>(Idx)) {
11137     if (VecVT.is512BitVector() ||
11138         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11139          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11140
11141       MVT MaskEltVT =
11142         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11143       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11144                                     MaskEltVT.getSizeInBits());
11145
11146       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11147       auto PtrVT = getPointerTy(DAG.getDataLayout());
11148       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11149                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11150                                  DAG.getConstant(0, dl, PtrVT));
11151       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11152       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11153                          DAG.getConstant(0, dl, PtrVT));
11154     }
11155     return SDValue();
11156   }
11157
11158   // If this is a 256-bit vector result, first extract the 128-bit vector and
11159   // then extract the element from the 128-bit vector.
11160   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11161
11162     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11163     // Get the 128-bit vector.
11164     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11165     MVT EltVT = VecVT.getVectorElementType();
11166
11167     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11168
11169     //if (IdxVal >= NumElems/2)
11170     //  IdxVal -= NumElems/2;
11171     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11172     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11173                        DAG.getConstant(IdxVal, dl, MVT::i32));
11174   }
11175
11176   assert(VecVT.is128BitVector() && "Unexpected vector length");
11177
11178   if (Subtarget->hasSSE41())
11179     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11180       return Res;
11181
11182   MVT VT = Op.getSimpleValueType();
11183   // TODO: handle v16i8.
11184   if (VT.getSizeInBits() == 16) {
11185     SDValue Vec = Op.getOperand(0);
11186     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11187     if (Idx == 0)
11188       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11189                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11190                                      DAG.getBitcast(MVT::v4i32, Vec),
11191                                      Op.getOperand(1)));
11192     // Transform it so it match pextrw which produces a 32-bit result.
11193     MVT EltVT = MVT::i32;
11194     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11195                                   Op.getOperand(0), Op.getOperand(1));
11196     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11197                                   DAG.getValueType(VT));
11198     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11199   }
11200
11201   if (VT.getSizeInBits() == 32) {
11202     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11203     if (Idx == 0)
11204       return Op;
11205
11206     // SHUFPS the element to the lowest double word, then movss.
11207     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11208     MVT VVT = Op.getOperand(0).getSimpleValueType();
11209     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11210                                        DAG.getUNDEF(VVT), Mask);
11211     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11212                        DAG.getIntPtrConstant(0, dl));
11213   }
11214
11215   if (VT.getSizeInBits() == 64) {
11216     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11217     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11218     //        to match extract_elt for f64.
11219     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11220     if (Idx == 0)
11221       return Op;
11222
11223     // UNPCKHPD the element to the lowest double word, then movsd.
11224     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11225     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11226     int Mask[2] = { 1, -1 };
11227     MVT VVT = Op.getOperand(0).getSimpleValueType();
11228     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11229                                        DAG.getUNDEF(VVT), Mask);
11230     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11231                        DAG.getIntPtrConstant(0, dl));
11232   }
11233
11234   return SDValue();
11235 }
11236
11237 /// Insert one bit to mask vector, like v16i1 or v8i1.
11238 /// AVX-512 feature.
11239 SDValue
11240 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11241   SDLoc dl(Op);
11242   SDValue Vec = Op.getOperand(0);
11243   SDValue Elt = Op.getOperand(1);
11244   SDValue Idx = Op.getOperand(2);
11245   MVT VecVT = Vec.getSimpleValueType();
11246
11247   if (!isa<ConstantSDNode>(Idx)) {
11248     // Non constant index. Extend source and destination,
11249     // insert element and then truncate the result.
11250     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11251     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11252     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11253       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11254       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11255     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11256   }
11257
11258   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11259   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11260   if (IdxVal)
11261     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11262                            DAG.getConstant(IdxVal, dl, MVT::i8));
11263   if (Vec.getOpcode() == ISD::UNDEF)
11264     return EltInVec;
11265   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11266 }
11267
11268 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11269                                                   SelectionDAG &DAG) const {
11270   MVT VT = Op.getSimpleValueType();
11271   MVT EltVT = VT.getVectorElementType();
11272
11273   if (EltVT == MVT::i1)
11274     return InsertBitToMaskVector(Op, DAG);
11275
11276   SDLoc dl(Op);
11277   SDValue N0 = Op.getOperand(0);
11278   SDValue N1 = Op.getOperand(1);
11279   SDValue N2 = Op.getOperand(2);
11280   if (!isa<ConstantSDNode>(N2))
11281     return SDValue();
11282   auto *N2C = cast<ConstantSDNode>(N2);
11283   unsigned IdxVal = N2C->getZExtValue();
11284
11285   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11286   // into that, and then insert the subvector back into the result.
11287   if (VT.is256BitVector() || VT.is512BitVector()) {
11288     // With a 256-bit vector, we can insert into the zero element efficiently
11289     // using a blend if we have AVX or AVX2 and the right data type.
11290     if (VT.is256BitVector() && IdxVal == 0) {
11291       // TODO: It is worthwhile to cast integer to floating point and back
11292       // and incur a domain crossing penalty if that's what we'll end up
11293       // doing anyway after extracting to a 128-bit vector.
11294       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11295           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11296         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11297         N2 = DAG.getIntPtrConstant(1, dl);
11298         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11299       }
11300     }
11301
11302     // Get the desired 128-bit vector chunk.
11303     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11304
11305     // Insert the element into the desired chunk.
11306     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11307     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11308
11309     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11310                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11311
11312     // Insert the changed part back into the bigger vector
11313     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11314   }
11315   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11316
11317   if (Subtarget->hasSSE41()) {
11318     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11319       unsigned Opc;
11320       if (VT == MVT::v8i16) {
11321         Opc = X86ISD::PINSRW;
11322       } else {
11323         assert(VT == MVT::v16i8);
11324         Opc = X86ISD::PINSRB;
11325       }
11326
11327       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11328       // argument.
11329       if (N1.getValueType() != MVT::i32)
11330         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11331       if (N2.getValueType() != MVT::i32)
11332         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11333       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11334     }
11335
11336     if (EltVT == MVT::f32) {
11337       // Bits [7:6] of the constant are the source select. This will always be
11338       //   zero here. The DAG Combiner may combine an extract_elt index into
11339       //   these bits. For example (insert (extract, 3), 2) could be matched by
11340       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11341       // Bits [5:4] of the constant are the destination select. This is the
11342       //   value of the incoming immediate.
11343       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11344       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11345
11346       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11347       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11348         // If this is an insertion of 32-bits into the low 32-bits of
11349         // a vector, we prefer to generate a blend with immediate rather
11350         // than an insertps. Blends are simpler operations in hardware and so
11351         // will always have equal or better performance than insertps.
11352         // But if optimizing for size and there's a load folding opportunity,
11353         // generate insertps because blendps does not have a 32-bit memory
11354         // operand form.
11355         N2 = DAG.getIntPtrConstant(1, dl);
11356         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11357         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11358       }
11359       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11360       // Create this as a scalar to vector..
11361       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11362       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11363     }
11364
11365     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11366       // PINSR* works with constant index.
11367       return Op;
11368     }
11369   }
11370
11371   if (EltVT == MVT::i8)
11372     return SDValue();
11373
11374   if (EltVT.getSizeInBits() == 16) {
11375     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11376     // as its second argument.
11377     if (N1.getValueType() != MVT::i32)
11378       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11379     if (N2.getValueType() != MVT::i32)
11380       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11381     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11382   }
11383   return SDValue();
11384 }
11385
11386 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11387   SDLoc dl(Op);
11388   MVT OpVT = Op.getSimpleValueType();
11389
11390   // If this is a 256-bit vector result, first insert into a 128-bit
11391   // vector and then insert into the 256-bit vector.
11392   if (!OpVT.is128BitVector()) {
11393     // Insert into a 128-bit vector.
11394     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11395     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11396                                  OpVT.getVectorNumElements() / SizeFactor);
11397
11398     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11399
11400     // Insert the 128-bit vector.
11401     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11402   }
11403
11404   if (OpVT == MVT::v1i64 &&
11405       Op.getOperand(0).getValueType() == MVT::i64)
11406     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11407
11408   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11409   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11410   return DAG.getBitcast(
11411       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11412 }
11413
11414 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11415 // a simple subregister reference or explicit instructions to grab
11416 // upper bits of a vector.
11417 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11418                                       SelectionDAG &DAG) {
11419   SDLoc dl(Op);
11420   SDValue In =  Op.getOperand(0);
11421   SDValue Idx = Op.getOperand(1);
11422   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11423   MVT ResVT   = Op.getSimpleValueType();
11424   MVT InVT    = In.getSimpleValueType();
11425
11426   if (Subtarget->hasFp256()) {
11427     if (ResVT.is128BitVector() &&
11428         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11429         isa<ConstantSDNode>(Idx)) {
11430       return Extract128BitVector(In, IdxVal, DAG, dl);
11431     }
11432     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11433         isa<ConstantSDNode>(Idx)) {
11434       return Extract256BitVector(In, IdxVal, DAG, dl);
11435     }
11436   }
11437   return SDValue();
11438 }
11439
11440 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11441 // simple superregister reference or explicit instructions to insert
11442 // the upper bits of a vector.
11443 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11444                                      SelectionDAG &DAG) {
11445   if (!Subtarget->hasAVX())
11446     return SDValue();
11447
11448   SDLoc dl(Op);
11449   SDValue Vec = Op.getOperand(0);
11450   SDValue SubVec = Op.getOperand(1);
11451   SDValue Idx = Op.getOperand(2);
11452
11453   if (!isa<ConstantSDNode>(Idx))
11454     return SDValue();
11455
11456   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11457   MVT OpVT = Op.getSimpleValueType();
11458   MVT SubVecVT = SubVec.getSimpleValueType();
11459
11460   // Fold two 16-byte subvector loads into one 32-byte load:
11461   // (insert_subvector (insert_subvector undef, (load addr), 0),
11462   //                   (load addr + 16), Elts/2)
11463   // --> load32 addr
11464   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11465       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11466       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11467     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11468     if (Idx2 && Idx2->getZExtValue() == 0) {
11469       SDValue SubVec2 = Vec.getOperand(1);
11470       // If needed, look through a bitcast to get to the load.
11471       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11472         SubVec2 = SubVec2.getOperand(0);
11473
11474       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11475         bool Fast;
11476         unsigned Alignment = FirstLd->getAlignment();
11477         unsigned AS = FirstLd->getAddressSpace();
11478         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11479         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11480                                     OpVT, AS, Alignment, &Fast) && Fast) {
11481           SDValue Ops[] = { SubVec2, SubVec };
11482           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11483             return Ld;
11484         }
11485       }
11486     }
11487   }
11488
11489   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11490       SubVecVT.is128BitVector())
11491     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11492
11493   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11494     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11495
11496   if (OpVT.getVectorElementType() == MVT::i1) {
11497     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11498       return Op;
11499     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11500     SDValue Undef = DAG.getUNDEF(OpVT);
11501     unsigned NumElems = OpVT.getVectorNumElements();
11502     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11503
11504     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11505       // Zero upper bits of the Vec
11506       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11507       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11508
11509       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11510                                  SubVec, ZeroIdx);
11511       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11512       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11513     }
11514     if (IdxVal == 0) {
11515       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11516                                  SubVec, ZeroIdx);
11517       // Zero upper bits of the Vec2
11518       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11519       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11520       // Zero lower bits of the Vec
11521       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11522       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11523       // Merge them together
11524       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11525     }
11526   }
11527   return SDValue();
11528 }
11529
11530 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11531 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11532 // one of the above mentioned nodes. It has to be wrapped because otherwise
11533 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11534 // be used to form addressing mode. These wrapped nodes will be selected
11535 // into MOV32ri.
11536 SDValue
11537 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11538   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11539
11540   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11541   // global base reg.
11542   unsigned char OpFlag = 0;
11543   unsigned WrapperKind = X86ISD::Wrapper;
11544   CodeModel::Model M = DAG.getTarget().getCodeModel();
11545
11546   if (Subtarget->isPICStyleRIPRel() &&
11547       (M == CodeModel::Small || M == CodeModel::Kernel))
11548     WrapperKind = X86ISD::WrapperRIP;
11549   else if (Subtarget->isPICStyleGOT())
11550     OpFlag = X86II::MO_GOTOFF;
11551   else if (Subtarget->isPICStyleStubPIC())
11552     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11553
11554   auto PtrVT = getPointerTy(DAG.getDataLayout());
11555   SDValue Result = DAG.getTargetConstantPool(
11556       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11557   SDLoc DL(CP);
11558   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11559   // With PIC, the address is actually $g + Offset.
11560   if (OpFlag) {
11561     Result =
11562         DAG.getNode(ISD::ADD, DL, PtrVT,
11563                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11564   }
11565
11566   return Result;
11567 }
11568
11569 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11570   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11571
11572   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11573   // global base reg.
11574   unsigned char OpFlag = 0;
11575   unsigned WrapperKind = X86ISD::Wrapper;
11576   CodeModel::Model M = DAG.getTarget().getCodeModel();
11577
11578   if (Subtarget->isPICStyleRIPRel() &&
11579       (M == CodeModel::Small || M == CodeModel::Kernel))
11580     WrapperKind = X86ISD::WrapperRIP;
11581   else if (Subtarget->isPICStyleGOT())
11582     OpFlag = X86II::MO_GOTOFF;
11583   else if (Subtarget->isPICStyleStubPIC())
11584     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11585
11586   auto PtrVT = getPointerTy(DAG.getDataLayout());
11587   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11588   SDLoc DL(JT);
11589   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11590
11591   // With PIC, the address is actually $g + Offset.
11592   if (OpFlag)
11593     Result =
11594         DAG.getNode(ISD::ADD, DL, PtrVT,
11595                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11596
11597   return Result;
11598 }
11599
11600 SDValue
11601 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11602   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11603
11604   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11605   // global base reg.
11606   unsigned char OpFlag = 0;
11607   unsigned WrapperKind = X86ISD::Wrapper;
11608   CodeModel::Model M = DAG.getTarget().getCodeModel();
11609
11610   if (Subtarget->isPICStyleRIPRel() &&
11611       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11612     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11613       OpFlag = X86II::MO_GOTPCREL;
11614     WrapperKind = X86ISD::WrapperRIP;
11615   } else if (Subtarget->isPICStyleGOT()) {
11616     OpFlag = X86II::MO_GOT;
11617   } else if (Subtarget->isPICStyleStubPIC()) {
11618     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11619   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11620     OpFlag = X86II::MO_DARWIN_NONLAZY;
11621   }
11622
11623   auto PtrVT = getPointerTy(DAG.getDataLayout());
11624   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11625
11626   SDLoc DL(Op);
11627   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11628
11629   // With PIC, the address is actually $g + Offset.
11630   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11631       !Subtarget->is64Bit()) {
11632     Result =
11633         DAG.getNode(ISD::ADD, DL, PtrVT,
11634                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11635   }
11636
11637   // For symbols that require a load from a stub to get the address, emit the
11638   // load.
11639   if (isGlobalStubReference(OpFlag))
11640     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11641                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11642                          false, false, false, 0);
11643
11644   return Result;
11645 }
11646
11647 SDValue
11648 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11649   // Create the TargetBlockAddressAddress node.
11650   unsigned char OpFlags =
11651     Subtarget->ClassifyBlockAddressReference();
11652   CodeModel::Model M = DAG.getTarget().getCodeModel();
11653   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11654   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11655   SDLoc dl(Op);
11656   auto PtrVT = getPointerTy(DAG.getDataLayout());
11657   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11658
11659   if (Subtarget->isPICStyleRIPRel() &&
11660       (M == CodeModel::Small || M == CodeModel::Kernel))
11661     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11662   else
11663     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11664
11665   // With PIC, the address is actually $g + Offset.
11666   if (isGlobalRelativeToPICBase(OpFlags)) {
11667     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11668                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11669   }
11670
11671   return Result;
11672 }
11673
11674 SDValue
11675 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11676                                       int64_t Offset, SelectionDAG &DAG) const {
11677   // Create the TargetGlobalAddress node, folding in the constant
11678   // offset if it is legal.
11679   unsigned char OpFlags =
11680       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11681   CodeModel::Model M = DAG.getTarget().getCodeModel();
11682   auto PtrVT = getPointerTy(DAG.getDataLayout());
11683   SDValue Result;
11684   if (OpFlags == X86II::MO_NO_FLAG &&
11685       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11686     // A direct static reference to a global.
11687     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11688     Offset = 0;
11689   } else {
11690     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11691   }
11692
11693   if (Subtarget->isPICStyleRIPRel() &&
11694       (M == CodeModel::Small || M == CodeModel::Kernel))
11695     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11696   else
11697     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11698
11699   // With PIC, the address is actually $g + Offset.
11700   if (isGlobalRelativeToPICBase(OpFlags)) {
11701     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11702                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11703   }
11704
11705   // For globals that require a load from a stub to get the address, emit the
11706   // load.
11707   if (isGlobalStubReference(OpFlags))
11708     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11709                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11710                          false, false, false, 0);
11711
11712   // If there was a non-zero offset that we didn't fold, create an explicit
11713   // addition for it.
11714   if (Offset != 0)
11715     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11716                          DAG.getConstant(Offset, dl, PtrVT));
11717
11718   return Result;
11719 }
11720
11721 SDValue
11722 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11723   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11724   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11725   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11726 }
11727
11728 static SDValue
11729 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11730            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11731            unsigned char OperandFlags, bool LocalDynamic = false) {
11732   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11733   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11734   SDLoc dl(GA);
11735   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11736                                            GA->getValueType(0),
11737                                            GA->getOffset(),
11738                                            OperandFlags);
11739
11740   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11741                                            : X86ISD::TLSADDR;
11742
11743   if (InFlag) {
11744     SDValue Ops[] = { Chain,  TGA, *InFlag };
11745     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11746   } else {
11747     SDValue Ops[]  = { Chain, TGA };
11748     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11749   }
11750
11751   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11752   MFI->setAdjustsStack(true);
11753   MFI->setHasCalls(true);
11754
11755   SDValue Flag = Chain.getValue(1);
11756   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11757 }
11758
11759 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11760 static SDValue
11761 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11762                                 const EVT PtrVT) {
11763   SDValue InFlag;
11764   SDLoc dl(GA);  // ? function entry point might be better
11765   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11766                                    DAG.getNode(X86ISD::GlobalBaseReg,
11767                                                SDLoc(), PtrVT), InFlag);
11768   InFlag = Chain.getValue(1);
11769
11770   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11771 }
11772
11773 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11774 static SDValue
11775 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11776                                 const EVT PtrVT) {
11777   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11778                     X86::RAX, X86II::MO_TLSGD);
11779 }
11780
11781 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11782                                            SelectionDAG &DAG,
11783                                            const EVT PtrVT,
11784                                            bool is64Bit) {
11785   SDLoc dl(GA);
11786
11787   // Get the start address of the TLS block for this module.
11788   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11789       .getInfo<X86MachineFunctionInfo>();
11790   MFI->incNumLocalDynamicTLSAccesses();
11791
11792   SDValue Base;
11793   if (is64Bit) {
11794     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11795                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11796   } else {
11797     SDValue InFlag;
11798     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11799         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11800     InFlag = Chain.getValue(1);
11801     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11802                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11803   }
11804
11805   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11806   // of Base.
11807
11808   // Build x@dtpoff.
11809   unsigned char OperandFlags = X86II::MO_DTPOFF;
11810   unsigned WrapperKind = X86ISD::Wrapper;
11811   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11812                                            GA->getValueType(0),
11813                                            GA->getOffset(), OperandFlags);
11814   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11815
11816   // Add x@dtpoff with the base.
11817   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11818 }
11819
11820 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11821 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11822                                    const EVT PtrVT, TLSModel::Model model,
11823                                    bool is64Bit, bool isPIC) {
11824   SDLoc dl(GA);
11825
11826   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11827   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11828                                                          is64Bit ? 257 : 256));
11829
11830   SDValue ThreadPointer =
11831       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11832                   MachinePointerInfo(Ptr), false, false, false, 0);
11833
11834   unsigned char OperandFlags = 0;
11835   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11836   // initialexec.
11837   unsigned WrapperKind = X86ISD::Wrapper;
11838   if (model == TLSModel::LocalExec) {
11839     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11840   } else if (model == TLSModel::InitialExec) {
11841     if (is64Bit) {
11842       OperandFlags = X86II::MO_GOTTPOFF;
11843       WrapperKind = X86ISD::WrapperRIP;
11844     } else {
11845       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11846     }
11847   } else {
11848     llvm_unreachable("Unexpected model");
11849   }
11850
11851   // emit "addl x@ntpoff,%eax" (local exec)
11852   // or "addl x@indntpoff,%eax" (initial exec)
11853   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11854   SDValue TGA =
11855       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11856                                  GA->getOffset(), OperandFlags);
11857   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11858
11859   if (model == TLSModel::InitialExec) {
11860     if (isPIC && !is64Bit) {
11861       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11862                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11863                            Offset);
11864     }
11865
11866     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11867                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11868                          false, false, false, 0);
11869   }
11870
11871   // The address of the thread local variable is the add of the thread
11872   // pointer with the offset of the variable.
11873   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11874 }
11875
11876 SDValue
11877 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11878
11879   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11880   const GlobalValue *GV = GA->getGlobal();
11881   auto PtrVT = getPointerTy(DAG.getDataLayout());
11882
11883   if (Subtarget->isTargetELF()) {
11884     if (DAG.getTarget().Options.EmulatedTLS)
11885       return LowerToTLSEmulatedModel(GA, DAG);
11886     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11887     switch (model) {
11888       case TLSModel::GeneralDynamic:
11889         if (Subtarget->is64Bit())
11890           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11891         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11892       case TLSModel::LocalDynamic:
11893         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11894                                            Subtarget->is64Bit());
11895       case TLSModel::InitialExec:
11896       case TLSModel::LocalExec:
11897         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11898                                    DAG.getTarget().getRelocationModel() ==
11899                                        Reloc::PIC_);
11900     }
11901     llvm_unreachable("Unknown TLS model.");
11902   }
11903
11904   if (Subtarget->isTargetDarwin()) {
11905     // Darwin only has one model of TLS.  Lower to that.
11906     unsigned char OpFlag = 0;
11907     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11908                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11909
11910     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11911     // global base reg.
11912     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11913                  !Subtarget->is64Bit();
11914     if (PIC32)
11915       OpFlag = X86II::MO_TLVP_PIC_BASE;
11916     else
11917       OpFlag = X86II::MO_TLVP;
11918     SDLoc DL(Op);
11919     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11920                                                 GA->getValueType(0),
11921                                                 GA->getOffset(), OpFlag);
11922     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11923
11924     // With PIC32, the address is actually $g + Offset.
11925     if (PIC32)
11926       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11927                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11928                            Offset);
11929
11930     // Lowering the machine isd will make sure everything is in the right
11931     // location.
11932     SDValue Chain = DAG.getEntryNode();
11933     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11934     SDValue Args[] = { Chain, Offset };
11935     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11936
11937     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11938     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11939     MFI->setAdjustsStack(true);
11940
11941     // And our return value (tls address) is in the standard call return value
11942     // location.
11943     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11944     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11945   }
11946
11947   if (Subtarget->isTargetKnownWindowsMSVC() ||
11948       Subtarget->isTargetWindowsGNU()) {
11949     // Just use the implicit TLS architecture
11950     // Need to generate someting similar to:
11951     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11952     //                                  ; from TEB
11953     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11954     //   mov     rcx, qword [rdx+rcx*8]
11955     //   mov     eax, .tls$:tlsvar
11956     //   [rax+rcx] contains the address
11957     // Windows 64bit: gs:0x58
11958     // Windows 32bit: fs:__tls_array
11959
11960     SDLoc dl(GA);
11961     SDValue Chain = DAG.getEntryNode();
11962
11963     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11964     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11965     // use its literal value of 0x2C.
11966     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11967                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11968                                                              256)
11969                                         : Type::getInt32PtrTy(*DAG.getContext(),
11970                                                               257));
11971
11972     SDValue TlsArray = Subtarget->is64Bit()
11973                            ? DAG.getIntPtrConstant(0x58, dl)
11974                            : (Subtarget->isTargetWindowsGNU()
11975                                   ? DAG.getIntPtrConstant(0x2C, dl)
11976                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11977
11978     SDValue ThreadPointer =
11979         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11980                     false, false, 0);
11981
11982     SDValue res;
11983     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11984       res = ThreadPointer;
11985     } else {
11986       // Load the _tls_index variable
11987       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11988       if (Subtarget->is64Bit())
11989         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11990                              MachinePointerInfo(), MVT::i32, false, false,
11991                              false, 0);
11992       else
11993         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11994                           false, false, 0);
11995
11996       auto &DL = DAG.getDataLayout();
11997       SDValue Scale =
11998           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11999       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12000
12001       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12002     }
12003
12004     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12005                       false, 0);
12006
12007     // Get the offset of start of .tls section
12008     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12009                                              GA->getValueType(0),
12010                                              GA->getOffset(), X86II::MO_SECREL);
12011     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12012
12013     // The address of the thread local variable is the add of the thread
12014     // pointer with the offset of the variable.
12015     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12016   }
12017
12018   llvm_unreachable("TLS not implemented for this target.");
12019 }
12020
12021 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12022 /// and take a 2 x i32 value to shift plus a shift amount.
12023 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12024   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12025   MVT VT = Op.getSimpleValueType();
12026   unsigned VTBits = VT.getSizeInBits();
12027   SDLoc dl(Op);
12028   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12029   SDValue ShOpLo = Op.getOperand(0);
12030   SDValue ShOpHi = Op.getOperand(1);
12031   SDValue ShAmt  = Op.getOperand(2);
12032   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12033   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12034   // during isel.
12035   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12036                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12037   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12038                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12039                        : DAG.getConstant(0, dl, VT);
12040
12041   SDValue Tmp2, Tmp3;
12042   if (Op.getOpcode() == ISD::SHL_PARTS) {
12043     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12044     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12045   } else {
12046     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12047     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12048   }
12049
12050   // If the shift amount is larger or equal than the width of a part we can't
12051   // rely on the results of shld/shrd. Insert a test and select the appropriate
12052   // values for large shift amounts.
12053   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12054                                 DAG.getConstant(VTBits, dl, MVT::i8));
12055   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12056                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12057
12058   SDValue Hi, Lo;
12059   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12060   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12061   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12062
12063   if (Op.getOpcode() == ISD::SHL_PARTS) {
12064     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12065     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12066   } else {
12067     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12068     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12069   }
12070
12071   SDValue Ops[2] = { Lo, Hi };
12072   return DAG.getMergeValues(Ops, dl);
12073 }
12074
12075 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12076                                            SelectionDAG &DAG) const {
12077   SDValue Src = Op.getOperand(0);
12078   MVT SrcVT = Src.getSimpleValueType();
12079   MVT VT = Op.getSimpleValueType();
12080   SDLoc dl(Op);
12081
12082   if (SrcVT.isVector()) {
12083     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12084       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12085                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12086                          DAG.getUNDEF(SrcVT)));
12087     }
12088     if (SrcVT.getVectorElementType() == MVT::i1) {
12089       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12090       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12091                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12092     }
12093     return SDValue();
12094   }
12095
12096   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12097          "Unknown SINT_TO_FP to lower!");
12098
12099   // These are really Legal; return the operand so the caller accepts it as
12100   // Legal.
12101   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12102     return Op;
12103   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12104       Subtarget->is64Bit()) {
12105     return Op;
12106   }
12107
12108   unsigned Size = SrcVT.getSizeInBits()/8;
12109   MachineFunction &MF = DAG.getMachineFunction();
12110   auto PtrVT = getPointerTy(MF.getDataLayout());
12111   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12112   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12113   SDValue Chain = DAG.getStore(
12114       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12115       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12116       false, 0);
12117   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12118 }
12119
12120 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12121                                      SDValue StackSlot,
12122                                      SelectionDAG &DAG) const {
12123   // Build the FILD
12124   SDLoc DL(Op);
12125   SDVTList Tys;
12126   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12127   if (useSSE)
12128     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12129   else
12130     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12131
12132   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12133
12134   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12135   MachineMemOperand *MMO;
12136   if (FI) {
12137     int SSFI = FI->getIndex();
12138     MMO = DAG.getMachineFunction().getMachineMemOperand(
12139         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12140         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12141   } else {
12142     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12143     StackSlot = StackSlot.getOperand(1);
12144   }
12145   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12146   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12147                                            X86ISD::FILD, DL,
12148                                            Tys, Ops, SrcVT, MMO);
12149
12150   if (useSSE) {
12151     Chain = Result.getValue(1);
12152     SDValue InFlag = Result.getValue(2);
12153
12154     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12155     // shouldn't be necessary except that RFP cannot be live across
12156     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12157     MachineFunction &MF = DAG.getMachineFunction();
12158     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12159     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12160     auto PtrVT = getPointerTy(MF.getDataLayout());
12161     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12162     Tys = DAG.getVTList(MVT::Other);
12163     SDValue Ops[] = {
12164       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12165     };
12166     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12167         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12168         MachineMemOperand::MOStore, SSFISize, SSFISize);
12169
12170     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12171                                     Ops, Op.getValueType(), MMO);
12172     Result = DAG.getLoad(
12173         Op.getValueType(), DL, Chain, StackSlot,
12174         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12175         false, false, false, 0);
12176   }
12177
12178   return Result;
12179 }
12180
12181 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12182 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12183                                                SelectionDAG &DAG) const {
12184   // This algorithm is not obvious. Here it is what we're trying to output:
12185   /*
12186      movq       %rax,  %xmm0
12187      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12188      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12189      #ifdef __SSE3__
12190        haddpd   %xmm0, %xmm0
12191      #else
12192        pshufd   $0x4e, %xmm0, %xmm1
12193        addpd    %xmm1, %xmm0
12194      #endif
12195   */
12196
12197   SDLoc dl(Op);
12198   LLVMContext *Context = DAG.getContext();
12199
12200   // Build some magic constants.
12201   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12202   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12203   auto PtrVT = getPointerTy(DAG.getDataLayout());
12204   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12205
12206   SmallVector<Constant*,2> CV1;
12207   CV1.push_back(
12208     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12209                                       APInt(64, 0x4330000000000000ULL))));
12210   CV1.push_back(
12211     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12212                                       APInt(64, 0x4530000000000000ULL))));
12213   Constant *C1 = ConstantVector::get(CV1);
12214   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12215
12216   // Load the 64-bit value into an XMM register.
12217   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12218                             Op.getOperand(0));
12219   SDValue CLod0 =
12220       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12221                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12222                   false, false, false, 16);
12223   SDValue Unpck1 =
12224       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12225
12226   SDValue CLod1 =
12227       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12228                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12229                   false, false, false, 16);
12230   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12231   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12232   SDValue Result;
12233
12234   if (Subtarget->hasSSE3()) {
12235     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12236     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12237   } else {
12238     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12239     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12240                                            S2F, 0x4E, DAG);
12241     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12242                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12243   }
12244
12245   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12246                      DAG.getIntPtrConstant(0, dl));
12247 }
12248
12249 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12250 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12251                                                SelectionDAG &DAG) const {
12252   SDLoc dl(Op);
12253   // FP constant to bias correct the final result.
12254   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12255                                    MVT::f64);
12256
12257   // Load the 32-bit value into an XMM register.
12258   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12259                              Op.getOperand(0));
12260
12261   // Zero out the upper parts of the register.
12262   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12263
12264   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12265                      DAG.getBitcast(MVT::v2f64, Load),
12266                      DAG.getIntPtrConstant(0, dl));
12267
12268   // Or the load with the bias.
12269   SDValue Or = DAG.getNode(
12270       ISD::OR, dl, MVT::v2i64,
12271       DAG.getBitcast(MVT::v2i64,
12272                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12273       DAG.getBitcast(MVT::v2i64,
12274                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12275   Or =
12276       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12277                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12278
12279   // Subtract the bias.
12280   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12281
12282   // Handle final rounding.
12283   EVT DestVT = Op.getValueType();
12284
12285   if (DestVT.bitsLT(MVT::f64))
12286     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12287                        DAG.getIntPtrConstant(0, dl));
12288   if (DestVT.bitsGT(MVT::f64))
12289     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12290
12291   // Handle final rounding.
12292   return Sub;
12293 }
12294
12295 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12296                                      const X86Subtarget &Subtarget) {
12297   // The algorithm is the following:
12298   // #ifdef __SSE4_1__
12299   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12300   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12301   //                                 (uint4) 0x53000000, 0xaa);
12302   // #else
12303   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12304   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12305   // #endif
12306   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12307   //     return (float4) lo + fhi;
12308
12309   SDLoc DL(Op);
12310   SDValue V = Op->getOperand(0);
12311   EVT VecIntVT = V.getValueType();
12312   bool Is128 = VecIntVT == MVT::v4i32;
12313   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12314   // If we convert to something else than the supported type, e.g., to v4f64,
12315   // abort early.
12316   if (VecFloatVT != Op->getValueType(0))
12317     return SDValue();
12318
12319   unsigned NumElts = VecIntVT.getVectorNumElements();
12320   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12321          "Unsupported custom type");
12322   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12323
12324   // In the #idef/#else code, we have in common:
12325   // - The vector of constants:
12326   // -- 0x4b000000
12327   // -- 0x53000000
12328   // - A shift:
12329   // -- v >> 16
12330
12331   // Create the splat vector for 0x4b000000.
12332   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12333   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12334                            CstLow, CstLow, CstLow, CstLow};
12335   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12336                                   makeArrayRef(&CstLowArray[0], NumElts));
12337   // Create the splat vector for 0x53000000.
12338   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12339   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12340                             CstHigh, CstHigh, CstHigh, CstHigh};
12341   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12342                                    makeArrayRef(&CstHighArray[0], NumElts));
12343
12344   // Create the right shift.
12345   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12346   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12347                              CstShift, CstShift, CstShift, CstShift};
12348   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12349                                     makeArrayRef(&CstShiftArray[0], NumElts));
12350   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12351
12352   SDValue Low, High;
12353   if (Subtarget.hasSSE41()) {
12354     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12355     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12356     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12357     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12358     // Low will be bitcasted right away, so do not bother bitcasting back to its
12359     // original type.
12360     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12361                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12362     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12363     //                                 (uint4) 0x53000000, 0xaa);
12364     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12365     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12366     // High will be bitcasted right away, so do not bother bitcasting back to
12367     // its original type.
12368     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12369                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12370   } else {
12371     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12372     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12373                                      CstMask, CstMask, CstMask);
12374     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12375     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12376     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12377
12378     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12379     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12380   }
12381
12382   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12383   SDValue CstFAdd = DAG.getConstantFP(
12384       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12385   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12386                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12387   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12388                                    makeArrayRef(&CstFAddArray[0], NumElts));
12389
12390   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12391   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12392   SDValue FHigh =
12393       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12394   //     return (float4) lo + fhi;
12395   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12396   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12397 }
12398
12399 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12400                                                SelectionDAG &DAG) const {
12401   SDValue N0 = Op.getOperand(0);
12402   MVT SVT = N0.getSimpleValueType();
12403   SDLoc dl(Op);
12404
12405   switch (SVT.SimpleTy) {
12406   default:
12407     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12408   case MVT::v4i8:
12409   case MVT::v4i16:
12410   case MVT::v8i8:
12411   case MVT::v8i16: {
12412     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12413     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12414                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12415   }
12416   case MVT::v4i32:
12417   case MVT::v8i32:
12418     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12419   case MVT::v16i8:
12420   case MVT::v16i16:
12421     if (Subtarget->hasAVX512())
12422       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12423                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12424   }
12425   llvm_unreachable(nullptr);
12426 }
12427
12428 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12429                                            SelectionDAG &DAG) const {
12430   SDValue N0 = Op.getOperand(0);
12431   SDLoc dl(Op);
12432   auto PtrVT = getPointerTy(DAG.getDataLayout());
12433
12434   if (Op.getValueType().isVector())
12435     return lowerUINT_TO_FP_vec(Op, DAG);
12436
12437   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12438   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12439   // the optimization here.
12440   if (DAG.SignBitIsZero(N0))
12441     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12442
12443   MVT SrcVT = N0.getSimpleValueType();
12444   MVT DstVT = Op.getSimpleValueType();
12445   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12446     return LowerUINT_TO_FP_i64(Op, DAG);
12447   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12448     return LowerUINT_TO_FP_i32(Op, DAG);
12449   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12450     return SDValue();
12451
12452   // Make a 64-bit buffer, and use it to build an FILD.
12453   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12454   if (SrcVT == MVT::i32) {
12455     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12456     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12457     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12458                                   StackSlot, MachinePointerInfo(),
12459                                   false, false, 0);
12460     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12461                                   OffsetSlot, MachinePointerInfo(),
12462                                   false, false, 0);
12463     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12464     return Fild;
12465   }
12466
12467   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12468   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12469                                StackSlot, MachinePointerInfo(),
12470                                false, false, 0);
12471   // For i64 source, we need to add the appropriate power of 2 if the input
12472   // was negative.  This is the same as the optimization in
12473   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12474   // we must be careful to do the computation in x87 extended precision, not
12475   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12476   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12477   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12478       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12479       MachineMemOperand::MOLoad, 8, 8);
12480
12481   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12482   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12483   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12484                                          MVT::i64, MMO);
12485
12486   APInt FF(32, 0x5F800000ULL);
12487
12488   // Check whether the sign bit is set.
12489   SDValue SignSet = DAG.getSetCC(
12490       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12491       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12492
12493   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12494   SDValue FudgePtr = DAG.getConstantPool(
12495       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12496
12497   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12498   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12499   SDValue Four = DAG.getIntPtrConstant(4, dl);
12500   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12501                                Zero, Four);
12502   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12503
12504   // Load the value out, extending it from f32 to f80.
12505   // FIXME: Avoid the extend by constructing the right constant pool?
12506   SDValue Fudge = DAG.getExtLoad(
12507       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12508       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12509       false, false, false, 4);
12510   // Extend everything to 80 bits to force it to be done on x87.
12511   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12512   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12513                      DAG.getIntPtrConstant(0, dl));
12514 }
12515
12516 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12517 // is legal, or has an f16 source (which needs to be promoted to f32),
12518 // just return an <SDValue(), SDValue()> pair.
12519 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12520 // to i16, i32 or i64, and we lower it to a legal sequence.
12521 // If lowered to the final integer result we return a <result, SDValue()> pair.
12522 // Otherwise we lower it to a sequence ending with a FIST, return a
12523 // <FIST, StackSlot> pair, and the caller is responsible for loading
12524 // the final integer result from StackSlot.
12525 std::pair<SDValue,SDValue>
12526 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12527                                    bool IsSigned, bool IsReplace) const {
12528   SDLoc DL(Op);
12529
12530   EVT DstTy = Op.getValueType();
12531   EVT TheVT = Op.getOperand(0).getValueType();
12532   auto PtrVT = getPointerTy(DAG.getDataLayout());
12533
12534   if (TheVT == MVT::f16)
12535     // We need to promote the f16 to f32 before using the lowering
12536     // in this routine.
12537     return std::make_pair(SDValue(), SDValue());
12538
12539   assert((TheVT == MVT::f32 ||
12540           TheVT == MVT::f64 ||
12541           TheVT == MVT::f80) &&
12542          "Unexpected FP operand type in FP_TO_INTHelper");
12543
12544   // If using FIST to compute an unsigned i64, we'll need some fixup
12545   // to handle values above the maximum signed i64.  A FIST is always
12546   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12547   bool UnsignedFixup = !IsSigned &&
12548                        DstTy == MVT::i64 &&
12549                        (!Subtarget->is64Bit() ||
12550                         !isScalarFPTypeInSSEReg(TheVT));
12551
12552   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12553     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12554     // The low 32 bits of the fist result will have the correct uint32 result.
12555     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12556     DstTy = MVT::i64;
12557   }
12558
12559   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12560          DstTy.getSimpleVT() >= MVT::i16 &&
12561          "Unknown FP_TO_INT to lower!");
12562
12563   // These are really Legal.
12564   if (DstTy == MVT::i32 &&
12565       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12566     return std::make_pair(SDValue(), SDValue());
12567   if (Subtarget->is64Bit() &&
12568       DstTy == MVT::i64 &&
12569       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12570     return std::make_pair(SDValue(), SDValue());
12571
12572   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12573   // stack slot.
12574   MachineFunction &MF = DAG.getMachineFunction();
12575   unsigned MemSize = DstTy.getSizeInBits()/8;
12576   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12577   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12578
12579   unsigned Opc;
12580   switch (DstTy.getSimpleVT().SimpleTy) {
12581   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12582   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12583   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12584   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12585   }
12586
12587   SDValue Chain = DAG.getEntryNode();
12588   SDValue Value = Op.getOperand(0);
12589   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12590
12591   if (UnsignedFixup) {
12592     //
12593     // Conversion to unsigned i64 is implemented with a select,
12594     // depending on whether the source value fits in the range
12595     // of a signed i64.  Let Thresh be the FP equivalent of
12596     // 0x8000000000000000ULL.
12597     //
12598     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12599     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12600     //  Fist-to-mem64 FistSrc
12601     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12602     //  to XOR'ing the high 32 bits with Adjust.
12603     //
12604     // Being a power of 2, Thresh is exactly representable in all FP formats.
12605     // For X87 we'd like to use the smallest FP type for this constant, but
12606     // for DAG type consistency we have to match the FP operand type.
12607
12608     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12609     APFloat::opStatus Status = APFloat::opOK;
12610     bool LosesInfo = false;
12611     if (TheVT == MVT::f64)
12612       // The rounding mode is irrelevant as the conversion should be exact.
12613       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12614                               &LosesInfo);
12615     else if (TheVT == MVT::f80)
12616       Status = Thresh.convert(APFloat::x87DoubleExtended,
12617                               APFloat::rmNearestTiesToEven, &LosesInfo);
12618
12619     assert(Status == APFloat::opOK && !LosesInfo &&
12620            "FP conversion should have been exact");
12621
12622     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12623
12624     SDValue Cmp = DAG.getSetCC(DL,
12625                                getSetCCResultType(DAG.getDataLayout(),
12626                                                   *DAG.getContext(), TheVT),
12627                                Value, ThreshVal, ISD::SETLT);
12628     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12629                            DAG.getConstant(0, DL, MVT::i32),
12630                            DAG.getConstant(0x80000000, DL, MVT::i32));
12631     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12632     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12633                                               *DAG.getContext(), TheVT),
12634                        Value, ThreshVal, ISD::SETLT);
12635     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12636   }
12637
12638   // FIXME This causes a redundant load/store if the SSE-class value is already
12639   // in memory, such as if it is on the callstack.
12640   if (isScalarFPTypeInSSEReg(TheVT)) {
12641     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12642     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12643                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12644                          false, 0);
12645     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12646     SDValue Ops[] = {
12647       Chain, StackSlot, DAG.getValueType(TheVT)
12648     };
12649
12650     MachineMemOperand *MMO =
12651         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12652                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12653     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12654     Chain = Value.getValue(1);
12655     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12656     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12657   }
12658
12659   MachineMemOperand *MMO =
12660       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12661                               MachineMemOperand::MOStore, MemSize, MemSize);
12662
12663   if (UnsignedFixup) {
12664
12665     // Insert the FIST, load its result as two i32's,
12666     // and XOR the high i32 with Adjust.
12667
12668     SDValue FistOps[] = { Chain, Value, StackSlot };
12669     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12670                                            FistOps, DstTy, MMO);
12671
12672     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12673                                 MachinePointerInfo(),
12674                                 false, false, false, 0);
12675     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12676                                    DAG.getConstant(4, DL, PtrVT));
12677
12678     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12679                                  MachinePointerInfo(),
12680                                  false, false, false, 0);
12681     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12682
12683     if (Subtarget->is64Bit()) {
12684       // Join High32 and Low32 into a 64-bit result.
12685       // (High32 << 32) | Low32
12686       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12687       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12688       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12689                            DAG.getConstant(32, DL, MVT::i8));
12690       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12691       return std::make_pair(Result, SDValue());
12692     }
12693
12694     SDValue ResultOps[] = { Low32, High32 };
12695
12696     SDValue pair = IsReplace
12697       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12698       : DAG.getMergeValues(ResultOps, DL);
12699     return std::make_pair(pair, SDValue());
12700   } else {
12701     // Build the FP_TO_INT*_IN_MEM
12702     SDValue Ops[] = { Chain, Value, StackSlot };
12703     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12704                                            Ops, DstTy, MMO);
12705     return std::make_pair(FIST, StackSlot);
12706   }
12707 }
12708
12709 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12710                               const X86Subtarget *Subtarget) {
12711   MVT VT = Op->getSimpleValueType(0);
12712   SDValue In = Op->getOperand(0);
12713   MVT InVT = In.getSimpleValueType();
12714   SDLoc dl(Op);
12715
12716   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12717     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12718
12719   // Optimize vectors in AVX mode:
12720   //
12721   //   v8i16 -> v8i32
12722   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12723   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12724   //   Concat upper and lower parts.
12725   //
12726   //   v4i32 -> v4i64
12727   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12728   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12729   //   Concat upper and lower parts.
12730   //
12731
12732   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12733       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12734       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12735     return SDValue();
12736
12737   if (Subtarget->hasInt256())
12738     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12739
12740   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12741   SDValue Undef = DAG.getUNDEF(InVT);
12742   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12743   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12744   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12745
12746   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12747                              VT.getVectorNumElements()/2);
12748
12749   OpLo = DAG.getBitcast(HVT, OpLo);
12750   OpHi = DAG.getBitcast(HVT, OpHi);
12751
12752   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12753 }
12754
12755 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12756                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12757   MVT VT = Op->getSimpleValueType(0);
12758   SDValue In = Op->getOperand(0);
12759   MVT InVT = In.getSimpleValueType();
12760   SDLoc DL(Op);
12761   unsigned int NumElts = VT.getVectorNumElements();
12762   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12763     return SDValue();
12764
12765   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12766     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12767
12768   assert(InVT.getVectorElementType() == MVT::i1);
12769   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12770   SDValue One =
12771    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12772   SDValue Zero =
12773    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12774
12775   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12776   if (VT.is512BitVector())
12777     return V;
12778   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12779 }
12780
12781 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12782                                SelectionDAG &DAG) {
12783   if (Subtarget->hasFp256())
12784     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12785       return Res;
12786
12787   return SDValue();
12788 }
12789
12790 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12791                                 SelectionDAG &DAG) {
12792   SDLoc DL(Op);
12793   MVT VT = Op.getSimpleValueType();
12794   SDValue In = Op.getOperand(0);
12795   MVT SVT = In.getSimpleValueType();
12796
12797   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12798     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12799
12800   if (Subtarget->hasFp256())
12801     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12802       return Res;
12803
12804   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12805          VT.getVectorNumElements() != SVT.getVectorNumElements());
12806   return SDValue();
12807 }
12808
12809 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12810   SDLoc DL(Op);
12811   MVT VT = Op.getSimpleValueType();
12812   SDValue In = Op.getOperand(0);
12813   MVT InVT = In.getSimpleValueType();
12814
12815   if (VT == MVT::i1) {
12816     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12817            "Invalid scalar TRUNCATE operation");
12818     if (InVT.getSizeInBits() >= 32)
12819       return SDValue();
12820     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12821     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12822   }
12823   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12824          "Invalid TRUNCATE operation");
12825
12826   // move vector to mask - truncate solution for SKX
12827   if (VT.getVectorElementType() == MVT::i1) {
12828     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12829         Subtarget->hasBWI())
12830       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12831     if ((InVT.is256BitVector() || InVT.is128BitVector())
12832         && InVT.getScalarSizeInBits() <= 16 &&
12833         Subtarget->hasBWI() && Subtarget->hasVLX())
12834       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12835     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12836         Subtarget->hasDQI())
12837       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12838     if ((InVT.is256BitVector() || InVT.is128BitVector())
12839         && InVT.getScalarSizeInBits() >= 32 &&
12840         Subtarget->hasDQI() && Subtarget->hasVLX())
12841       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12842   }
12843
12844   if (VT.getVectorElementType() == MVT::i1) {
12845     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12846     unsigned NumElts = InVT.getVectorNumElements();
12847     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12848     if (InVT.getSizeInBits() < 512) {
12849       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12850       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12851       InVT = ExtVT;
12852     }
12853
12854     SDValue OneV =
12855      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12856     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12857     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12858   }
12859
12860   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12861   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12862       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12863     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12864
12865   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12866     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12867     if (Subtarget->hasInt256()) {
12868       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12869       In = DAG.getBitcast(MVT::v8i32, In);
12870       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12871                                 ShufMask);
12872       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12873                          DAG.getIntPtrConstant(0, DL));
12874     }
12875
12876     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12877                                DAG.getIntPtrConstant(0, DL));
12878     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12879                                DAG.getIntPtrConstant(2, DL));
12880     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12881     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12882     static const int ShufMask[] = {0, 2, 4, 6};
12883     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12884   }
12885
12886   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12887     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12888     if (Subtarget->hasInt256()) {
12889       In = DAG.getBitcast(MVT::v32i8, In);
12890
12891       SmallVector<SDValue,32> pshufbMask;
12892       for (unsigned i = 0; i < 2; ++i) {
12893         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12894         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12895         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12896         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12897         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12898         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12899         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12900         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12901         for (unsigned j = 0; j < 8; ++j)
12902           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12903       }
12904       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12905       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12906       In = DAG.getBitcast(MVT::v4i64, In);
12907
12908       static const int ShufMask[] = {0,  2,  -1,  -1};
12909       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12910                                 &ShufMask[0]);
12911       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12912                        DAG.getIntPtrConstant(0, DL));
12913       return DAG.getBitcast(VT, In);
12914     }
12915
12916     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12917                                DAG.getIntPtrConstant(0, DL));
12918
12919     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12920                                DAG.getIntPtrConstant(4, DL));
12921
12922     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12923     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12924
12925     // The PSHUFB mask:
12926     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12927                                    -1, -1, -1, -1, -1, -1, -1, -1};
12928
12929     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12930     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12931     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12932
12933     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12934     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12935
12936     // The MOVLHPS Mask:
12937     static const int ShufMask2[] = {0, 1, 4, 5};
12938     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12939     return DAG.getBitcast(MVT::v8i16, res);
12940   }
12941
12942   // Handle truncation of V256 to V128 using shuffles.
12943   if (!VT.is128BitVector() || !InVT.is256BitVector())
12944     return SDValue();
12945
12946   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12947
12948   unsigned NumElems = VT.getVectorNumElements();
12949   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12950
12951   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12952   // Prepare truncation shuffle mask
12953   for (unsigned i = 0; i != NumElems; ++i)
12954     MaskVec[i] = i * 2;
12955   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12956                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12957   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12958                      DAG.getIntPtrConstant(0, DL));
12959 }
12960
12961 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12962                                            SelectionDAG &DAG) const {
12963   assert(!Op.getSimpleValueType().isVector());
12964
12965   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12966     /*IsSigned=*/ true, /*IsReplace=*/ false);
12967   SDValue FIST = Vals.first, StackSlot = Vals.second;
12968   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12969   if (!FIST.getNode())
12970     return Op;
12971
12972   if (StackSlot.getNode())
12973     // Load the result.
12974     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12975                        FIST, StackSlot, MachinePointerInfo(),
12976                        false, false, false, 0);
12977
12978   // The node is the result.
12979   return FIST;
12980 }
12981
12982 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12983                                            SelectionDAG &DAG) const {
12984   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12985     /*IsSigned=*/ false, /*IsReplace=*/ false);
12986   SDValue FIST = Vals.first, StackSlot = Vals.second;
12987   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12988   if (!FIST.getNode())
12989     return Op;
12990
12991   if (StackSlot.getNode())
12992     // Load the result.
12993     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12994                        FIST, StackSlot, MachinePointerInfo(),
12995                        false, false, false, 0);
12996
12997   // The node is the result.
12998   return FIST;
12999 }
13000
13001 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13002   SDLoc DL(Op);
13003   MVT VT = Op.getSimpleValueType();
13004   SDValue In = Op.getOperand(0);
13005   MVT SVT = In.getSimpleValueType();
13006
13007   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13008
13009   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13010                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13011                                  In, DAG.getUNDEF(SVT)));
13012 }
13013
13014 /// The only differences between FABS and FNEG are the mask and the logic op.
13015 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13016 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13017   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13018          "Wrong opcode for lowering FABS or FNEG.");
13019
13020   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13021
13022   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13023   // into an FNABS. We'll lower the FABS after that if it is still in use.
13024   if (IsFABS)
13025     for (SDNode *User : Op->uses())
13026       if (User->getOpcode() == ISD::FNEG)
13027         return Op;
13028
13029   SDLoc dl(Op);
13030   MVT VT = Op.getSimpleValueType();
13031
13032   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13033   // decide if we should generate a 16-byte constant mask when we only need 4 or
13034   // 8 bytes for the scalar case.
13035
13036   MVT LogicVT;
13037   MVT EltVT;
13038   unsigned NumElts;
13039
13040   if (VT.isVector()) {
13041     LogicVT = VT;
13042     EltVT = VT.getVectorElementType();
13043     NumElts = VT.getVectorNumElements();
13044   } else {
13045     // There are no scalar bitwise logical SSE/AVX instructions, so we
13046     // generate a 16-byte vector constant and logic op even for the scalar case.
13047     // Using a 16-byte mask allows folding the load of the mask with
13048     // the logic op, so it can save (~4 bytes) on code size.
13049     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13050     EltVT = VT;
13051     NumElts = (VT == MVT::f64) ? 2 : 4;
13052   }
13053
13054   unsigned EltBits = EltVT.getSizeInBits();
13055   LLVMContext *Context = DAG.getContext();
13056   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13057   APInt MaskElt =
13058     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13059   Constant *C = ConstantInt::get(*Context, MaskElt);
13060   C = ConstantVector::getSplat(NumElts, C);
13061   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13062   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13063   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13064   SDValue Mask =
13065       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13066                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13067                   false, false, false, Alignment);
13068
13069   SDValue Op0 = Op.getOperand(0);
13070   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13071   unsigned LogicOp =
13072     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13073   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13074
13075   if (VT.isVector())
13076     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13077
13078   // For the scalar case extend to a 128-bit vector, perform the logic op,
13079   // and extract the scalar result back out.
13080   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13081   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13082   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13083                      DAG.getIntPtrConstant(0, dl));
13084 }
13085
13086 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13088   LLVMContext *Context = DAG.getContext();
13089   SDValue Op0 = Op.getOperand(0);
13090   SDValue Op1 = Op.getOperand(1);
13091   SDLoc dl(Op);
13092   MVT VT = Op.getSimpleValueType();
13093   MVT SrcVT = Op1.getSimpleValueType();
13094
13095   // If second operand is smaller, extend it first.
13096   if (SrcVT.bitsLT(VT)) {
13097     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13098     SrcVT = VT;
13099   }
13100   // And if it is bigger, shrink it first.
13101   if (SrcVT.bitsGT(VT)) {
13102     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13103     SrcVT = VT;
13104   }
13105
13106   // At this point the operands and the result should have the same
13107   // type, and that won't be f80 since that is not custom lowered.
13108
13109   const fltSemantics &Sem =
13110       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13111   const unsigned SizeInBits = VT.getSizeInBits();
13112
13113   SmallVector<Constant *, 4> CV(
13114       VT == MVT::f64 ? 2 : 4,
13115       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13116
13117   // First, clear all bits but the sign bit from the second operand (sign).
13118   CV[0] = ConstantFP::get(*Context,
13119                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13120   Constant *C = ConstantVector::get(CV);
13121   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13122   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13123
13124   // Perform all logic operations as 16-byte vectors because there are no
13125   // scalar FP logic instructions in SSE. This allows load folding of the
13126   // constants into the logic instructions.
13127   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13128   SDValue Mask1 =
13129       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13130                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13131                   false, false, false, 16);
13132   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13133   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13134
13135   // Next, clear the sign bit from the first operand (magnitude).
13136   // If it's a constant, we can clear it here.
13137   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13138     APFloat APF = Op0CN->getValueAPF();
13139     // If the magnitude is a positive zero, the sign bit alone is enough.
13140     if (APF.isPosZero())
13141       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13142                          DAG.getIntPtrConstant(0, dl));
13143     APF.clearSign();
13144     CV[0] = ConstantFP::get(*Context, APF);
13145   } else {
13146     CV[0] = ConstantFP::get(
13147         *Context,
13148         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13149   }
13150   C = ConstantVector::get(CV);
13151   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13152   SDValue Val =
13153       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13154                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13155                   false, false, false, 16);
13156   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13157   if (!isa<ConstantFPSDNode>(Op0)) {
13158     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13159     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13160   }
13161   // OR the magnitude value with the sign bit.
13162   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13163   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13164                      DAG.getIntPtrConstant(0, dl));
13165 }
13166
13167 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13168   SDValue N0 = Op.getOperand(0);
13169   SDLoc dl(Op);
13170   MVT VT = Op.getSimpleValueType();
13171
13172   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13173   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13174                                   DAG.getConstant(1, dl, VT));
13175   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13176 }
13177
13178 // Check whether an OR'd tree is PTEST-able.
13179 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13180                                       SelectionDAG &DAG) {
13181   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13182
13183   if (!Subtarget->hasSSE41())
13184     return SDValue();
13185
13186   if (!Op->hasOneUse())
13187     return SDValue();
13188
13189   SDNode *N = Op.getNode();
13190   SDLoc DL(N);
13191
13192   SmallVector<SDValue, 8> Opnds;
13193   DenseMap<SDValue, unsigned> VecInMap;
13194   SmallVector<SDValue, 8> VecIns;
13195   EVT VT = MVT::Other;
13196
13197   // Recognize a special case where a vector is casted into wide integer to
13198   // test all 0s.
13199   Opnds.push_back(N->getOperand(0));
13200   Opnds.push_back(N->getOperand(1));
13201
13202   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13203     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13204     // BFS traverse all OR'd operands.
13205     if (I->getOpcode() == ISD::OR) {
13206       Opnds.push_back(I->getOperand(0));
13207       Opnds.push_back(I->getOperand(1));
13208       // Re-evaluate the number of nodes to be traversed.
13209       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13210       continue;
13211     }
13212
13213     // Quit if a non-EXTRACT_VECTOR_ELT
13214     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13215       return SDValue();
13216
13217     // Quit if without a constant index.
13218     SDValue Idx = I->getOperand(1);
13219     if (!isa<ConstantSDNode>(Idx))
13220       return SDValue();
13221
13222     SDValue ExtractedFromVec = I->getOperand(0);
13223     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13224     if (M == VecInMap.end()) {
13225       VT = ExtractedFromVec.getValueType();
13226       // Quit if not 128/256-bit vector.
13227       if (!VT.is128BitVector() && !VT.is256BitVector())
13228         return SDValue();
13229       // Quit if not the same type.
13230       if (VecInMap.begin() != VecInMap.end() &&
13231           VT != VecInMap.begin()->first.getValueType())
13232         return SDValue();
13233       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13234       VecIns.push_back(ExtractedFromVec);
13235     }
13236     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13237   }
13238
13239   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13240          "Not extracted from 128-/256-bit vector.");
13241
13242   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13243
13244   for (DenseMap<SDValue, unsigned>::const_iterator
13245         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13246     // Quit if not all elements are used.
13247     if (I->second != FullMask)
13248       return SDValue();
13249   }
13250
13251   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13252
13253   // Cast all vectors into TestVT for PTEST.
13254   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13255     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13256
13257   // If more than one full vectors are evaluated, OR them first before PTEST.
13258   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13259     // Each iteration will OR 2 nodes and append the result until there is only
13260     // 1 node left, i.e. the final OR'd value of all vectors.
13261     SDValue LHS = VecIns[Slot];
13262     SDValue RHS = VecIns[Slot + 1];
13263     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13264   }
13265
13266   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13267                      VecIns.back(), VecIns.back());
13268 }
13269
13270 /// \brief return true if \c Op has a use that doesn't just read flags.
13271 static bool hasNonFlagsUse(SDValue Op) {
13272   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13273        ++UI) {
13274     SDNode *User = *UI;
13275     unsigned UOpNo = UI.getOperandNo();
13276     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13277       // Look pass truncate.
13278       UOpNo = User->use_begin().getOperandNo();
13279       User = *User->use_begin();
13280     }
13281
13282     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13283         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13284       return true;
13285   }
13286   return false;
13287 }
13288
13289 /// Emit nodes that will be selected as "test Op0,Op0", or something
13290 /// equivalent.
13291 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13292                                     SelectionDAG &DAG) const {
13293   if (Op.getValueType() == MVT::i1) {
13294     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13295     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13296                        DAG.getConstant(0, dl, MVT::i8));
13297   }
13298   // CF and OF aren't always set the way we want. Determine which
13299   // of these we need.
13300   bool NeedCF = false;
13301   bool NeedOF = false;
13302   switch (X86CC) {
13303   default: break;
13304   case X86::COND_A: case X86::COND_AE:
13305   case X86::COND_B: case X86::COND_BE:
13306     NeedCF = true;
13307     break;
13308   case X86::COND_G: case X86::COND_GE:
13309   case X86::COND_L: case X86::COND_LE:
13310   case X86::COND_O: case X86::COND_NO: {
13311     // Check if we really need to set the
13312     // Overflow flag. If NoSignedWrap is present
13313     // that is not actually needed.
13314     switch (Op->getOpcode()) {
13315     case ISD::ADD:
13316     case ISD::SUB:
13317     case ISD::MUL:
13318     case ISD::SHL: {
13319       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13320       if (BinNode->Flags.hasNoSignedWrap())
13321         break;
13322     }
13323     default:
13324       NeedOF = true;
13325       break;
13326     }
13327     break;
13328   }
13329   }
13330   // See if we can use the EFLAGS value from the operand instead of
13331   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13332   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13333   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13334     // Emit a CMP with 0, which is the TEST pattern.
13335     //if (Op.getValueType() == MVT::i1)
13336     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13337     //                     DAG.getConstant(0, MVT::i1));
13338     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13339                        DAG.getConstant(0, dl, Op.getValueType()));
13340   }
13341   unsigned Opcode = 0;
13342   unsigned NumOperands = 0;
13343
13344   // Truncate operations may prevent the merge of the SETCC instruction
13345   // and the arithmetic instruction before it. Attempt to truncate the operands
13346   // of the arithmetic instruction and use a reduced bit-width instruction.
13347   bool NeedTruncation = false;
13348   SDValue ArithOp = Op;
13349   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13350     SDValue Arith = Op->getOperand(0);
13351     // Both the trunc and the arithmetic op need to have one user each.
13352     if (Arith->hasOneUse())
13353       switch (Arith.getOpcode()) {
13354         default: break;
13355         case ISD::ADD:
13356         case ISD::SUB:
13357         case ISD::AND:
13358         case ISD::OR:
13359         case ISD::XOR: {
13360           NeedTruncation = true;
13361           ArithOp = Arith;
13362         }
13363       }
13364   }
13365
13366   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13367   // which may be the result of a CAST.  We use the variable 'Op', which is the
13368   // non-casted variable when we check for possible users.
13369   switch (ArithOp.getOpcode()) {
13370   case ISD::ADD:
13371     // Due to an isel shortcoming, be conservative if this add is likely to be
13372     // selected as part of a load-modify-store instruction. When the root node
13373     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13374     // uses of other nodes in the match, such as the ADD in this case. This
13375     // leads to the ADD being left around and reselected, with the result being
13376     // two adds in the output.  Alas, even if none our users are stores, that
13377     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13378     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13379     // climbing the DAG back to the root, and it doesn't seem to be worth the
13380     // effort.
13381     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13382          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13383       if (UI->getOpcode() != ISD::CopyToReg &&
13384           UI->getOpcode() != ISD::SETCC &&
13385           UI->getOpcode() != ISD::STORE)
13386         goto default_case;
13387
13388     if (ConstantSDNode *C =
13389         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13390       // An add of one will be selected as an INC.
13391       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13392         Opcode = X86ISD::INC;
13393         NumOperands = 1;
13394         break;
13395       }
13396
13397       // An add of negative one (subtract of one) will be selected as a DEC.
13398       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13399         Opcode = X86ISD::DEC;
13400         NumOperands = 1;
13401         break;
13402       }
13403     }
13404
13405     // Otherwise use a regular EFLAGS-setting add.
13406     Opcode = X86ISD::ADD;
13407     NumOperands = 2;
13408     break;
13409   case ISD::SHL:
13410   case ISD::SRL:
13411     // If we have a constant logical shift that's only used in a comparison
13412     // against zero turn it into an equivalent AND. This allows turning it into
13413     // a TEST instruction later.
13414     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13415         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13416       EVT VT = Op.getValueType();
13417       unsigned BitWidth = VT.getSizeInBits();
13418       unsigned ShAmt = Op->getConstantOperandVal(1);
13419       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13420         break;
13421       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13422                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13423                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13424       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13425         break;
13426       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13427                                 DAG.getConstant(Mask, dl, VT));
13428       DAG.ReplaceAllUsesWith(Op, New);
13429       Op = New;
13430     }
13431     break;
13432
13433   case ISD::AND:
13434     // If the primary and result isn't used, don't bother using X86ISD::AND,
13435     // because a TEST instruction will be better.
13436     if (!hasNonFlagsUse(Op))
13437       break;
13438     // FALL THROUGH
13439   case ISD::SUB:
13440   case ISD::OR:
13441   case ISD::XOR:
13442     // Due to the ISEL shortcoming noted above, be conservative if this op is
13443     // likely to be selected as part of a load-modify-store instruction.
13444     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13445            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13446       if (UI->getOpcode() == ISD::STORE)
13447         goto default_case;
13448
13449     // Otherwise use a regular EFLAGS-setting instruction.
13450     switch (ArithOp.getOpcode()) {
13451     default: llvm_unreachable("unexpected operator!");
13452     case ISD::SUB: Opcode = X86ISD::SUB; break;
13453     case ISD::XOR: Opcode = X86ISD::XOR; break;
13454     case ISD::AND: Opcode = X86ISD::AND; break;
13455     case ISD::OR: {
13456       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13457         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13458         if (EFLAGS.getNode())
13459           return EFLAGS;
13460       }
13461       Opcode = X86ISD::OR;
13462       break;
13463     }
13464     }
13465
13466     NumOperands = 2;
13467     break;
13468   case X86ISD::ADD:
13469   case X86ISD::SUB:
13470   case X86ISD::INC:
13471   case X86ISD::DEC:
13472   case X86ISD::OR:
13473   case X86ISD::XOR:
13474   case X86ISD::AND:
13475     return SDValue(Op.getNode(), 1);
13476   default:
13477   default_case:
13478     break;
13479   }
13480
13481   // If we found that truncation is beneficial, perform the truncation and
13482   // update 'Op'.
13483   if (NeedTruncation) {
13484     EVT VT = Op.getValueType();
13485     SDValue WideVal = Op->getOperand(0);
13486     EVT WideVT = WideVal.getValueType();
13487     unsigned ConvertedOp = 0;
13488     // Use a target machine opcode to prevent further DAGCombine
13489     // optimizations that may separate the arithmetic operations
13490     // from the setcc node.
13491     switch (WideVal.getOpcode()) {
13492       default: break;
13493       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13494       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13495       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13496       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13497       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13498     }
13499
13500     if (ConvertedOp) {
13501       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13502       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13503         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13504         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13505         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13506       }
13507     }
13508   }
13509
13510   if (Opcode == 0)
13511     // Emit a CMP with 0, which is the TEST pattern.
13512     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13513                        DAG.getConstant(0, dl, Op.getValueType()));
13514
13515   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13516   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13517
13518   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13519   DAG.ReplaceAllUsesWith(Op, New);
13520   return SDValue(New.getNode(), 1);
13521 }
13522
13523 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13524 /// equivalent.
13525 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13526                                    SDLoc dl, SelectionDAG &DAG) const {
13527   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13528     if (C->getAPIntValue() == 0)
13529       return EmitTest(Op0, X86CC, dl, DAG);
13530
13531      if (Op0.getValueType() == MVT::i1)
13532        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13533   }
13534
13535   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13536        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13537     // Do the comparison at i32 if it's smaller, besides the Atom case.
13538     // This avoids subregister aliasing issues. Keep the smaller reference
13539     // if we're optimizing for size, however, as that'll allow better folding
13540     // of memory operations.
13541     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13542         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13543         !Subtarget->isAtom()) {
13544       unsigned ExtendOp =
13545           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13546       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13547       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13548     }
13549     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13550     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13551     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13552                               Op0, Op1);
13553     return SDValue(Sub.getNode(), 1);
13554   }
13555   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13556 }
13557
13558 /// Convert a comparison if required by the subtarget.
13559 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13560                                                  SelectionDAG &DAG) const {
13561   // If the subtarget does not support the FUCOMI instruction, floating-point
13562   // comparisons have to be converted.
13563   if (Subtarget->hasCMov() ||
13564       Cmp.getOpcode() != X86ISD::CMP ||
13565       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13566       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13567     return Cmp;
13568
13569   // The instruction selector will select an FUCOM instruction instead of
13570   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13571   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13572   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13573   SDLoc dl(Cmp);
13574   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13575   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13576   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13577                             DAG.getConstant(8, dl, MVT::i8));
13578   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13579   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13580 }
13581
13582 /// The minimum architected relative accuracy is 2^-12. We need one
13583 /// Newton-Raphson step to have a good float result (24 bits of precision).
13584 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13585                                             DAGCombinerInfo &DCI,
13586                                             unsigned &RefinementSteps,
13587                                             bool &UseOneConstNR) const {
13588   EVT VT = Op.getValueType();
13589   const char *RecipOp;
13590
13591   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13592   // TODO: Add support for AVX512 (v16f32).
13593   // It is likely not profitable to do this for f64 because a double-precision
13594   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13595   // instructions: convert to single, rsqrtss, convert back to double, refine
13596   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13597   // along with FMA, this could be a throughput win.
13598   if (VT == MVT::f32 && Subtarget->hasSSE1())
13599     RecipOp = "sqrtf";
13600   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13601            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13602     RecipOp = "vec-sqrtf";
13603   else
13604     return SDValue();
13605
13606   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13607   if (!Recips.isEnabled(RecipOp))
13608     return SDValue();
13609
13610   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13611   UseOneConstNR = false;
13612   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13613 }
13614
13615 /// The minimum architected relative accuracy is 2^-12. We need one
13616 /// Newton-Raphson step to have a good float result (24 bits of precision).
13617 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13618                                             DAGCombinerInfo &DCI,
13619                                             unsigned &RefinementSteps) const {
13620   EVT VT = Op.getValueType();
13621   const char *RecipOp;
13622
13623   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13624   // TODO: Add support for AVX512 (v16f32).
13625   // It is likely not profitable to do this for f64 because a double-precision
13626   // reciprocal estimate with refinement on x86 prior to FMA requires
13627   // 15 instructions: convert to single, rcpss, convert back to double, refine
13628   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13629   // along with FMA, this could be a throughput win.
13630   if (VT == MVT::f32 && Subtarget->hasSSE1())
13631     RecipOp = "divf";
13632   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13633            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13634     RecipOp = "vec-divf";
13635   else
13636     return SDValue();
13637
13638   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13639   if (!Recips.isEnabled(RecipOp))
13640     return SDValue();
13641
13642   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13643   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13644 }
13645
13646 /// If we have at least two divisions that use the same divisor, convert to
13647 /// multplication by a reciprocal. This may need to be adjusted for a given
13648 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13649 /// This is because we still need one division to calculate the reciprocal and
13650 /// then we need two multiplies by that reciprocal as replacements for the
13651 /// original divisions.
13652 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13653   return 2;
13654 }
13655
13656 static bool isAllOnes(SDValue V) {
13657   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13658   return C && C->isAllOnesValue();
13659 }
13660
13661 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13662 /// if it's possible.
13663 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13664                                      SDLoc dl, SelectionDAG &DAG) const {
13665   SDValue Op0 = And.getOperand(0);
13666   SDValue Op1 = And.getOperand(1);
13667   if (Op0.getOpcode() == ISD::TRUNCATE)
13668     Op0 = Op0.getOperand(0);
13669   if (Op1.getOpcode() == ISD::TRUNCATE)
13670     Op1 = Op1.getOperand(0);
13671
13672   SDValue LHS, RHS;
13673   if (Op1.getOpcode() == ISD::SHL)
13674     std::swap(Op0, Op1);
13675   if (Op0.getOpcode() == ISD::SHL) {
13676     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13677       if (And00C->getZExtValue() == 1) {
13678         // If we looked past a truncate, check that it's only truncating away
13679         // known zeros.
13680         unsigned BitWidth = Op0.getValueSizeInBits();
13681         unsigned AndBitWidth = And.getValueSizeInBits();
13682         if (BitWidth > AndBitWidth) {
13683           APInt Zeros, Ones;
13684           DAG.computeKnownBits(Op0, Zeros, Ones);
13685           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13686             return SDValue();
13687         }
13688         LHS = Op1;
13689         RHS = Op0.getOperand(1);
13690       }
13691   } else if (Op1.getOpcode() == ISD::Constant) {
13692     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13693     uint64_t AndRHSVal = AndRHS->getZExtValue();
13694     SDValue AndLHS = Op0;
13695
13696     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13697       LHS = AndLHS.getOperand(0);
13698       RHS = AndLHS.getOperand(1);
13699     }
13700
13701     // Use BT if the immediate can't be encoded in a TEST instruction.
13702     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13703       LHS = AndLHS;
13704       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13705     }
13706   }
13707
13708   if (LHS.getNode()) {
13709     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13710     // instruction.  Since the shift amount is in-range-or-undefined, we know
13711     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13712     // the encoding for the i16 version is larger than the i32 version.
13713     // Also promote i16 to i32 for performance / code size reason.
13714     if (LHS.getValueType() == MVT::i8 ||
13715         LHS.getValueType() == MVT::i16)
13716       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13717
13718     // If the operand types disagree, extend the shift amount to match.  Since
13719     // BT ignores high bits (like shifts) we can use anyextend.
13720     if (LHS.getValueType() != RHS.getValueType())
13721       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13722
13723     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13724     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13725     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13726                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13727   }
13728
13729   return SDValue();
13730 }
13731
13732 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13733 /// mask CMPs.
13734 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13735                               SDValue &Op1) {
13736   unsigned SSECC;
13737   bool Swap = false;
13738
13739   // SSE Condition code mapping:
13740   //  0 - EQ
13741   //  1 - LT
13742   //  2 - LE
13743   //  3 - UNORD
13744   //  4 - NEQ
13745   //  5 - NLT
13746   //  6 - NLE
13747   //  7 - ORD
13748   switch (SetCCOpcode) {
13749   default: llvm_unreachable("Unexpected SETCC condition");
13750   case ISD::SETOEQ:
13751   case ISD::SETEQ:  SSECC = 0; break;
13752   case ISD::SETOGT:
13753   case ISD::SETGT:  Swap = true; // Fallthrough
13754   case ISD::SETLT:
13755   case ISD::SETOLT: SSECC = 1; break;
13756   case ISD::SETOGE:
13757   case ISD::SETGE:  Swap = true; // Fallthrough
13758   case ISD::SETLE:
13759   case ISD::SETOLE: SSECC = 2; break;
13760   case ISD::SETUO:  SSECC = 3; break;
13761   case ISD::SETUNE:
13762   case ISD::SETNE:  SSECC = 4; break;
13763   case ISD::SETULE: Swap = true; // Fallthrough
13764   case ISD::SETUGE: SSECC = 5; break;
13765   case ISD::SETULT: Swap = true; // Fallthrough
13766   case ISD::SETUGT: SSECC = 6; break;
13767   case ISD::SETO:   SSECC = 7; break;
13768   case ISD::SETUEQ:
13769   case ISD::SETONE: SSECC = 8; break;
13770   }
13771   if (Swap)
13772     std::swap(Op0, Op1);
13773
13774   return SSECC;
13775 }
13776
13777 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13778 // ones, and then concatenate the result back.
13779 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13780   MVT VT = Op.getSimpleValueType();
13781
13782   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13783          "Unsupported value type for operation");
13784
13785   unsigned NumElems = VT.getVectorNumElements();
13786   SDLoc dl(Op);
13787   SDValue CC = Op.getOperand(2);
13788
13789   // Extract the LHS vectors
13790   SDValue LHS = Op.getOperand(0);
13791   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13792   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13793
13794   // Extract the RHS vectors
13795   SDValue RHS = Op.getOperand(1);
13796   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13797   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13798
13799   // Issue the operation on the smaller types and concatenate the result back
13800   MVT EltVT = VT.getVectorElementType();
13801   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13802   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13803                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13804                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13805 }
13806
13807 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13808   SDValue Op0 = Op.getOperand(0);
13809   SDValue Op1 = Op.getOperand(1);
13810   SDValue CC = Op.getOperand(2);
13811   MVT VT = Op.getSimpleValueType();
13812   SDLoc dl(Op);
13813
13814   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13815          "Unexpected type for boolean compare operation");
13816   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13817   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13818                                DAG.getConstant(-1, dl, VT));
13819   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13820                                DAG.getConstant(-1, dl, VT));
13821   switch (SetCCOpcode) {
13822   default: llvm_unreachable("Unexpected SETCC condition");
13823   case ISD::SETEQ:
13824     // (x == y) -> ~(x ^ y)
13825     return DAG.getNode(ISD::XOR, dl, VT,
13826                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13827                        DAG.getConstant(-1, dl, VT));
13828   case ISD::SETNE:
13829     // (x != y) -> (x ^ y)
13830     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13831   case ISD::SETUGT:
13832   case ISD::SETGT:
13833     // (x > y) -> (x & ~y)
13834     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13835   case ISD::SETULT:
13836   case ISD::SETLT:
13837     // (x < y) -> (~x & y)
13838     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13839   case ISD::SETULE:
13840   case ISD::SETLE:
13841     // (x <= y) -> (~x | y)
13842     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13843   case ISD::SETUGE:
13844   case ISD::SETGE:
13845     // (x >=y) -> (x | ~y)
13846     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13847   }
13848 }
13849
13850 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13851                                      const X86Subtarget *Subtarget) {
13852   SDValue Op0 = Op.getOperand(0);
13853   SDValue Op1 = Op.getOperand(1);
13854   SDValue CC = Op.getOperand(2);
13855   MVT VT = Op.getSimpleValueType();
13856   SDLoc dl(Op);
13857
13858   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13859          Op.getValueType().getScalarType() == MVT::i1 &&
13860          "Cannot set masked compare for this operation");
13861
13862   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13863   unsigned  Opc = 0;
13864   bool Unsigned = false;
13865   bool Swap = false;
13866   unsigned SSECC;
13867   switch (SetCCOpcode) {
13868   default: llvm_unreachable("Unexpected SETCC condition");
13869   case ISD::SETNE:  SSECC = 4; break;
13870   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13871   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13872   case ISD::SETLT:  Swap = true; //fall-through
13873   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13874   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13875   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13876   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13877   case ISD::SETULE: Unsigned = true; //fall-through
13878   case ISD::SETLE:  SSECC = 2; break;
13879   }
13880
13881   if (Swap)
13882     std::swap(Op0, Op1);
13883   if (Opc)
13884     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13885   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13886   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13887                      DAG.getConstant(SSECC, dl, MVT::i8));
13888 }
13889
13890 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13891 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13892 /// return an empty value.
13893 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13894 {
13895   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13896   if (!BV)
13897     return SDValue();
13898
13899   MVT VT = Op1.getSimpleValueType();
13900   MVT EVT = VT.getVectorElementType();
13901   unsigned n = VT.getVectorNumElements();
13902   SmallVector<SDValue, 8> ULTOp1;
13903
13904   for (unsigned i = 0; i < n; ++i) {
13905     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13906     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13907       return SDValue();
13908
13909     // Avoid underflow.
13910     APInt Val = Elt->getAPIntValue();
13911     if (Val == 0)
13912       return SDValue();
13913
13914     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13915   }
13916
13917   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13918 }
13919
13920 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13921                            SelectionDAG &DAG) {
13922   SDValue Op0 = Op.getOperand(0);
13923   SDValue Op1 = Op.getOperand(1);
13924   SDValue CC = Op.getOperand(2);
13925   MVT VT = Op.getSimpleValueType();
13926   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13927   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13928   SDLoc dl(Op);
13929
13930   if (isFP) {
13931 #ifndef NDEBUG
13932     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13933     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13934 #endif
13935
13936     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13937     unsigned Opc = X86ISD::CMPP;
13938     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13939       assert(VT.getVectorNumElements() <= 16);
13940       Opc = X86ISD::CMPM;
13941     }
13942     // In the two special cases we can't handle, emit two comparisons.
13943     if (SSECC == 8) {
13944       unsigned CC0, CC1;
13945       unsigned CombineOpc;
13946       if (SetCCOpcode == ISD::SETUEQ) {
13947         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13948       } else {
13949         assert(SetCCOpcode == ISD::SETONE);
13950         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13951       }
13952
13953       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13954                                  DAG.getConstant(CC0, dl, MVT::i8));
13955       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13956                                  DAG.getConstant(CC1, dl, MVT::i8));
13957       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13958     }
13959     // Handle all other FP comparisons here.
13960     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13961                        DAG.getConstant(SSECC, dl, MVT::i8));
13962   }
13963
13964   // Break 256-bit integer vector compare into smaller ones.
13965   if (VT.is256BitVector() && !Subtarget->hasInt256())
13966     return Lower256IntVSETCC(Op, DAG);
13967
13968   EVT OpVT = Op1.getValueType();
13969   if (OpVT.getVectorElementType() == MVT::i1)
13970     return LowerBoolVSETCC_AVX512(Op, DAG);
13971
13972   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13973   if (Subtarget->hasAVX512()) {
13974     if (Op1.getValueType().is512BitVector() ||
13975         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13976         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13977       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13978
13979     // In AVX-512 architecture setcc returns mask with i1 elements,
13980     // But there is no compare instruction for i8 and i16 elements in KNL.
13981     // We are not talking about 512-bit operands in this case, these
13982     // types are illegal.
13983     if (MaskResult &&
13984         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13985          OpVT.getVectorElementType().getSizeInBits() >= 8))
13986       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13987                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13988   }
13989
13990   // We are handling one of the integer comparisons here.  Since SSE only has
13991   // GT and EQ comparisons for integer, swapping operands and multiple
13992   // operations may be required for some comparisons.
13993   unsigned Opc;
13994   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13995   bool Subus = false;
13996
13997   switch (SetCCOpcode) {
13998   default: llvm_unreachable("Unexpected SETCC condition");
13999   case ISD::SETNE:  Invert = true;
14000   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14001   case ISD::SETLT:  Swap = true;
14002   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14003   case ISD::SETGE:  Swap = true;
14004   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14005                     Invert = true; break;
14006   case ISD::SETULT: Swap = true;
14007   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14008                     FlipSigns = true; break;
14009   case ISD::SETUGE: Swap = true;
14010   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14011                     FlipSigns = true; Invert = true; break;
14012   }
14013
14014   // Special case: Use min/max operations for SETULE/SETUGE
14015   MVT VET = VT.getVectorElementType();
14016   bool hasMinMax =
14017        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14018     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14019
14020   if (hasMinMax) {
14021     switch (SetCCOpcode) {
14022     default: break;
14023     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14024     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14025     }
14026
14027     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14028   }
14029
14030   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14031   if (!MinMax && hasSubus) {
14032     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14033     // Op0 u<= Op1:
14034     //   t = psubus Op0, Op1
14035     //   pcmpeq t, <0..0>
14036     switch (SetCCOpcode) {
14037     default: break;
14038     case ISD::SETULT: {
14039       // If the comparison is against a constant we can turn this into a
14040       // setule.  With psubus, setule does not require a swap.  This is
14041       // beneficial because the constant in the register is no longer
14042       // destructed as the destination so it can be hoisted out of a loop.
14043       // Only do this pre-AVX since vpcmp* is no longer destructive.
14044       if (Subtarget->hasAVX())
14045         break;
14046       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14047       if (ULEOp1.getNode()) {
14048         Op1 = ULEOp1;
14049         Subus = true; Invert = false; Swap = false;
14050       }
14051       break;
14052     }
14053     // Psubus is better than flip-sign because it requires no inversion.
14054     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14055     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14056     }
14057
14058     if (Subus) {
14059       Opc = X86ISD::SUBUS;
14060       FlipSigns = false;
14061     }
14062   }
14063
14064   if (Swap)
14065     std::swap(Op0, Op1);
14066
14067   // Check that the operation in question is available (most are plain SSE2,
14068   // but PCMPGTQ and PCMPEQQ have different requirements).
14069   if (VT == MVT::v2i64) {
14070     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14071       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14072
14073       // First cast everything to the right type.
14074       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14075       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14076
14077       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14078       // bits of the inputs before performing those operations. The lower
14079       // compare is always unsigned.
14080       SDValue SB;
14081       if (FlipSigns) {
14082         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14083       } else {
14084         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14085         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14086         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14087                          Sign, Zero, Sign, Zero);
14088       }
14089       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14090       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14091
14092       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14093       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14094       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14095
14096       // Create masks for only the low parts/high parts of the 64 bit integers.
14097       static const int MaskHi[] = { 1, 1, 3, 3 };
14098       static const int MaskLo[] = { 0, 0, 2, 2 };
14099       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14100       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14101       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14102
14103       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14104       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14105
14106       if (Invert)
14107         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14108
14109       return DAG.getBitcast(VT, Result);
14110     }
14111
14112     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14113       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14114       // pcmpeqd + pshufd + pand.
14115       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14116
14117       // First cast everything to the right type.
14118       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14119       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14120
14121       // Do the compare.
14122       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14123
14124       // Make sure the lower and upper halves are both all-ones.
14125       static const int Mask[] = { 1, 0, 3, 2 };
14126       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14127       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14128
14129       if (Invert)
14130         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14131
14132       return DAG.getBitcast(VT, Result);
14133     }
14134   }
14135
14136   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14137   // bits of the inputs before performing those operations.
14138   if (FlipSigns) {
14139     EVT EltVT = VT.getVectorElementType();
14140     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14141                                  VT);
14142     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14143     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14144   }
14145
14146   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14147
14148   // If the logical-not of the result is required, perform that now.
14149   if (Invert)
14150     Result = DAG.getNOT(dl, Result, VT);
14151
14152   if (MinMax)
14153     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14154
14155   if (Subus)
14156     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14157                          getZeroVector(VT, Subtarget, DAG, dl));
14158
14159   return Result;
14160 }
14161
14162 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14163
14164   MVT VT = Op.getSimpleValueType();
14165
14166   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14167
14168   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14169          && "SetCC type must be 8-bit or 1-bit integer");
14170   SDValue Op0 = Op.getOperand(0);
14171   SDValue Op1 = Op.getOperand(1);
14172   SDLoc dl(Op);
14173   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14174
14175   // Optimize to BT if possible.
14176   // Lower (X & (1 << N)) == 0 to BT(X, N).
14177   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14178   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14179   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14180       Op1.getOpcode() == ISD::Constant &&
14181       cast<ConstantSDNode>(Op1)->isNullValue() &&
14182       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14183     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14184     if (NewSetCC.getNode()) {
14185       if (VT == MVT::i1)
14186         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14187       return NewSetCC;
14188     }
14189   }
14190
14191   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14192   // these.
14193   if (Op1.getOpcode() == ISD::Constant &&
14194       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14195        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14196       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14197
14198     // If the input is a setcc, then reuse the input setcc or use a new one with
14199     // the inverted condition.
14200     if (Op0.getOpcode() == X86ISD::SETCC) {
14201       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14202       bool Invert = (CC == ISD::SETNE) ^
14203         cast<ConstantSDNode>(Op1)->isNullValue();
14204       if (!Invert)
14205         return Op0;
14206
14207       CCode = X86::GetOppositeBranchCondition(CCode);
14208       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14209                                   DAG.getConstant(CCode, dl, MVT::i8),
14210                                   Op0.getOperand(1));
14211       if (VT == MVT::i1)
14212         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14213       return SetCC;
14214     }
14215   }
14216   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14217       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14218       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14219
14220     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14221     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14222   }
14223
14224   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14225   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14226   if (X86CC == X86::COND_INVALID)
14227     return SDValue();
14228
14229   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14230   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14231   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14232                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14233   if (VT == MVT::i1)
14234     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14235   return SetCC;
14236 }
14237
14238 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14239 static bool isX86LogicalCmp(SDValue Op) {
14240   unsigned Opc = Op.getNode()->getOpcode();
14241   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14242       Opc == X86ISD::SAHF)
14243     return true;
14244   if (Op.getResNo() == 1 &&
14245       (Opc == X86ISD::ADD ||
14246        Opc == X86ISD::SUB ||
14247        Opc == X86ISD::ADC ||
14248        Opc == X86ISD::SBB ||
14249        Opc == X86ISD::SMUL ||
14250        Opc == X86ISD::UMUL ||
14251        Opc == X86ISD::INC ||
14252        Opc == X86ISD::DEC ||
14253        Opc == X86ISD::OR ||
14254        Opc == X86ISD::XOR ||
14255        Opc == X86ISD::AND))
14256     return true;
14257
14258   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14259     return true;
14260
14261   return false;
14262 }
14263
14264 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14265   if (V.getOpcode() != ISD::TRUNCATE)
14266     return false;
14267
14268   SDValue VOp0 = V.getOperand(0);
14269   unsigned InBits = VOp0.getValueSizeInBits();
14270   unsigned Bits = V.getValueSizeInBits();
14271   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14272 }
14273
14274 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14275   bool addTest = true;
14276   SDValue Cond  = Op.getOperand(0);
14277   SDValue Op1 = Op.getOperand(1);
14278   SDValue Op2 = Op.getOperand(2);
14279   SDLoc DL(Op);
14280   EVT VT = Op1.getValueType();
14281   SDValue CC;
14282
14283   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14284   // are available or VBLENDV if AVX is available.
14285   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14286   if (Cond.getOpcode() == ISD::SETCC &&
14287       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14288        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14289       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14290     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14291     int SSECC = translateX86FSETCC(
14292         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14293
14294     if (SSECC != 8) {
14295       if (Subtarget->hasAVX512()) {
14296         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14297                                   DAG.getConstant(SSECC, DL, MVT::i8));
14298         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14299       }
14300
14301       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14302                                 DAG.getConstant(SSECC, DL, MVT::i8));
14303
14304       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14305       // of 3 logic instructions for size savings and potentially speed.
14306       // Unfortunately, there is no scalar form of VBLENDV.
14307
14308       // If either operand is a constant, don't try this. We can expect to
14309       // optimize away at least one of the logic instructions later in that
14310       // case, so that sequence would be faster than a variable blend.
14311
14312       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14313       // uses XMM0 as the selection register. That may need just as many
14314       // instructions as the AND/ANDN/OR sequence due to register moves, so
14315       // don't bother.
14316
14317       if (Subtarget->hasAVX() &&
14318           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14319
14320         // Convert to vectors, do a VSELECT, and convert back to scalar.
14321         // All of the conversions should be optimized away.
14322
14323         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14324         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14325         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14326         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14327
14328         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14329         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14330
14331         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14332
14333         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14334                            VSel, DAG.getIntPtrConstant(0, DL));
14335       }
14336       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14337       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14338       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14339     }
14340   }
14341
14342   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14343     SDValue Op1Scalar;
14344     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14345       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14346     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14347       Op1Scalar = Op1.getOperand(0);
14348     SDValue Op2Scalar;
14349     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14350       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14351     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14352       Op2Scalar = Op2.getOperand(0);
14353     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14354       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14355                                       Op1Scalar.getValueType(),
14356                                       Cond, Op1Scalar, Op2Scalar);
14357       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14358         return DAG.getBitcast(VT, newSelect);
14359       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14360       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14361                          DAG.getIntPtrConstant(0, DL));
14362     }
14363   }
14364
14365   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14366     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14367     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14368                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14369     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14370                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14371     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14372                                     Cond, Op1, Op2);
14373     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14374   }
14375
14376   if (Cond.getOpcode() == ISD::SETCC) {
14377     SDValue NewCond = LowerSETCC(Cond, DAG);
14378     if (NewCond.getNode())
14379       Cond = NewCond;
14380   }
14381
14382   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14383   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14384   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14385   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14386   if (Cond.getOpcode() == X86ISD::SETCC &&
14387       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14388       isZero(Cond.getOperand(1).getOperand(1))) {
14389     SDValue Cmp = Cond.getOperand(1);
14390
14391     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14392
14393     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14394         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14395       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14396
14397       SDValue CmpOp0 = Cmp.getOperand(0);
14398       // Apply further optimizations for special cases
14399       // (select (x != 0), -1, 0) -> neg & sbb
14400       // (select (x == 0), 0, -1) -> neg & sbb
14401       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14402         if (YC->isNullValue() &&
14403             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14404           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14405           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14406                                     DAG.getConstant(0, DL,
14407                                                     CmpOp0.getValueType()),
14408                                     CmpOp0);
14409           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14410                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14411                                     SDValue(Neg.getNode(), 1));
14412           return Res;
14413         }
14414
14415       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14416                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14417       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14418
14419       SDValue Res =   // Res = 0 or -1.
14420         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14421                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14422
14423       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14424         Res = DAG.getNOT(DL, Res, Res.getValueType());
14425
14426       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14427       if (!N2C || !N2C->isNullValue())
14428         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14429       return Res;
14430     }
14431   }
14432
14433   // Look past (and (setcc_carry (cmp ...)), 1).
14434   if (Cond.getOpcode() == ISD::AND &&
14435       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14436     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14437     if (C && C->getAPIntValue() == 1)
14438       Cond = Cond.getOperand(0);
14439   }
14440
14441   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14442   // setting operand in place of the X86ISD::SETCC.
14443   unsigned CondOpcode = Cond.getOpcode();
14444   if (CondOpcode == X86ISD::SETCC ||
14445       CondOpcode == X86ISD::SETCC_CARRY) {
14446     CC = Cond.getOperand(0);
14447
14448     SDValue Cmp = Cond.getOperand(1);
14449     unsigned Opc = Cmp.getOpcode();
14450     MVT VT = Op.getSimpleValueType();
14451
14452     bool IllegalFPCMov = false;
14453     if (VT.isFloatingPoint() && !VT.isVector() &&
14454         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14455       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14456
14457     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14458         Opc == X86ISD::BT) { // FIXME
14459       Cond = Cmp;
14460       addTest = false;
14461     }
14462   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14463              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14464              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14465               Cond.getOperand(0).getValueType() != MVT::i8)) {
14466     SDValue LHS = Cond.getOperand(0);
14467     SDValue RHS = Cond.getOperand(1);
14468     unsigned X86Opcode;
14469     unsigned X86Cond;
14470     SDVTList VTs;
14471     switch (CondOpcode) {
14472     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14473     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14474     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14475     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14476     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14477     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14478     default: llvm_unreachable("unexpected overflowing operator");
14479     }
14480     if (CondOpcode == ISD::UMULO)
14481       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14482                           MVT::i32);
14483     else
14484       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14485
14486     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14487
14488     if (CondOpcode == ISD::UMULO)
14489       Cond = X86Op.getValue(2);
14490     else
14491       Cond = X86Op.getValue(1);
14492
14493     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14494     addTest = false;
14495   }
14496
14497   if (addTest) {
14498     // Look past the truncate if the high bits are known zero.
14499     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14500       Cond = Cond.getOperand(0);
14501
14502     // We know the result of AND is compared against zero. Try to match
14503     // it to BT.
14504     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14505       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14506       if (NewSetCC.getNode()) {
14507         CC = NewSetCC.getOperand(0);
14508         Cond = NewSetCC.getOperand(1);
14509         addTest = false;
14510       }
14511     }
14512   }
14513
14514   if (addTest) {
14515     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14516     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14517   }
14518
14519   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14520   // a <  b ?  0 : -1 -> RES = setcc_carry
14521   // a >= b ? -1 :  0 -> RES = setcc_carry
14522   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14523   if (Cond.getOpcode() == X86ISD::SUB) {
14524     Cond = ConvertCmpIfNecessary(Cond, DAG);
14525     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14526
14527     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14528         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14529       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14530                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14531                                 Cond);
14532       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14533         return DAG.getNOT(DL, Res, Res.getValueType());
14534       return Res;
14535     }
14536   }
14537
14538   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14539   // widen the cmov and push the truncate through. This avoids introducing a new
14540   // branch during isel and doesn't add any extensions.
14541   if (Op.getValueType() == MVT::i8 &&
14542       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14543     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14544     if (T1.getValueType() == T2.getValueType() &&
14545         // Blacklist CopyFromReg to avoid partial register stalls.
14546         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14547       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14548       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14549       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14550     }
14551   }
14552
14553   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14554   // condition is true.
14555   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14556   SDValue Ops[] = { Op2, Op1, CC, Cond };
14557   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14558 }
14559
14560 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14561                                        const X86Subtarget *Subtarget,
14562                                        SelectionDAG &DAG) {
14563   MVT VT = Op->getSimpleValueType(0);
14564   SDValue In = Op->getOperand(0);
14565   MVT InVT = In.getSimpleValueType();
14566   MVT VTElt = VT.getVectorElementType();
14567   MVT InVTElt = InVT.getVectorElementType();
14568   SDLoc dl(Op);
14569
14570   // SKX processor
14571   if ((InVTElt == MVT::i1) &&
14572       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14573         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14574
14575        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14576         VTElt.getSizeInBits() <= 16)) ||
14577
14578        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14579         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14580
14581        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14582         VTElt.getSizeInBits() >= 32))))
14583     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14584
14585   unsigned int NumElts = VT.getVectorNumElements();
14586
14587   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14588     return SDValue();
14589
14590   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14591     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14592       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14593     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14594   }
14595
14596   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14597   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14598   SDValue NegOne =
14599    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14600                    ExtVT);
14601   SDValue Zero =
14602    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14603
14604   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14605   if (VT.is512BitVector())
14606     return V;
14607   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14608 }
14609
14610 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14611                                              const X86Subtarget *Subtarget,
14612                                              SelectionDAG &DAG) {
14613   SDValue In = Op->getOperand(0);
14614   MVT VT = Op->getSimpleValueType(0);
14615   MVT InVT = In.getSimpleValueType();
14616   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14617
14618   MVT InSVT = InVT.getScalarType();
14619   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14620
14621   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14622     return SDValue();
14623   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14624     return SDValue();
14625
14626   SDLoc dl(Op);
14627
14628   // SSE41 targets can use the pmovsx* instructions directly.
14629   if (Subtarget->hasSSE41())
14630     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14631
14632   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14633   SDValue Curr = In;
14634   MVT CurrVT = InVT;
14635
14636   // As SRAI is only available on i16/i32 types, we expand only up to i32
14637   // and handle i64 separately.
14638   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14639     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14640     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14641     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14642     Curr = DAG.getBitcast(CurrVT, Curr);
14643   }
14644
14645   SDValue SignExt = Curr;
14646   if (CurrVT != InVT) {
14647     unsigned SignExtShift =
14648         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14649     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14650                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14651   }
14652
14653   if (CurrVT == VT)
14654     return SignExt;
14655
14656   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14657     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14658                                DAG.getConstant(31, dl, MVT::i8));
14659     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14660     return DAG.getBitcast(VT, Ext);
14661   }
14662
14663   return SDValue();
14664 }
14665
14666 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14667                                 SelectionDAG &DAG) {
14668   MVT VT = Op->getSimpleValueType(0);
14669   SDValue In = Op->getOperand(0);
14670   MVT InVT = In.getSimpleValueType();
14671   SDLoc dl(Op);
14672
14673   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14674     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14675
14676   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14677       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14678       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14679     return SDValue();
14680
14681   if (Subtarget->hasInt256())
14682     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14683
14684   // Optimize vectors in AVX mode
14685   // Sign extend  v8i16 to v8i32 and
14686   //              v4i32 to v4i64
14687   //
14688   // Divide input vector into two parts
14689   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14690   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14691   // concat the vectors to original VT
14692
14693   unsigned NumElems = InVT.getVectorNumElements();
14694   SDValue Undef = DAG.getUNDEF(InVT);
14695
14696   SmallVector<int,8> ShufMask1(NumElems, -1);
14697   for (unsigned i = 0; i != NumElems/2; ++i)
14698     ShufMask1[i] = i;
14699
14700   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14701
14702   SmallVector<int,8> ShufMask2(NumElems, -1);
14703   for (unsigned i = 0; i != NumElems/2; ++i)
14704     ShufMask2[i] = i + NumElems/2;
14705
14706   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14707
14708   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14709                                 VT.getVectorNumElements()/2);
14710
14711   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14712   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14713
14714   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14715 }
14716
14717 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14718 // may emit an illegal shuffle but the expansion is still better than scalar
14719 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14720 // we'll emit a shuffle and a arithmetic shift.
14721 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14722 // TODO: It is possible to support ZExt by zeroing the undef values during
14723 // the shuffle phase or after the shuffle.
14724 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14725                                  SelectionDAG &DAG) {
14726   MVT RegVT = Op.getSimpleValueType();
14727   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14728   assert(RegVT.isInteger() &&
14729          "We only custom lower integer vector sext loads.");
14730
14731   // Nothing useful we can do without SSE2 shuffles.
14732   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14733
14734   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14735   SDLoc dl(Ld);
14736   EVT MemVT = Ld->getMemoryVT();
14737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14738   unsigned RegSz = RegVT.getSizeInBits();
14739
14740   ISD::LoadExtType Ext = Ld->getExtensionType();
14741
14742   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14743          && "Only anyext and sext are currently implemented.");
14744   assert(MemVT != RegVT && "Cannot extend to the same type");
14745   assert(MemVT.isVector() && "Must load a vector from memory");
14746
14747   unsigned NumElems = RegVT.getVectorNumElements();
14748   unsigned MemSz = MemVT.getSizeInBits();
14749   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14750
14751   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14752     // The only way in which we have a legal 256-bit vector result but not the
14753     // integer 256-bit operations needed to directly lower a sextload is if we
14754     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14755     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14756     // correctly legalized. We do this late to allow the canonical form of
14757     // sextload to persist throughout the rest of the DAG combiner -- it wants
14758     // to fold together any extensions it can, and so will fuse a sign_extend
14759     // of an sextload into a sextload targeting a wider value.
14760     SDValue Load;
14761     if (MemSz == 128) {
14762       // Just switch this to a normal load.
14763       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14764                                        "it must be a legal 128-bit vector "
14765                                        "type!");
14766       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14767                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14768                   Ld->isInvariant(), Ld->getAlignment());
14769     } else {
14770       assert(MemSz < 128 &&
14771              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14772       // Do an sext load to a 128-bit vector type. We want to use the same
14773       // number of elements, but elements half as wide. This will end up being
14774       // recursively lowered by this routine, but will succeed as we definitely
14775       // have all the necessary features if we're using AVX1.
14776       EVT HalfEltVT =
14777           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14778       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14779       Load =
14780           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14781                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14782                          Ld->isNonTemporal(), Ld->isInvariant(),
14783                          Ld->getAlignment());
14784     }
14785
14786     // Replace chain users with the new chain.
14787     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14788     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14789
14790     // Finally, do a normal sign-extend to the desired register.
14791     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14792   }
14793
14794   // All sizes must be a power of two.
14795   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14796          "Non-power-of-two elements are not custom lowered!");
14797
14798   // Attempt to load the original value using scalar loads.
14799   // Find the largest scalar type that divides the total loaded size.
14800   MVT SclrLoadTy = MVT::i8;
14801   for (MVT Tp : MVT::integer_valuetypes()) {
14802     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14803       SclrLoadTy = Tp;
14804     }
14805   }
14806
14807   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14808   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14809       (64 <= MemSz))
14810     SclrLoadTy = MVT::f64;
14811
14812   // Calculate the number of scalar loads that we need to perform
14813   // in order to load our vector from memory.
14814   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14815
14816   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14817          "Can only lower sext loads with a single scalar load!");
14818
14819   unsigned loadRegZize = RegSz;
14820   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14821     loadRegZize = 128;
14822
14823   // Represent our vector as a sequence of elements which are the
14824   // largest scalar that we can load.
14825   EVT LoadUnitVecVT = EVT::getVectorVT(
14826       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14827
14828   // Represent the data using the same element type that is stored in
14829   // memory. In practice, we ''widen'' MemVT.
14830   EVT WideVecVT =
14831       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14832                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14833
14834   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14835          "Invalid vector type");
14836
14837   // We can't shuffle using an illegal type.
14838   assert(TLI.isTypeLegal(WideVecVT) &&
14839          "We only lower types that form legal widened vector types");
14840
14841   SmallVector<SDValue, 8> Chains;
14842   SDValue Ptr = Ld->getBasePtr();
14843   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14844                                       TLI.getPointerTy(DAG.getDataLayout()));
14845   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14846
14847   for (unsigned i = 0; i < NumLoads; ++i) {
14848     // Perform a single load.
14849     SDValue ScalarLoad =
14850         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14851                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14852                     Ld->getAlignment());
14853     Chains.push_back(ScalarLoad.getValue(1));
14854     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14855     // another round of DAGCombining.
14856     if (i == 0)
14857       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14858     else
14859       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14860                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14861
14862     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14863   }
14864
14865   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14866
14867   // Bitcast the loaded value to a vector of the original element type, in
14868   // the size of the target vector type.
14869   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14870   unsigned SizeRatio = RegSz / MemSz;
14871
14872   if (Ext == ISD::SEXTLOAD) {
14873     // If we have SSE4.1, we can directly emit a VSEXT node.
14874     if (Subtarget->hasSSE41()) {
14875       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14876       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14877       return Sext;
14878     }
14879
14880     // Otherwise we'll shuffle the small elements in the high bits of the
14881     // larger type and perform an arithmetic shift. If the shift is not legal
14882     // it's better to scalarize.
14883     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14884            "We can't implement a sext load without an arithmetic right shift!");
14885
14886     // Redistribute the loaded elements into the different locations.
14887     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14888     for (unsigned i = 0; i != NumElems; ++i)
14889       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14890
14891     SDValue Shuff = DAG.getVectorShuffle(
14892         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14893
14894     Shuff = DAG.getBitcast(RegVT, Shuff);
14895
14896     // Build the arithmetic shift.
14897     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14898                    MemVT.getVectorElementType().getSizeInBits();
14899     Shuff =
14900         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14901                     DAG.getConstant(Amt, dl, RegVT));
14902
14903     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14904     return Shuff;
14905   }
14906
14907   // Redistribute the loaded elements into the different locations.
14908   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14909   for (unsigned i = 0; i != NumElems; ++i)
14910     ShuffleVec[i * SizeRatio] = i;
14911
14912   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14913                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14914
14915   // Bitcast to the requested type.
14916   Shuff = DAG.getBitcast(RegVT, Shuff);
14917   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14918   return Shuff;
14919 }
14920
14921 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14922 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14923 // from the AND / OR.
14924 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14925   Opc = Op.getOpcode();
14926   if (Opc != ISD::OR && Opc != ISD::AND)
14927     return false;
14928   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14929           Op.getOperand(0).hasOneUse() &&
14930           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14931           Op.getOperand(1).hasOneUse());
14932 }
14933
14934 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14935 // 1 and that the SETCC node has a single use.
14936 static bool isXor1OfSetCC(SDValue Op) {
14937   if (Op.getOpcode() != ISD::XOR)
14938     return false;
14939   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14940   if (N1C && N1C->getAPIntValue() == 1) {
14941     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14942       Op.getOperand(0).hasOneUse();
14943   }
14944   return false;
14945 }
14946
14947 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14948   bool addTest = true;
14949   SDValue Chain = Op.getOperand(0);
14950   SDValue Cond  = Op.getOperand(1);
14951   SDValue Dest  = Op.getOperand(2);
14952   SDLoc dl(Op);
14953   SDValue CC;
14954   bool Inverted = false;
14955
14956   if (Cond.getOpcode() == ISD::SETCC) {
14957     // Check for setcc([su]{add,sub,mul}o == 0).
14958     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14959         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14960         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14961         Cond.getOperand(0).getResNo() == 1 &&
14962         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14963          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14964          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14965          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14966          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14967          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14968       Inverted = true;
14969       Cond = Cond.getOperand(0);
14970     } else {
14971       SDValue NewCond = LowerSETCC(Cond, DAG);
14972       if (NewCond.getNode())
14973         Cond = NewCond;
14974     }
14975   }
14976 #if 0
14977   // FIXME: LowerXALUO doesn't handle these!!
14978   else if (Cond.getOpcode() == X86ISD::ADD  ||
14979            Cond.getOpcode() == X86ISD::SUB  ||
14980            Cond.getOpcode() == X86ISD::SMUL ||
14981            Cond.getOpcode() == X86ISD::UMUL)
14982     Cond = LowerXALUO(Cond, DAG);
14983 #endif
14984
14985   // Look pass (and (setcc_carry (cmp ...)), 1).
14986   if (Cond.getOpcode() == ISD::AND &&
14987       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14988     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14989     if (C && C->getAPIntValue() == 1)
14990       Cond = Cond.getOperand(0);
14991   }
14992
14993   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14994   // setting operand in place of the X86ISD::SETCC.
14995   unsigned CondOpcode = Cond.getOpcode();
14996   if (CondOpcode == X86ISD::SETCC ||
14997       CondOpcode == X86ISD::SETCC_CARRY) {
14998     CC = Cond.getOperand(0);
14999
15000     SDValue Cmp = Cond.getOperand(1);
15001     unsigned Opc = Cmp.getOpcode();
15002     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15003     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15004       Cond = Cmp;
15005       addTest = false;
15006     } else {
15007       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15008       default: break;
15009       case X86::COND_O:
15010       case X86::COND_B:
15011         // These can only come from an arithmetic instruction with overflow,
15012         // e.g. SADDO, UADDO.
15013         Cond = Cond.getNode()->getOperand(1);
15014         addTest = false;
15015         break;
15016       }
15017     }
15018   }
15019   CondOpcode = Cond.getOpcode();
15020   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15021       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15022       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15023        Cond.getOperand(0).getValueType() != MVT::i8)) {
15024     SDValue LHS = Cond.getOperand(0);
15025     SDValue RHS = Cond.getOperand(1);
15026     unsigned X86Opcode;
15027     unsigned X86Cond;
15028     SDVTList VTs;
15029     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15030     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15031     // X86ISD::INC).
15032     switch (CondOpcode) {
15033     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15034     case ISD::SADDO:
15035       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15036         if (C->isOne()) {
15037           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15038           break;
15039         }
15040       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15041     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15042     case ISD::SSUBO:
15043       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15044         if (C->isOne()) {
15045           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15046           break;
15047         }
15048       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15049     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15050     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15051     default: llvm_unreachable("unexpected overflowing operator");
15052     }
15053     if (Inverted)
15054       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15055     if (CondOpcode == ISD::UMULO)
15056       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15057                           MVT::i32);
15058     else
15059       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15060
15061     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15062
15063     if (CondOpcode == ISD::UMULO)
15064       Cond = X86Op.getValue(2);
15065     else
15066       Cond = X86Op.getValue(1);
15067
15068     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15069     addTest = false;
15070   } else {
15071     unsigned CondOpc;
15072     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15073       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15074       if (CondOpc == ISD::OR) {
15075         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15076         // two branches instead of an explicit OR instruction with a
15077         // separate test.
15078         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15079             isX86LogicalCmp(Cmp)) {
15080           CC = Cond.getOperand(0).getOperand(0);
15081           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15082                               Chain, Dest, CC, Cmp);
15083           CC = Cond.getOperand(1).getOperand(0);
15084           Cond = Cmp;
15085           addTest = false;
15086         }
15087       } else { // ISD::AND
15088         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15089         // two branches instead of an explicit AND instruction with a
15090         // separate test. However, we only do this if this block doesn't
15091         // have a fall-through edge, because this requires an explicit
15092         // jmp when the condition is false.
15093         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15094             isX86LogicalCmp(Cmp) &&
15095             Op.getNode()->hasOneUse()) {
15096           X86::CondCode CCode =
15097             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15098           CCode = X86::GetOppositeBranchCondition(CCode);
15099           CC = DAG.getConstant(CCode, dl, MVT::i8);
15100           SDNode *User = *Op.getNode()->use_begin();
15101           // Look for an unconditional branch following this conditional branch.
15102           // We need this because we need to reverse the successors in order
15103           // to implement FCMP_OEQ.
15104           if (User->getOpcode() == ISD::BR) {
15105             SDValue FalseBB = User->getOperand(1);
15106             SDNode *NewBR =
15107               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15108             assert(NewBR == User);
15109             (void)NewBR;
15110             Dest = FalseBB;
15111
15112             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15113                                 Chain, Dest, CC, Cmp);
15114             X86::CondCode CCode =
15115               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15116             CCode = X86::GetOppositeBranchCondition(CCode);
15117             CC = DAG.getConstant(CCode, dl, MVT::i8);
15118             Cond = Cmp;
15119             addTest = false;
15120           }
15121         }
15122       }
15123     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15124       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15125       // It should be transformed during dag combiner except when the condition
15126       // is set by a arithmetics with overflow node.
15127       X86::CondCode CCode =
15128         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15129       CCode = X86::GetOppositeBranchCondition(CCode);
15130       CC = DAG.getConstant(CCode, dl, MVT::i8);
15131       Cond = Cond.getOperand(0).getOperand(1);
15132       addTest = false;
15133     } else if (Cond.getOpcode() == ISD::SETCC &&
15134                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15135       // For FCMP_OEQ, we can emit
15136       // two branches instead of an explicit AND instruction with a
15137       // separate test. However, we only do this if this block doesn't
15138       // have a fall-through edge, because this requires an explicit
15139       // jmp when the condition is false.
15140       if (Op.getNode()->hasOneUse()) {
15141         SDNode *User = *Op.getNode()->use_begin();
15142         // Look for an unconditional branch following this conditional branch.
15143         // We need this because we need to reverse the successors in order
15144         // to implement FCMP_OEQ.
15145         if (User->getOpcode() == ISD::BR) {
15146           SDValue FalseBB = User->getOperand(1);
15147           SDNode *NewBR =
15148             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15149           assert(NewBR == User);
15150           (void)NewBR;
15151           Dest = FalseBB;
15152
15153           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15154                                     Cond.getOperand(0), Cond.getOperand(1));
15155           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15156           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15157           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15158                               Chain, Dest, CC, Cmp);
15159           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15160           Cond = Cmp;
15161           addTest = false;
15162         }
15163       }
15164     } else if (Cond.getOpcode() == ISD::SETCC &&
15165                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15166       // For FCMP_UNE, we can emit
15167       // two branches instead of an explicit AND instruction with a
15168       // separate test. However, we only do this if this block doesn't
15169       // have a fall-through edge, because this requires an explicit
15170       // jmp when the condition is false.
15171       if (Op.getNode()->hasOneUse()) {
15172         SDNode *User = *Op.getNode()->use_begin();
15173         // Look for an unconditional branch following this conditional branch.
15174         // We need this because we need to reverse the successors in order
15175         // to implement FCMP_UNE.
15176         if (User->getOpcode() == ISD::BR) {
15177           SDValue FalseBB = User->getOperand(1);
15178           SDNode *NewBR =
15179             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15180           assert(NewBR == User);
15181           (void)NewBR;
15182
15183           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15184                                     Cond.getOperand(0), Cond.getOperand(1));
15185           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15186           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15187           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15188                               Chain, Dest, CC, Cmp);
15189           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15190           Cond = Cmp;
15191           addTest = false;
15192           Dest = FalseBB;
15193         }
15194       }
15195     }
15196   }
15197
15198   if (addTest) {
15199     // Look pass the truncate if the high bits are known zero.
15200     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15201         Cond = Cond.getOperand(0);
15202
15203     // We know the result of AND is compared against zero. Try to match
15204     // it to BT.
15205     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15206       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15207       if (NewSetCC.getNode()) {
15208         CC = NewSetCC.getOperand(0);
15209         Cond = NewSetCC.getOperand(1);
15210         addTest = false;
15211       }
15212     }
15213   }
15214
15215   if (addTest) {
15216     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15217     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15218     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15219   }
15220   Cond = ConvertCmpIfNecessary(Cond, DAG);
15221   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15222                      Chain, Dest, CC, Cond);
15223 }
15224
15225 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15226 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15227 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15228 // that the guard pages used by the OS virtual memory manager are allocated in
15229 // correct sequence.
15230 SDValue
15231 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15232                                            SelectionDAG &DAG) const {
15233   MachineFunction &MF = DAG.getMachineFunction();
15234   bool SplitStack = MF.shouldSplitStack();
15235   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15236                SplitStack;
15237   SDLoc dl(Op);
15238
15239   if (!Lower) {
15240     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15241     SDNode* Node = Op.getNode();
15242
15243     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15244     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15245         " not tell us which reg is the stack pointer!");
15246     EVT VT = Node->getValueType(0);
15247     SDValue Tmp1 = SDValue(Node, 0);
15248     SDValue Tmp2 = SDValue(Node, 1);
15249     SDValue Tmp3 = Node->getOperand(2);
15250     SDValue Chain = Tmp1.getOperand(0);
15251
15252     // Chain the dynamic stack allocation so that it doesn't modify the stack
15253     // pointer when other instructions are using the stack.
15254     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15255         SDLoc(Node));
15256
15257     SDValue Size = Tmp2.getOperand(1);
15258     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15259     Chain = SP.getValue(1);
15260     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15261     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15262     unsigned StackAlign = TFI.getStackAlignment();
15263     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15264     if (Align > StackAlign)
15265       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15266           DAG.getConstant(-(uint64_t)Align, dl, VT));
15267     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15268
15269     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15270         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15271         SDLoc(Node));
15272
15273     SDValue Ops[2] = { Tmp1, Tmp2 };
15274     return DAG.getMergeValues(Ops, dl);
15275   }
15276
15277   // Get the inputs.
15278   SDValue Chain = Op.getOperand(0);
15279   SDValue Size  = Op.getOperand(1);
15280   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15281   EVT VT = Op.getNode()->getValueType(0);
15282
15283   bool Is64Bit = Subtarget->is64Bit();
15284   MVT SPTy = getPointerTy(DAG.getDataLayout());
15285
15286   if (SplitStack) {
15287     MachineRegisterInfo &MRI = MF.getRegInfo();
15288
15289     if (Is64Bit) {
15290       // The 64 bit implementation of segmented stacks needs to clobber both r10
15291       // r11. This makes it impossible to use it along with nested parameters.
15292       const Function *F = MF.getFunction();
15293
15294       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15295            I != E; ++I)
15296         if (I->hasNestAttr())
15297           report_fatal_error("Cannot use segmented stacks with functions that "
15298                              "have nested arguments.");
15299     }
15300
15301     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15302     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15303     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15304     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15305                                 DAG.getRegister(Vreg, SPTy));
15306     SDValue Ops1[2] = { Value, Chain };
15307     return DAG.getMergeValues(Ops1, dl);
15308   } else {
15309     SDValue Flag;
15310     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15311
15312     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15313     Flag = Chain.getValue(1);
15314     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15315
15316     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15317
15318     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15319     unsigned SPReg = RegInfo->getStackRegister();
15320     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15321     Chain = SP.getValue(1);
15322
15323     if (Align) {
15324       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15325                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15326       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15327     }
15328
15329     SDValue Ops1[2] = { SP, Chain };
15330     return DAG.getMergeValues(Ops1, dl);
15331   }
15332 }
15333
15334 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15335   MachineFunction &MF = DAG.getMachineFunction();
15336   auto PtrVT = getPointerTy(MF.getDataLayout());
15337   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15338
15339   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15340   SDLoc DL(Op);
15341
15342   if (!Subtarget->is64Bit() ||
15343       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15344     // vastart just stores the address of the VarArgsFrameIndex slot into the
15345     // memory location argument.
15346     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15347     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15348                         MachinePointerInfo(SV), false, false, 0);
15349   }
15350
15351   // __va_list_tag:
15352   //   gp_offset         (0 - 6 * 8)
15353   //   fp_offset         (48 - 48 + 8 * 16)
15354   //   overflow_arg_area (point to parameters coming in memory).
15355   //   reg_save_area
15356   SmallVector<SDValue, 8> MemOps;
15357   SDValue FIN = Op.getOperand(1);
15358   // Store gp_offset
15359   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15360                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15361                                                DL, MVT::i32),
15362                                FIN, MachinePointerInfo(SV), false, false, 0);
15363   MemOps.push_back(Store);
15364
15365   // Store fp_offset
15366   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15367   Store = DAG.getStore(Op.getOperand(0), DL,
15368                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15369                                        MVT::i32),
15370                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15371   MemOps.push_back(Store);
15372
15373   // Store ptr to overflow_arg_area
15374   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15375   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15376   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15377                        MachinePointerInfo(SV, 8),
15378                        false, false, 0);
15379   MemOps.push_back(Store);
15380
15381   // Store ptr to reg_save_area.
15382   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15383       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15384   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15385   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15386       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15387   MemOps.push_back(Store);
15388   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15389 }
15390
15391 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15392   assert(Subtarget->is64Bit() &&
15393          "LowerVAARG only handles 64-bit va_arg!");
15394   assert(Op.getNode()->getNumOperands() == 4);
15395
15396   MachineFunction &MF = DAG.getMachineFunction();
15397   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15398     // The Win64 ABI uses char* instead of a structure.
15399     return DAG.expandVAArg(Op.getNode());
15400
15401   SDValue Chain = Op.getOperand(0);
15402   SDValue SrcPtr = Op.getOperand(1);
15403   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15404   unsigned Align = Op.getConstantOperandVal(3);
15405   SDLoc dl(Op);
15406
15407   EVT ArgVT = Op.getNode()->getValueType(0);
15408   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15409   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15410   uint8_t ArgMode;
15411
15412   // Decide which area this value should be read from.
15413   // TODO: Implement the AMD64 ABI in its entirety. This simple
15414   // selection mechanism works only for the basic types.
15415   if (ArgVT == MVT::f80) {
15416     llvm_unreachable("va_arg for f80 not yet implemented");
15417   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15418     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15419   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15420     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15421   } else {
15422     llvm_unreachable("Unhandled argument type in LowerVAARG");
15423   }
15424
15425   if (ArgMode == 2) {
15426     // Sanity Check: Make sure using fp_offset makes sense.
15427     assert(!Subtarget->useSoftFloat() &&
15428            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15429            Subtarget->hasSSE1());
15430   }
15431
15432   // Insert VAARG_64 node into the DAG
15433   // VAARG_64 returns two values: Variable Argument Address, Chain
15434   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15435                        DAG.getConstant(ArgMode, dl, MVT::i8),
15436                        DAG.getConstant(Align, dl, MVT::i32)};
15437   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15438   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15439                                           VTs, InstOps, MVT::i64,
15440                                           MachinePointerInfo(SV),
15441                                           /*Align=*/0,
15442                                           /*Volatile=*/false,
15443                                           /*ReadMem=*/true,
15444                                           /*WriteMem=*/true);
15445   Chain = VAARG.getValue(1);
15446
15447   // Load the next argument and return it
15448   return DAG.getLoad(ArgVT, dl,
15449                      Chain,
15450                      VAARG,
15451                      MachinePointerInfo(),
15452                      false, false, false, 0);
15453 }
15454
15455 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15456                            SelectionDAG &DAG) {
15457   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15458   // where a va_list is still an i8*.
15459   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15460   if (Subtarget->isCallingConvWin64(
15461         DAG.getMachineFunction().getFunction()->getCallingConv()))
15462     // Probably a Win64 va_copy.
15463     return DAG.expandVACopy(Op.getNode());
15464
15465   SDValue Chain = Op.getOperand(0);
15466   SDValue DstPtr = Op.getOperand(1);
15467   SDValue SrcPtr = Op.getOperand(2);
15468   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15469   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15470   SDLoc DL(Op);
15471
15472   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15473                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15474                        false, false,
15475                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15476 }
15477
15478 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15479 // amount is a constant. Takes immediate version of shift as input.
15480 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15481                                           SDValue SrcOp, uint64_t ShiftAmt,
15482                                           SelectionDAG &DAG) {
15483   MVT ElementType = VT.getVectorElementType();
15484
15485   // Fold this packed shift into its first operand if ShiftAmt is 0.
15486   if (ShiftAmt == 0)
15487     return SrcOp;
15488
15489   // Check for ShiftAmt >= element width
15490   if (ShiftAmt >= ElementType.getSizeInBits()) {
15491     if (Opc == X86ISD::VSRAI)
15492       ShiftAmt = ElementType.getSizeInBits() - 1;
15493     else
15494       return DAG.getConstant(0, dl, VT);
15495   }
15496
15497   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15498          && "Unknown target vector shift-by-constant node");
15499
15500   // Fold this packed vector shift into a build vector if SrcOp is a
15501   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15502   if (VT == SrcOp.getSimpleValueType() &&
15503       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15504     SmallVector<SDValue, 8> Elts;
15505     unsigned NumElts = SrcOp->getNumOperands();
15506     ConstantSDNode *ND;
15507
15508     switch(Opc) {
15509     default: llvm_unreachable(nullptr);
15510     case X86ISD::VSHLI:
15511       for (unsigned i=0; i!=NumElts; ++i) {
15512         SDValue CurrentOp = SrcOp->getOperand(i);
15513         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15514           Elts.push_back(CurrentOp);
15515           continue;
15516         }
15517         ND = cast<ConstantSDNode>(CurrentOp);
15518         const APInt &C = ND->getAPIntValue();
15519         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15520       }
15521       break;
15522     case X86ISD::VSRLI:
15523       for (unsigned i=0; i!=NumElts; ++i) {
15524         SDValue CurrentOp = SrcOp->getOperand(i);
15525         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15526           Elts.push_back(CurrentOp);
15527           continue;
15528         }
15529         ND = cast<ConstantSDNode>(CurrentOp);
15530         const APInt &C = ND->getAPIntValue();
15531         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15532       }
15533       break;
15534     case X86ISD::VSRAI:
15535       for (unsigned i=0; i!=NumElts; ++i) {
15536         SDValue CurrentOp = SrcOp->getOperand(i);
15537         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15538           Elts.push_back(CurrentOp);
15539           continue;
15540         }
15541         ND = cast<ConstantSDNode>(CurrentOp);
15542         const APInt &C = ND->getAPIntValue();
15543         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15544       }
15545       break;
15546     }
15547
15548     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15549   }
15550
15551   return DAG.getNode(Opc, dl, VT, SrcOp,
15552                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15553 }
15554
15555 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15556 // may or may not be a constant. Takes immediate version of shift as input.
15557 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15558                                    SDValue SrcOp, SDValue ShAmt,
15559                                    SelectionDAG &DAG) {
15560   MVT SVT = ShAmt.getSimpleValueType();
15561   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15562
15563   // Catch shift-by-constant.
15564   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15565     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15566                                       CShAmt->getZExtValue(), DAG);
15567
15568   // Change opcode to non-immediate version
15569   switch (Opc) {
15570     default: llvm_unreachable("Unknown target vector shift node");
15571     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15572     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15573     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15574   }
15575
15576   const X86Subtarget &Subtarget =
15577       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15578   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15579       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15580     // Let the shuffle legalizer expand this shift amount node.
15581     SDValue Op0 = ShAmt.getOperand(0);
15582     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15583     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15584   } else {
15585     // Need to build a vector containing shift amount.
15586     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15587     SmallVector<SDValue, 4> ShOps;
15588     ShOps.push_back(ShAmt);
15589     if (SVT == MVT::i32) {
15590       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15591       ShOps.push_back(DAG.getUNDEF(SVT));
15592     }
15593     ShOps.push_back(DAG.getUNDEF(SVT));
15594
15595     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15596     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15597   }
15598
15599   // The return type has to be a 128-bit type with the same element
15600   // type as the input type.
15601   MVT EltVT = VT.getVectorElementType();
15602   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15603
15604   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15605   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15606 }
15607
15608 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15609 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15610 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15611 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15612                                     SDValue PreservedSrc,
15613                                     const X86Subtarget *Subtarget,
15614                                     SelectionDAG &DAG) {
15615     EVT VT = Op.getValueType();
15616     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15617                                   MVT::i1, VT.getVectorNumElements());
15618     SDValue VMask = SDValue();
15619     unsigned OpcodeSelect = ISD::VSELECT;
15620     SDLoc dl(Op);
15621
15622     assert(MaskVT.isSimple() && "invalid mask type");
15623
15624     if (isAllOnes(Mask))
15625       return Op;
15626
15627     if (MaskVT.bitsGT(Mask.getValueType())) {
15628       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15629                                          MaskVT.getSizeInBits());
15630       VMask = DAG.getBitcast(MaskVT,
15631                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15632     } else {
15633       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15634                                        Mask.getValueType().getSizeInBits());
15635       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15636       // are extracted by EXTRACT_SUBVECTOR.
15637       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15638                           DAG.getBitcast(BitcastVT, Mask),
15639                           DAG.getIntPtrConstant(0, dl));
15640     }
15641
15642     switch (Op.getOpcode()) {
15643       default: break;
15644       case X86ISD::PCMPEQM:
15645       case X86ISD::PCMPGTM:
15646       case X86ISD::CMPM:
15647       case X86ISD::CMPMU:
15648         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15649       case X86ISD::VTRUNC:
15650       case X86ISD::VTRUNCS:
15651       case X86ISD::VTRUNCUS:
15652         // We can't use ISD::VSELECT here because it is not always "Legal"
15653         // for the destination type. For example vpmovqb require only AVX512
15654         // and vselect that can operate on byte element type require BWI
15655         OpcodeSelect = X86ISD::SELECT;
15656         break;
15657     }
15658     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15659       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15660     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15661 }
15662
15663 /// \brief Creates an SDNode for a predicated scalar operation.
15664 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15665 /// The mask is coming as MVT::i8 and it should be truncated
15666 /// to MVT::i1 while lowering masking intrinsics.
15667 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15668 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15669 /// for a scalar instruction.
15670 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15671                                     SDValue PreservedSrc,
15672                                     const X86Subtarget *Subtarget,
15673                                     SelectionDAG &DAG) {
15674     if (isAllOnes(Mask))
15675       return Op;
15676
15677     EVT VT = Op.getValueType();
15678     SDLoc dl(Op);
15679     // The mask should be of type MVT::i1
15680     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15681
15682     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15683       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15684     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15685 }
15686
15687 static int getSEHRegistrationNodeSize(const Function *Fn) {
15688   if (!Fn->hasPersonalityFn())
15689     report_fatal_error(
15690         "querying registration node size for function without personality");
15691   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15692   // WinEHStatePass for the full struct definition.
15693   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15694   case EHPersonality::MSVC_X86SEH: return 24;
15695   case EHPersonality::MSVC_CXX: return 16;
15696   default: break;
15697   }
15698   report_fatal_error("can only recover FP for MSVC EH personality functions");
15699 }
15700
15701 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15702 /// function or when returning to a parent frame after catching an exception, we
15703 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15704 /// Here's the math:
15705 ///   RegNodeBase = EntryEBP - RegNodeSize
15706 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15707 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15708 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15709 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15710                                    SDValue EntryEBP) {
15711   MachineFunction &MF = DAG.getMachineFunction();
15712   SDLoc dl;
15713
15714   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15715   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15716
15717   // It's possible that the parent function no longer has a personality function
15718   // if the exceptional code was optimized away, in which case we just return
15719   // the incoming EBP.
15720   if (!Fn->hasPersonalityFn())
15721     return EntryEBP;
15722
15723   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15724
15725   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15726   // registration.
15727   MCSymbol *OffsetSym =
15728       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15729           GlobalValue::getRealLinkageName(Fn->getName()));
15730   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15731   SDValue RegNodeFrameOffset =
15732       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15733
15734   // RegNodeBase = EntryEBP - RegNodeSize
15735   // ParentFP = RegNodeBase - RegNodeFrameOffset
15736   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15737                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15738   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15739 }
15740
15741 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15742                                        SelectionDAG &DAG) {
15743   SDLoc dl(Op);
15744   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15745   EVT VT = Op.getValueType();
15746   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15747   if (IntrData) {
15748     switch(IntrData->Type) {
15749     case INTR_TYPE_1OP:
15750       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15751     case INTR_TYPE_2OP:
15752       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15753         Op.getOperand(2));
15754     case INTR_TYPE_2OP_IMM8:
15755       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15756                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15757     case INTR_TYPE_3OP:
15758       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15759         Op.getOperand(2), Op.getOperand(3));
15760     case INTR_TYPE_4OP:
15761       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15762         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15763     case INTR_TYPE_1OP_MASK_RM: {
15764       SDValue Src = Op.getOperand(1);
15765       SDValue PassThru = Op.getOperand(2);
15766       SDValue Mask = Op.getOperand(3);
15767       SDValue RoundingMode;
15768       // We allways add rounding mode to the Node.
15769       // If the rounding mode is not specified, we add the
15770       // "current direction" mode.
15771       if (Op.getNumOperands() == 4)
15772         RoundingMode =
15773           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15774       else
15775         RoundingMode = Op.getOperand(4);
15776       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15777       if (IntrWithRoundingModeOpcode != 0)
15778         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15779             X86::STATIC_ROUNDING::CUR_DIRECTION)
15780           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15781                                       dl, Op.getValueType(), Src, RoundingMode),
15782                                       Mask, PassThru, Subtarget, DAG);
15783       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15784                                               RoundingMode),
15785                                   Mask, PassThru, Subtarget, DAG);
15786     }
15787     case INTR_TYPE_1OP_MASK: {
15788       SDValue Src = Op.getOperand(1);
15789       SDValue PassThru = Op.getOperand(2);
15790       SDValue Mask = Op.getOperand(3);
15791       // We add rounding mode to the Node when
15792       //   - RM Opcode is specified and
15793       //   - RM is not "current direction".
15794       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15795       if (IntrWithRoundingModeOpcode != 0) {
15796         SDValue Rnd = Op.getOperand(4);
15797         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15798         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15799           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15800                                       dl, Op.getValueType(),
15801                                       Src, Rnd),
15802                                       Mask, PassThru, Subtarget, DAG);
15803         }
15804       }
15805       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15806                                   Mask, PassThru, Subtarget, DAG);
15807     }
15808     case INTR_TYPE_SCALAR_MASK_RM: {
15809       SDValue Src1 = Op.getOperand(1);
15810       SDValue Src2 = Op.getOperand(2);
15811       SDValue Src0 = Op.getOperand(3);
15812       SDValue Mask = Op.getOperand(4);
15813       // There are 2 kinds of intrinsics in this group:
15814       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15815       // (2) With rounding mode and sae - 7 operands.
15816       if (Op.getNumOperands() == 6) {
15817         SDValue Sae  = Op.getOperand(5);
15818         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15819         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15820                                                 Sae),
15821                                     Mask, Src0, Subtarget, DAG);
15822       }
15823       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15824       SDValue RoundingMode  = Op.getOperand(5);
15825       SDValue Sae  = Op.getOperand(6);
15826       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15827                                               RoundingMode, Sae),
15828                                   Mask, Src0, Subtarget, DAG);
15829     }
15830     case INTR_TYPE_2OP_MASK: {
15831       SDValue Src1 = Op.getOperand(1);
15832       SDValue Src2 = Op.getOperand(2);
15833       SDValue PassThru = Op.getOperand(3);
15834       SDValue Mask = Op.getOperand(4);
15835       // We specify 2 possible opcodes for intrinsics with rounding modes.
15836       // First, we check if the intrinsic may have non-default rounding mode,
15837       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15838       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15839       if (IntrWithRoundingModeOpcode != 0) {
15840         SDValue Rnd = Op.getOperand(5);
15841         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15842         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15843           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15844                                       dl, Op.getValueType(),
15845                                       Src1, Src2, Rnd),
15846                                       Mask, PassThru, Subtarget, DAG);
15847         }
15848       }
15849       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15850                                               Src1,Src2),
15851                                   Mask, PassThru, Subtarget, DAG);
15852     }
15853     case INTR_TYPE_2OP_MASK_RM: {
15854       SDValue Src1 = Op.getOperand(1);
15855       SDValue Src2 = Op.getOperand(2);
15856       SDValue PassThru = Op.getOperand(3);
15857       SDValue Mask = Op.getOperand(4);
15858       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15859       // First, we check if the intrinsic have rounding mode (6 operands),
15860       // if not, we set rounding mode to "current".
15861       SDValue Rnd;
15862       if (Op.getNumOperands() == 6)
15863         Rnd = Op.getOperand(5);
15864       else
15865         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15866       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15867                                               Src1, Src2, Rnd),
15868                                   Mask, PassThru, Subtarget, DAG);
15869     }
15870     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
15871       SDValue Src1 = Op.getOperand(1);
15872       SDValue Src2 = Op.getOperand(2);
15873       SDValue Src3 = Op.getOperand(3);
15874       SDValue PassThru = Op.getOperand(4);
15875       SDValue Mask = Op.getOperand(5);
15876       SDValue Sae  = Op.getOperand(6);
15877
15878       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
15879                                               Src2, Src3, Sae),
15880                                   Mask, PassThru, Subtarget, DAG);
15881     }
15882     case INTR_TYPE_3OP_MASK_RM: {
15883       SDValue Src1 = Op.getOperand(1);
15884       SDValue Src2 = Op.getOperand(2);
15885       SDValue Imm = Op.getOperand(3);
15886       SDValue PassThru = Op.getOperand(4);
15887       SDValue Mask = Op.getOperand(5);
15888       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15889       // First, we check if the intrinsic have rounding mode (7 operands),
15890       // if not, we set rounding mode to "current".
15891       SDValue Rnd;
15892       if (Op.getNumOperands() == 7)
15893         Rnd = Op.getOperand(6);
15894       else
15895         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15896       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15897         Src1, Src2, Imm, Rnd),
15898         Mask, PassThru, Subtarget, DAG);
15899     }
15900     case INTR_TYPE_3OP_IMM8_MASK:
15901     case INTR_TYPE_3OP_MASK: {
15902       SDValue Src1 = Op.getOperand(1);
15903       SDValue Src2 = Op.getOperand(2);
15904       SDValue Src3 = Op.getOperand(3);
15905       SDValue PassThru = Op.getOperand(4);
15906       SDValue Mask = Op.getOperand(5);
15907
15908       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15909         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15910       // We specify 2 possible opcodes for intrinsics with rounding modes.
15911       // First, we check if the intrinsic may have non-default rounding mode,
15912       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15913       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15914       if (IntrWithRoundingModeOpcode != 0) {
15915         SDValue Rnd = Op.getOperand(6);
15916         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15917         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15918           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15919                                       dl, Op.getValueType(),
15920                                       Src1, Src2, Src3, Rnd),
15921                                       Mask, PassThru, Subtarget, DAG);
15922         }
15923       }
15924       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15925                                               Src1, Src2, Src3),
15926                                   Mask, PassThru, Subtarget, DAG);
15927     }
15928     case VPERM_3OP_MASKZ:
15929     case VPERM_3OP_MASK:
15930     case FMA_OP_MASK3:
15931     case FMA_OP_MASKZ:
15932     case FMA_OP_MASK: {
15933       SDValue Src1 = Op.getOperand(1);
15934       SDValue Src2 = Op.getOperand(2);
15935       SDValue Src3 = Op.getOperand(3);
15936       SDValue Mask = Op.getOperand(4);
15937       EVT VT = Op.getValueType();
15938       SDValue PassThru = SDValue();
15939
15940       // set PassThru element
15941       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15942         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15943       else if (IntrData->Type == FMA_OP_MASK3)
15944         PassThru = Src3;
15945       else
15946         PassThru = Src1;
15947
15948       // We specify 2 possible opcodes for intrinsics with rounding modes.
15949       // First, we check if the intrinsic may have non-default rounding mode,
15950       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15951       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15952       if (IntrWithRoundingModeOpcode != 0) {
15953         SDValue Rnd = Op.getOperand(5);
15954         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15955             X86::STATIC_ROUNDING::CUR_DIRECTION)
15956           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15957                                                   dl, Op.getValueType(),
15958                                                   Src1, Src2, Src3, Rnd),
15959                                       Mask, PassThru, Subtarget, DAG);
15960       }
15961       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15962                                               dl, Op.getValueType(),
15963                                               Src1, Src2, Src3),
15964                                   Mask, PassThru, Subtarget, DAG);
15965     }
15966     case CMP_MASK:
15967     case CMP_MASK_CC: {
15968       // Comparison intrinsics with masks.
15969       // Example of transformation:
15970       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15971       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15972       // (i8 (bitcast
15973       //   (v8i1 (insert_subvector undef,
15974       //           (v2i1 (and (PCMPEQM %a, %b),
15975       //                      (extract_subvector
15976       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15977       EVT VT = Op.getOperand(1).getValueType();
15978       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15979                                     VT.getVectorNumElements());
15980       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15981       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15982                                        Mask.getValueType().getSizeInBits());
15983       SDValue Cmp;
15984       if (IntrData->Type == CMP_MASK_CC) {
15985         SDValue CC = Op.getOperand(3);
15986         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15987         // We specify 2 possible opcodes for intrinsics with rounding modes.
15988         // First, we check if the intrinsic may have non-default rounding mode,
15989         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15990         if (IntrData->Opc1 != 0) {
15991           SDValue Rnd = Op.getOperand(5);
15992           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15993               X86::STATIC_ROUNDING::CUR_DIRECTION)
15994             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15995                               Op.getOperand(2), CC, Rnd);
15996         }
15997         //default rounding mode
15998         if(!Cmp.getNode())
15999             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16000                               Op.getOperand(2), CC);
16001
16002       } else {
16003         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16004         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16005                           Op.getOperand(2));
16006       }
16007       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16008                                              DAG.getTargetConstant(0, dl,
16009                                                                    MaskVT),
16010                                              Subtarget, DAG);
16011       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16012                                 DAG.getUNDEF(BitcastVT), CmpMask,
16013                                 DAG.getIntPtrConstant(0, dl));
16014       return DAG.getBitcast(Op.getValueType(), Res);
16015     }
16016     case COMI: { // Comparison intrinsics
16017       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16018       SDValue LHS = Op.getOperand(1);
16019       SDValue RHS = Op.getOperand(2);
16020       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16021       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16022       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16023       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16024                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16025       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16026     }
16027     case VSHIFT:
16028       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16029                                  Op.getOperand(1), Op.getOperand(2), DAG);
16030     case VSHIFT_MASK:
16031       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16032                                                       Op.getSimpleValueType(),
16033                                                       Op.getOperand(1),
16034                                                       Op.getOperand(2), DAG),
16035                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16036                                   DAG);
16037     case COMPRESS_EXPAND_IN_REG: {
16038       SDValue Mask = Op.getOperand(3);
16039       SDValue DataToCompress = Op.getOperand(1);
16040       SDValue PassThru = Op.getOperand(2);
16041       if (isAllOnes(Mask)) // return data as is
16042         return Op.getOperand(1);
16043
16044       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16045                                               DataToCompress),
16046                                   Mask, PassThru, Subtarget, DAG);
16047     }
16048     case BLEND: {
16049       SDValue Mask = Op.getOperand(3);
16050       EVT VT = Op.getValueType();
16051       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16052                                     VT.getVectorNumElements());
16053       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16054                                        Mask.getValueType().getSizeInBits());
16055       SDLoc dl(Op);
16056       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16057                                   DAG.getBitcast(BitcastVT, Mask),
16058                                   DAG.getIntPtrConstant(0, dl));
16059       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16060                          Op.getOperand(2));
16061     }
16062     default:
16063       break;
16064     }
16065   }
16066
16067   switch (IntNo) {
16068   default: return SDValue();    // Don't custom lower most intrinsics.
16069
16070   case Intrinsic::x86_avx2_permd:
16071   case Intrinsic::x86_avx2_permps:
16072     // Operands intentionally swapped. Mask is last operand to intrinsic,
16073     // but second operand for node/instruction.
16074     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16075                        Op.getOperand(2), Op.getOperand(1));
16076
16077   // ptest and testp intrinsics. The intrinsic these come from are designed to
16078   // return an integer value, not just an instruction so lower it to the ptest
16079   // or testp pattern and a setcc for the result.
16080   case Intrinsic::x86_sse41_ptestz:
16081   case Intrinsic::x86_sse41_ptestc:
16082   case Intrinsic::x86_sse41_ptestnzc:
16083   case Intrinsic::x86_avx_ptestz_256:
16084   case Intrinsic::x86_avx_ptestc_256:
16085   case Intrinsic::x86_avx_ptestnzc_256:
16086   case Intrinsic::x86_avx_vtestz_ps:
16087   case Intrinsic::x86_avx_vtestc_ps:
16088   case Intrinsic::x86_avx_vtestnzc_ps:
16089   case Intrinsic::x86_avx_vtestz_pd:
16090   case Intrinsic::x86_avx_vtestc_pd:
16091   case Intrinsic::x86_avx_vtestnzc_pd:
16092   case Intrinsic::x86_avx_vtestz_ps_256:
16093   case Intrinsic::x86_avx_vtestc_ps_256:
16094   case Intrinsic::x86_avx_vtestnzc_ps_256:
16095   case Intrinsic::x86_avx_vtestz_pd_256:
16096   case Intrinsic::x86_avx_vtestc_pd_256:
16097   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16098     bool IsTestPacked = false;
16099     unsigned X86CC;
16100     switch (IntNo) {
16101     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16102     case Intrinsic::x86_avx_vtestz_ps:
16103     case Intrinsic::x86_avx_vtestz_pd:
16104     case Intrinsic::x86_avx_vtestz_ps_256:
16105     case Intrinsic::x86_avx_vtestz_pd_256:
16106       IsTestPacked = true; // Fallthrough
16107     case Intrinsic::x86_sse41_ptestz:
16108     case Intrinsic::x86_avx_ptestz_256:
16109       // ZF = 1
16110       X86CC = X86::COND_E;
16111       break;
16112     case Intrinsic::x86_avx_vtestc_ps:
16113     case Intrinsic::x86_avx_vtestc_pd:
16114     case Intrinsic::x86_avx_vtestc_ps_256:
16115     case Intrinsic::x86_avx_vtestc_pd_256:
16116       IsTestPacked = true; // Fallthrough
16117     case Intrinsic::x86_sse41_ptestc:
16118     case Intrinsic::x86_avx_ptestc_256:
16119       // CF = 1
16120       X86CC = X86::COND_B;
16121       break;
16122     case Intrinsic::x86_avx_vtestnzc_ps:
16123     case Intrinsic::x86_avx_vtestnzc_pd:
16124     case Intrinsic::x86_avx_vtestnzc_ps_256:
16125     case Intrinsic::x86_avx_vtestnzc_pd_256:
16126       IsTestPacked = true; // Fallthrough
16127     case Intrinsic::x86_sse41_ptestnzc:
16128     case Intrinsic::x86_avx_ptestnzc_256:
16129       // ZF and CF = 0
16130       X86CC = X86::COND_A;
16131       break;
16132     }
16133
16134     SDValue LHS = Op.getOperand(1);
16135     SDValue RHS = Op.getOperand(2);
16136     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16137     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16138     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16139     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16140     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16141   }
16142   case Intrinsic::x86_avx512_kortestz_w:
16143   case Intrinsic::x86_avx512_kortestc_w: {
16144     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16145     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16146     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16147     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16148     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16149     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16150     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16151   }
16152
16153   case Intrinsic::x86_sse42_pcmpistria128:
16154   case Intrinsic::x86_sse42_pcmpestria128:
16155   case Intrinsic::x86_sse42_pcmpistric128:
16156   case Intrinsic::x86_sse42_pcmpestric128:
16157   case Intrinsic::x86_sse42_pcmpistrio128:
16158   case Intrinsic::x86_sse42_pcmpestrio128:
16159   case Intrinsic::x86_sse42_pcmpistris128:
16160   case Intrinsic::x86_sse42_pcmpestris128:
16161   case Intrinsic::x86_sse42_pcmpistriz128:
16162   case Intrinsic::x86_sse42_pcmpestriz128: {
16163     unsigned Opcode;
16164     unsigned X86CC;
16165     switch (IntNo) {
16166     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16167     case Intrinsic::x86_sse42_pcmpistria128:
16168       Opcode = X86ISD::PCMPISTRI;
16169       X86CC = X86::COND_A;
16170       break;
16171     case Intrinsic::x86_sse42_pcmpestria128:
16172       Opcode = X86ISD::PCMPESTRI;
16173       X86CC = X86::COND_A;
16174       break;
16175     case Intrinsic::x86_sse42_pcmpistric128:
16176       Opcode = X86ISD::PCMPISTRI;
16177       X86CC = X86::COND_B;
16178       break;
16179     case Intrinsic::x86_sse42_pcmpestric128:
16180       Opcode = X86ISD::PCMPESTRI;
16181       X86CC = X86::COND_B;
16182       break;
16183     case Intrinsic::x86_sse42_pcmpistrio128:
16184       Opcode = X86ISD::PCMPISTRI;
16185       X86CC = X86::COND_O;
16186       break;
16187     case Intrinsic::x86_sse42_pcmpestrio128:
16188       Opcode = X86ISD::PCMPESTRI;
16189       X86CC = X86::COND_O;
16190       break;
16191     case Intrinsic::x86_sse42_pcmpistris128:
16192       Opcode = X86ISD::PCMPISTRI;
16193       X86CC = X86::COND_S;
16194       break;
16195     case Intrinsic::x86_sse42_pcmpestris128:
16196       Opcode = X86ISD::PCMPESTRI;
16197       X86CC = X86::COND_S;
16198       break;
16199     case Intrinsic::x86_sse42_pcmpistriz128:
16200       Opcode = X86ISD::PCMPISTRI;
16201       X86CC = X86::COND_E;
16202       break;
16203     case Intrinsic::x86_sse42_pcmpestriz128:
16204       Opcode = X86ISD::PCMPESTRI;
16205       X86CC = X86::COND_E;
16206       break;
16207     }
16208     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16209     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16210     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16211     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16212                                 DAG.getConstant(X86CC, dl, MVT::i8),
16213                                 SDValue(PCMP.getNode(), 1));
16214     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16215   }
16216
16217   case Intrinsic::x86_sse42_pcmpistri128:
16218   case Intrinsic::x86_sse42_pcmpestri128: {
16219     unsigned Opcode;
16220     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16221       Opcode = X86ISD::PCMPISTRI;
16222     else
16223       Opcode = X86ISD::PCMPESTRI;
16224
16225     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16226     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16227     return DAG.getNode(Opcode, dl, VTs, NewOps);
16228   }
16229
16230   case Intrinsic::x86_seh_lsda: {
16231     // Compute the symbol for the LSDA. We know it'll get emitted later.
16232     MachineFunction &MF = DAG.getMachineFunction();
16233     SDValue Op1 = Op.getOperand(1);
16234     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16235     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16236         GlobalValue::getRealLinkageName(Fn->getName()));
16237
16238     // Generate a simple absolute symbol reference. This intrinsic is only
16239     // supported on 32-bit Windows, which isn't PIC.
16240     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16241     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16242   }
16243
16244   case Intrinsic::x86_seh_recoverfp: {
16245     SDValue FnOp = Op.getOperand(1);
16246     SDValue IncomingFPOp = Op.getOperand(2);
16247     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16248     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16249     if (!Fn)
16250       report_fatal_error(
16251           "llvm.x86.seh.recoverfp must take a function as the first argument");
16252     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16253   }
16254
16255   case Intrinsic::localaddress: {
16256     // Returns one of the stack, base, or frame pointer registers, depending on
16257     // which is used to reference local variables.
16258     MachineFunction &MF = DAG.getMachineFunction();
16259     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16260     unsigned Reg;
16261     if (RegInfo->hasBasePointer(MF))
16262       Reg = RegInfo->getBaseRegister();
16263     else // This function handles the SP or FP case.
16264       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16265     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16266   }
16267   }
16268 }
16269
16270 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16271                               SDValue Src, SDValue Mask, SDValue Base,
16272                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16273                               const X86Subtarget * Subtarget) {
16274   SDLoc dl(Op);
16275   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16276   if (!C)
16277     llvm_unreachable("Invalid scale type");
16278   unsigned ScaleVal = C->getZExtValue();
16279   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16280     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16281
16282   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16283   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16284                              Index.getSimpleValueType().getVectorNumElements());
16285   SDValue MaskInReg;
16286   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16287   if (MaskC)
16288     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16289   else {
16290     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16291                                      Mask.getValueType().getSizeInBits());
16292
16293     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16294     // are extracted by EXTRACT_SUBVECTOR.
16295     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16296                             DAG.getBitcast(BitcastVT, Mask),
16297                             DAG.getIntPtrConstant(0, dl));
16298   }
16299   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16300   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16301   SDValue Segment = DAG.getRegister(0, MVT::i32);
16302   if (Src.getOpcode() == ISD::UNDEF)
16303     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16304   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16305   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16306   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16307   return DAG.getMergeValues(RetOps, dl);
16308 }
16309
16310 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16311                                SDValue Src, SDValue Mask, SDValue Base,
16312                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16313   SDLoc dl(Op);
16314   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16315   if (!C)
16316     llvm_unreachable("Invalid scale type");
16317   unsigned ScaleVal = C->getZExtValue();
16318   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16319     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16320
16321   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16322   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16323   SDValue Segment = DAG.getRegister(0, MVT::i32);
16324   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16325                              Index.getSimpleValueType().getVectorNumElements());
16326   SDValue MaskInReg;
16327   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16328   if (MaskC)
16329     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16330   else {
16331     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16332                                      Mask.getValueType().getSizeInBits());
16333
16334     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16335     // are extracted by EXTRACT_SUBVECTOR.
16336     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16337                             DAG.getBitcast(BitcastVT, Mask),
16338                             DAG.getIntPtrConstant(0, dl));
16339   }
16340   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16341   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16342   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16343   return SDValue(Res, 1);
16344 }
16345
16346 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16347                                SDValue Mask, SDValue Base, SDValue Index,
16348                                SDValue ScaleOp, SDValue Chain) {
16349   SDLoc dl(Op);
16350   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16351   assert(C && "Invalid scale type");
16352   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16353   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16354   SDValue Segment = DAG.getRegister(0, MVT::i32);
16355   EVT MaskVT =
16356     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16357   SDValue MaskInReg;
16358   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16359   if (MaskC)
16360     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16361   else
16362     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16363   //SDVTList VTs = DAG.getVTList(MVT::Other);
16364   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16365   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16366   return SDValue(Res, 0);
16367 }
16368
16369 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16370 // read performance monitor counters (x86_rdpmc).
16371 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16372                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16373                               SmallVectorImpl<SDValue> &Results) {
16374   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16375   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16376   SDValue LO, HI;
16377
16378   // The ECX register is used to select the index of the performance counter
16379   // to read.
16380   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16381                                    N->getOperand(2));
16382   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16383
16384   // Reads the content of a 64-bit performance counter and returns it in the
16385   // registers EDX:EAX.
16386   if (Subtarget->is64Bit()) {
16387     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16388     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16389                             LO.getValue(2));
16390   } else {
16391     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16392     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16393                             LO.getValue(2));
16394   }
16395   Chain = HI.getValue(1);
16396
16397   if (Subtarget->is64Bit()) {
16398     // The EAX register is loaded with the low-order 32 bits. The EDX register
16399     // is loaded with the supported high-order bits of the counter.
16400     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16401                               DAG.getConstant(32, DL, MVT::i8));
16402     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16403     Results.push_back(Chain);
16404     return;
16405   }
16406
16407   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16408   SDValue Ops[] = { LO, HI };
16409   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16410   Results.push_back(Pair);
16411   Results.push_back(Chain);
16412 }
16413
16414 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16415 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16416 // also used to custom lower READCYCLECOUNTER nodes.
16417 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16418                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16419                               SmallVectorImpl<SDValue> &Results) {
16420   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16421   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16422   SDValue LO, HI;
16423
16424   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16425   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16426   // and the EAX register is loaded with the low-order 32 bits.
16427   if (Subtarget->is64Bit()) {
16428     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16429     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16430                             LO.getValue(2));
16431   } else {
16432     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16433     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16434                             LO.getValue(2));
16435   }
16436   SDValue Chain = HI.getValue(1);
16437
16438   if (Opcode == X86ISD::RDTSCP_DAG) {
16439     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16440
16441     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16442     // the ECX register. Add 'ecx' explicitly to the chain.
16443     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16444                                      HI.getValue(2));
16445     // Explicitly store the content of ECX at the location passed in input
16446     // to the 'rdtscp' intrinsic.
16447     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16448                          MachinePointerInfo(), false, false, 0);
16449   }
16450
16451   if (Subtarget->is64Bit()) {
16452     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16453     // the EAX register is loaded with the low-order 32 bits.
16454     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16455                               DAG.getConstant(32, DL, MVT::i8));
16456     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16457     Results.push_back(Chain);
16458     return;
16459   }
16460
16461   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16462   SDValue Ops[] = { LO, HI };
16463   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16464   Results.push_back(Pair);
16465   Results.push_back(Chain);
16466 }
16467
16468 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16469                                      SelectionDAG &DAG) {
16470   SmallVector<SDValue, 2> Results;
16471   SDLoc DL(Op);
16472   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16473                           Results);
16474   return DAG.getMergeValues(Results, DL);
16475 }
16476
16477 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16478                                     SelectionDAG &DAG) {
16479   MachineFunction &MF = DAG.getMachineFunction();
16480   const Function *Fn = MF.getFunction();
16481   SDLoc dl(Op);
16482   SDValue Chain = Op.getOperand(0);
16483
16484   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16485          "using llvm.x86.seh.restoreframe requires a frame pointer");
16486
16487   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16488   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16489
16490   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16491   unsigned FrameReg =
16492       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16493   unsigned SPReg = RegInfo->getStackRegister();
16494   unsigned SlotSize = RegInfo->getSlotSize();
16495
16496   // Get incoming EBP.
16497   SDValue IncomingEBP =
16498       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16499
16500   // SP is saved in the first field of every registration node, so load
16501   // [EBP-RegNodeSize] into SP.
16502   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16503   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16504                                DAG.getConstant(-RegNodeSize, dl, VT));
16505   SDValue NewSP =
16506       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16507                   false, VT.getScalarSizeInBits() / 8);
16508   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16509
16510   if (!RegInfo->needsStackRealignment(MF)) {
16511     // Adjust EBP to point back to the original frame position.
16512     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16513     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16514   } else {
16515     assert(RegInfo->hasBasePointer(MF) &&
16516            "functions with Win32 EH must use frame or base pointer register");
16517
16518     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16519     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16520     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16521
16522     // Reload the spilled EBP value, now that the stack and base pointers are
16523     // set up.
16524     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16525     X86FI->setHasSEHFramePtrSave(true);
16526     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16527     X86FI->setSEHFramePtrSaveIndex(FI);
16528     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16529                                 MachinePointerInfo(), false, false, false,
16530                                 VT.getScalarSizeInBits() / 8);
16531     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16532   }
16533
16534   return Chain;
16535 }
16536
16537 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16538 /// return truncate Store/MaskedStore Node
16539 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16540                                                SelectionDAG &DAG,
16541                                                MVT ElementType) {
16542   SDLoc dl(Op);
16543   SDValue Mask = Op.getOperand(4);
16544   SDValue DataToTruncate = Op.getOperand(3);
16545   SDValue Addr = Op.getOperand(2);
16546   SDValue Chain = Op.getOperand(0);
16547
16548   EVT VT  = DataToTruncate.getValueType();
16549   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16550                              ElementType, VT.getVectorNumElements());
16551
16552   if (isAllOnes(Mask)) // return just a truncate store
16553     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16554                              MachinePointerInfo(), SVT, false, false,
16555                              SVT.getScalarSizeInBits()/8);
16556
16557   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16558                                 MVT::i1, VT.getVectorNumElements());
16559   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16560                                    Mask.getValueType().getSizeInBits());
16561   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16562   // are extracted by EXTRACT_SUBVECTOR.
16563   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16564                               DAG.getBitcast(BitcastVT, Mask),
16565                               DAG.getIntPtrConstant(0, dl));
16566
16567   MachineMemOperand *MMO = DAG.getMachineFunction().
16568     getMachineMemOperand(MachinePointerInfo(),
16569                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16570                          SVT.getScalarSizeInBits()/8);
16571
16572   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16573                             VMask, SVT, MMO, true);
16574 }
16575
16576 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16577                                       SelectionDAG &DAG) {
16578   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16579
16580   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16581   if (!IntrData) {
16582     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16583       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16584     return SDValue();
16585   }
16586
16587   SDLoc dl(Op);
16588   switch(IntrData->Type) {
16589   default:
16590     llvm_unreachable("Unknown Intrinsic Type");
16591     break;
16592   case RDSEED:
16593   case RDRAND: {
16594     // Emit the node with the right value type.
16595     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16596     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16597
16598     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16599     // Otherwise return the value from Rand, which is always 0, casted to i32.
16600     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16601                       DAG.getConstant(1, dl, Op->getValueType(1)),
16602                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16603                       SDValue(Result.getNode(), 1) };
16604     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16605                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16606                                   Ops);
16607
16608     // Return { result, isValid, chain }.
16609     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16610                        SDValue(Result.getNode(), 2));
16611   }
16612   case GATHER: {
16613   //gather(v1, mask, index, base, scale);
16614     SDValue Chain = Op.getOperand(0);
16615     SDValue Src   = Op.getOperand(2);
16616     SDValue Base  = Op.getOperand(3);
16617     SDValue Index = Op.getOperand(4);
16618     SDValue Mask  = Op.getOperand(5);
16619     SDValue Scale = Op.getOperand(6);
16620     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16621                          Chain, Subtarget);
16622   }
16623   case SCATTER: {
16624   //scatter(base, mask, index, v1, scale);
16625     SDValue Chain = Op.getOperand(0);
16626     SDValue Base  = Op.getOperand(2);
16627     SDValue Mask  = Op.getOperand(3);
16628     SDValue Index = Op.getOperand(4);
16629     SDValue Src   = Op.getOperand(5);
16630     SDValue Scale = Op.getOperand(6);
16631     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16632                           Scale, Chain);
16633   }
16634   case PREFETCH: {
16635     SDValue Hint = Op.getOperand(6);
16636     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16637     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16638     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16639     SDValue Chain = Op.getOperand(0);
16640     SDValue Mask  = Op.getOperand(2);
16641     SDValue Index = Op.getOperand(3);
16642     SDValue Base  = Op.getOperand(4);
16643     SDValue Scale = Op.getOperand(5);
16644     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16645   }
16646   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16647   case RDTSC: {
16648     SmallVector<SDValue, 2> Results;
16649     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16650                             Results);
16651     return DAG.getMergeValues(Results, dl);
16652   }
16653   // Read Performance Monitoring Counters.
16654   case RDPMC: {
16655     SmallVector<SDValue, 2> Results;
16656     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16657     return DAG.getMergeValues(Results, dl);
16658   }
16659   // XTEST intrinsics.
16660   case XTEST: {
16661     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16662     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16663     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16664                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16665                                 InTrans);
16666     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16667     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16668                        Ret, SDValue(InTrans.getNode(), 1));
16669   }
16670   // ADC/ADCX/SBB
16671   case ADX: {
16672     SmallVector<SDValue, 2> Results;
16673     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16674     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16675     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16676                                 DAG.getConstant(-1, dl, MVT::i8));
16677     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16678                               Op.getOperand(4), GenCF.getValue(1));
16679     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16680                                  Op.getOperand(5), MachinePointerInfo(),
16681                                  false, false, 0);
16682     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16683                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16684                                 Res.getValue(1));
16685     Results.push_back(SetCC);
16686     Results.push_back(Store);
16687     return DAG.getMergeValues(Results, dl);
16688   }
16689   case COMPRESS_TO_MEM: {
16690     SDLoc dl(Op);
16691     SDValue Mask = Op.getOperand(4);
16692     SDValue DataToCompress = Op.getOperand(3);
16693     SDValue Addr = Op.getOperand(2);
16694     SDValue Chain = Op.getOperand(0);
16695
16696     EVT VT = DataToCompress.getValueType();
16697     if (isAllOnes(Mask)) // return just a store
16698       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16699                           MachinePointerInfo(), false, false,
16700                           VT.getScalarSizeInBits()/8);
16701
16702     SDValue Compressed =
16703       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16704                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16705     return DAG.getStore(Chain, dl, Compressed, Addr,
16706                         MachinePointerInfo(), false, false,
16707                         VT.getScalarSizeInBits()/8);
16708   }
16709   case TRUNCATE_TO_MEM_VI8:
16710     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16711   case TRUNCATE_TO_MEM_VI16:
16712     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16713   case TRUNCATE_TO_MEM_VI32:
16714     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16715   case EXPAND_FROM_MEM: {
16716     SDLoc dl(Op);
16717     SDValue Mask = Op.getOperand(4);
16718     SDValue PassThru = Op.getOperand(3);
16719     SDValue Addr = Op.getOperand(2);
16720     SDValue Chain = Op.getOperand(0);
16721     EVT VT = Op.getValueType();
16722
16723     if (isAllOnes(Mask)) // return just a load
16724       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16725                          false, VT.getScalarSizeInBits()/8);
16726
16727     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16728                                        false, false, false,
16729                                        VT.getScalarSizeInBits()/8);
16730
16731     SDValue Results[] = {
16732       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16733                            Mask, PassThru, Subtarget, DAG), Chain};
16734     return DAG.getMergeValues(Results, dl);
16735   }
16736   }
16737 }
16738
16739 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16740                                            SelectionDAG &DAG) const {
16741   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16742   MFI->setReturnAddressIsTaken(true);
16743
16744   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16745     return SDValue();
16746
16747   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16748   SDLoc dl(Op);
16749   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16750
16751   if (Depth > 0) {
16752     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16753     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16754     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16755     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16756                        DAG.getNode(ISD::ADD, dl, PtrVT,
16757                                    FrameAddr, Offset),
16758                        MachinePointerInfo(), false, false, false, 0);
16759   }
16760
16761   // Just load the return address.
16762   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16763   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16764                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16765 }
16766
16767 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16768   MachineFunction &MF = DAG.getMachineFunction();
16769   MachineFrameInfo *MFI = MF.getFrameInfo();
16770   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16771   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16772   EVT VT = Op.getValueType();
16773
16774   MFI->setFrameAddressIsTaken(true);
16775
16776   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16777     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16778     // is not possible to crawl up the stack without looking at the unwind codes
16779     // simultaneously.
16780     int FrameAddrIndex = FuncInfo->getFAIndex();
16781     if (!FrameAddrIndex) {
16782       // Set up a frame object for the return address.
16783       unsigned SlotSize = RegInfo->getSlotSize();
16784       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16785           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16786       FuncInfo->setFAIndex(FrameAddrIndex);
16787     }
16788     return DAG.getFrameIndex(FrameAddrIndex, VT);
16789   }
16790
16791   unsigned FrameReg =
16792       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16793   SDLoc dl(Op);  // FIXME probably not meaningful
16794   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16795   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16796           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16797          "Invalid Frame Register!");
16798   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16799   while (Depth--)
16800     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16801                             MachinePointerInfo(),
16802                             false, false, false, 0);
16803   return FrameAddr;
16804 }
16805
16806 // FIXME? Maybe this could be a TableGen attribute on some registers and
16807 // this table could be generated automatically from RegInfo.
16808 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16809                                               SelectionDAG &DAG) const {
16810   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16811   const MachineFunction &MF = DAG.getMachineFunction();
16812
16813   unsigned Reg = StringSwitch<unsigned>(RegName)
16814                        .Case("esp", X86::ESP)
16815                        .Case("rsp", X86::RSP)
16816                        .Case("ebp", X86::EBP)
16817                        .Case("rbp", X86::RBP)
16818                        .Default(0);
16819
16820   if (Reg == X86::EBP || Reg == X86::RBP) {
16821     if (!TFI.hasFP(MF))
16822       report_fatal_error("register " + StringRef(RegName) +
16823                          " is allocatable: function has no frame pointer");
16824 #ifndef NDEBUG
16825     else {
16826       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16827       unsigned FrameReg =
16828           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16829       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16830              "Invalid Frame Register!");
16831     }
16832 #endif
16833   }
16834
16835   if (Reg)
16836     return Reg;
16837
16838   report_fatal_error("Invalid register name global variable");
16839 }
16840
16841 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16842                                                      SelectionDAG &DAG) const {
16843   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16844   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16845 }
16846
16847 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16848   SDValue Chain     = Op.getOperand(0);
16849   SDValue Offset    = Op.getOperand(1);
16850   SDValue Handler   = Op.getOperand(2);
16851   SDLoc dl      (Op);
16852
16853   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16854   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16855   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16856   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16857           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16858          "Invalid Frame Register!");
16859   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16860   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16861
16862   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16863                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16864                                                        dl));
16865   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16866   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16867                        false, false, 0);
16868   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16869
16870   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16871                      DAG.getRegister(StoreAddrReg, PtrVT));
16872 }
16873
16874 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16875   SDValue Chain = Op.getOperand(0);
16876   SDValue Dest = Op.getOperand(1);
16877   SDLoc DL(Op);
16878
16879   MVT PtrVT = getPointerTy(DAG.getDataLayout());
16880
16881   MachineFunction &MF = DAG.getMachineFunction();
16882   if (isAsynchronousEHPersonality(
16883           classifyEHPersonality(MF.getFunction()->getPersonalityFn()))) {
16884     // For SEH, codegen catchret as a branch for now.
16885     // FIXME: Insert something to restore the frame.
16886     return DAG.getNode(ISD::BR, DL, MVT::Other, Chain, Dest);
16887   }
16888
16889   unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16890
16891   // Load the address of the destination block.
16892   // FIXME: Do this without creating a BlockAddress.
16893   MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16894   BlockAddress *BA =
16895       BlockAddress::get(const_cast<Function *>(MF.getFunction()),
16896                         const_cast<BasicBlock *>(DestMBB->getBasicBlock()));
16897   DestMBB->setHasAddressTaken();
16898   SDValue BlockPtr = DAG.getBlockAddress(BA, PtrVT);
16899   Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, BlockPtr);
16900   return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16901                      DAG.getRegister(ReturnReg, PtrVT));
16902 }
16903
16904 SDValue X86TargetLowering::LowerCLEANUPRET(SDValue Op, SelectionDAG &DAG) const {
16905   return DAG.getNode(X86ISD::CLEANUPRET, SDLoc(Op), MVT::Other,
16906                      Op.getOperand(0));
16907 }
16908
16909 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16910                                                SelectionDAG &DAG) const {
16911   SDLoc DL(Op);
16912   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16913                      DAG.getVTList(MVT::i32, MVT::Other),
16914                      Op.getOperand(0), Op.getOperand(1));
16915 }
16916
16917 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16918                                                 SelectionDAG &DAG) const {
16919   SDLoc DL(Op);
16920   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16921                      Op.getOperand(0), Op.getOperand(1));
16922 }
16923
16924 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16925   return Op.getOperand(0);
16926 }
16927
16928 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16929                                                 SelectionDAG &DAG) const {
16930   SDValue Root = Op.getOperand(0);
16931   SDValue Trmp = Op.getOperand(1); // trampoline
16932   SDValue FPtr = Op.getOperand(2); // nested function
16933   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16934   SDLoc dl (Op);
16935
16936   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16937   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16938
16939   if (Subtarget->is64Bit()) {
16940     SDValue OutChains[6];
16941
16942     // Large code-model.
16943     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16944     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16945
16946     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16947     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16948
16949     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16950
16951     // Load the pointer to the nested function into R11.
16952     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16953     SDValue Addr = Trmp;
16954     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16955                                 Addr, MachinePointerInfo(TrmpAddr),
16956                                 false, false, 0);
16957
16958     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16959                        DAG.getConstant(2, dl, MVT::i64));
16960     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16961                                 MachinePointerInfo(TrmpAddr, 2),
16962                                 false, false, 2);
16963
16964     // Load the 'nest' parameter value into R10.
16965     // R10 is specified in X86CallingConv.td
16966     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16967     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16968                        DAG.getConstant(10, dl, MVT::i64));
16969     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16970                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16971                                 false, false, 0);
16972
16973     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16974                        DAG.getConstant(12, dl, MVT::i64));
16975     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16976                                 MachinePointerInfo(TrmpAddr, 12),
16977                                 false, false, 2);
16978
16979     // Jump to the nested function.
16980     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16981     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16982                        DAG.getConstant(20, dl, MVT::i64));
16983     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16984                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16985                                 false, false, 0);
16986
16987     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16988     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16989                        DAG.getConstant(22, dl, MVT::i64));
16990     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16991                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16992                                 false, false, 0);
16993
16994     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16995   } else {
16996     const Function *Func =
16997       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16998     CallingConv::ID CC = Func->getCallingConv();
16999     unsigned NestReg;
17000
17001     switch (CC) {
17002     default:
17003       llvm_unreachable("Unsupported calling convention");
17004     case CallingConv::C:
17005     case CallingConv::X86_StdCall: {
17006       // Pass 'nest' parameter in ECX.
17007       // Must be kept in sync with X86CallingConv.td
17008       NestReg = X86::ECX;
17009
17010       // Check that ECX wasn't needed by an 'inreg' parameter.
17011       FunctionType *FTy = Func->getFunctionType();
17012       const AttributeSet &Attrs = Func->getAttributes();
17013
17014       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17015         unsigned InRegCount = 0;
17016         unsigned Idx = 1;
17017
17018         for (FunctionType::param_iterator I = FTy->param_begin(),
17019              E = FTy->param_end(); I != E; ++I, ++Idx)
17020           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17021             auto &DL = DAG.getDataLayout();
17022             // FIXME: should only count parameters that are lowered to integers.
17023             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17024           }
17025
17026         if (InRegCount > 2) {
17027           report_fatal_error("Nest register in use - reduce number of inreg"
17028                              " parameters!");
17029         }
17030       }
17031       break;
17032     }
17033     case CallingConv::X86_FastCall:
17034     case CallingConv::X86_ThisCall:
17035     case CallingConv::Fast:
17036       // Pass 'nest' parameter in EAX.
17037       // Must be kept in sync with X86CallingConv.td
17038       NestReg = X86::EAX;
17039       break;
17040     }
17041
17042     SDValue OutChains[4];
17043     SDValue Addr, Disp;
17044
17045     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17046                        DAG.getConstant(10, dl, MVT::i32));
17047     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17048
17049     // This is storing the opcode for MOV32ri.
17050     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17051     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17052     OutChains[0] = DAG.getStore(Root, dl,
17053                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17054                                 Trmp, MachinePointerInfo(TrmpAddr),
17055                                 false, false, 0);
17056
17057     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17058                        DAG.getConstant(1, dl, MVT::i32));
17059     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17060                                 MachinePointerInfo(TrmpAddr, 1),
17061                                 false, false, 1);
17062
17063     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17064     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17065                        DAG.getConstant(5, dl, MVT::i32));
17066     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17067                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17068                                 false, false, 1);
17069
17070     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17071                        DAG.getConstant(6, dl, MVT::i32));
17072     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17073                                 MachinePointerInfo(TrmpAddr, 6),
17074                                 false, false, 1);
17075
17076     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17077   }
17078 }
17079
17080 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17081                                             SelectionDAG &DAG) const {
17082   /*
17083    The rounding mode is in bits 11:10 of FPSR, and has the following
17084    settings:
17085      00 Round to nearest
17086      01 Round to -inf
17087      10 Round to +inf
17088      11 Round to 0
17089
17090   FLT_ROUNDS, on the other hand, expects the following:
17091     -1 Undefined
17092      0 Round to 0
17093      1 Round to nearest
17094      2 Round to +inf
17095      3 Round to -inf
17096
17097   To perform the conversion, we do:
17098     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17099   */
17100
17101   MachineFunction &MF = DAG.getMachineFunction();
17102   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17103   unsigned StackAlignment = TFI.getStackAlignment();
17104   MVT VT = Op.getSimpleValueType();
17105   SDLoc DL(Op);
17106
17107   // Save FP Control Word to stack slot
17108   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17109   SDValue StackSlot =
17110       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17111
17112   MachineMemOperand *MMO =
17113       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17114                               MachineMemOperand::MOStore, 2, 2);
17115
17116   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17117   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17118                                           DAG.getVTList(MVT::Other),
17119                                           Ops, MVT::i16, MMO);
17120
17121   // Load FP Control Word from stack slot
17122   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17123                             MachinePointerInfo(), false, false, false, 0);
17124
17125   // Transform as necessary
17126   SDValue CWD1 =
17127     DAG.getNode(ISD::SRL, DL, MVT::i16,
17128                 DAG.getNode(ISD::AND, DL, MVT::i16,
17129                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17130                 DAG.getConstant(11, DL, MVT::i8));
17131   SDValue CWD2 =
17132     DAG.getNode(ISD::SRL, DL, MVT::i16,
17133                 DAG.getNode(ISD::AND, DL, MVT::i16,
17134                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17135                 DAG.getConstant(9, DL, MVT::i8));
17136
17137   SDValue RetVal =
17138     DAG.getNode(ISD::AND, DL, MVT::i16,
17139                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17140                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17141                             DAG.getConstant(1, DL, MVT::i16)),
17142                 DAG.getConstant(3, DL, MVT::i16));
17143
17144   return DAG.getNode((VT.getSizeInBits() < 16 ?
17145                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17146 }
17147
17148 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17149   MVT VT = Op.getSimpleValueType();
17150   EVT OpVT = VT;
17151   unsigned NumBits = VT.getSizeInBits();
17152   SDLoc dl(Op);
17153
17154   Op = Op.getOperand(0);
17155   if (VT == MVT::i8) {
17156     // Zero extend to i32 since there is not an i8 bsr.
17157     OpVT = MVT::i32;
17158     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17159   }
17160
17161   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17162   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17163   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17164
17165   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17166   SDValue Ops[] = {
17167     Op,
17168     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17169     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17170     Op.getValue(1)
17171   };
17172   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17173
17174   // Finally xor with NumBits-1.
17175   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17176                    DAG.getConstant(NumBits - 1, dl, OpVT));
17177
17178   if (VT == MVT::i8)
17179     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17180   return Op;
17181 }
17182
17183 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17184   MVT VT = Op.getSimpleValueType();
17185   EVT OpVT = VT;
17186   unsigned NumBits = VT.getSizeInBits();
17187   SDLoc dl(Op);
17188
17189   Op = Op.getOperand(0);
17190   if (VT == MVT::i8) {
17191     // Zero extend to i32 since there is not an i8 bsr.
17192     OpVT = MVT::i32;
17193     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17194   }
17195
17196   // Issue a bsr (scan bits in reverse).
17197   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17198   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17199
17200   // And xor with NumBits-1.
17201   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17202                    DAG.getConstant(NumBits - 1, dl, OpVT));
17203
17204   if (VT == MVT::i8)
17205     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17206   return Op;
17207 }
17208
17209 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17210   MVT VT = Op.getSimpleValueType();
17211   unsigned NumBits = VT.getSizeInBits();
17212   SDLoc dl(Op);
17213   Op = Op.getOperand(0);
17214
17215   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17216   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17217   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17218
17219   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17220   SDValue Ops[] = {
17221     Op,
17222     DAG.getConstant(NumBits, dl, VT),
17223     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17224     Op.getValue(1)
17225   };
17226   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17227 }
17228
17229 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17230 // ones, and then concatenate the result back.
17231 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17232   MVT VT = Op.getSimpleValueType();
17233
17234   assert(VT.is256BitVector() && VT.isInteger() &&
17235          "Unsupported value type for operation");
17236
17237   unsigned NumElems = VT.getVectorNumElements();
17238   SDLoc dl(Op);
17239
17240   // Extract the LHS vectors
17241   SDValue LHS = Op.getOperand(0);
17242   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17243   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17244
17245   // Extract the RHS vectors
17246   SDValue RHS = Op.getOperand(1);
17247   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17248   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17249
17250   MVT EltVT = VT.getVectorElementType();
17251   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17252
17253   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17254                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17255                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17256 }
17257
17258 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17259   if (Op.getValueType() == MVT::i1)
17260     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17261                        Op.getOperand(0), Op.getOperand(1));
17262   assert(Op.getSimpleValueType().is256BitVector() &&
17263          Op.getSimpleValueType().isInteger() &&
17264          "Only handle AVX 256-bit vector integer operation");
17265   return Lower256IntArith(Op, DAG);
17266 }
17267
17268 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17269   if (Op.getValueType() == MVT::i1)
17270     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17271                        Op.getOperand(0), Op.getOperand(1));
17272   assert(Op.getSimpleValueType().is256BitVector() &&
17273          Op.getSimpleValueType().isInteger() &&
17274          "Only handle AVX 256-bit vector integer operation");
17275   return Lower256IntArith(Op, DAG);
17276 }
17277
17278 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17279   assert(Op.getSimpleValueType().is256BitVector() &&
17280          Op.getSimpleValueType().isInteger() &&
17281          "Only handle AVX 256-bit vector integer operation");
17282   return Lower256IntArith(Op, DAG);
17283 }
17284
17285 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17286                         SelectionDAG &DAG) {
17287   SDLoc dl(Op);
17288   MVT VT = Op.getSimpleValueType();
17289
17290   if (VT == MVT::i1)
17291     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17292
17293   // Decompose 256-bit ops into smaller 128-bit ops.
17294   if (VT.is256BitVector() && !Subtarget->hasInt256())
17295     return Lower256IntArith(Op, DAG);
17296
17297   SDValue A = Op.getOperand(0);
17298   SDValue B = Op.getOperand(1);
17299
17300   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17301   // pairs, multiply and truncate.
17302   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17303     if (Subtarget->hasInt256()) {
17304       if (VT == MVT::v32i8) {
17305         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17306         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17307         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17308         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17309         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17310         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17311         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17312         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17313                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17314                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17315       }
17316
17317       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17318       return DAG.getNode(
17319           ISD::TRUNCATE, dl, VT,
17320           DAG.getNode(ISD::MUL, dl, ExVT,
17321                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17322                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17323     }
17324
17325     assert(VT == MVT::v16i8 &&
17326            "Pre-AVX2 support only supports v16i8 multiplication");
17327     MVT ExVT = MVT::v8i16;
17328
17329     // Extract the lo parts and sign extend to i16
17330     SDValue ALo, BLo;
17331     if (Subtarget->hasSSE41()) {
17332       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17333       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17334     } else {
17335       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17336                               -1, 4, -1, 5, -1, 6, -1, 7};
17337       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17338       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17339       ALo = DAG.getBitcast(ExVT, ALo);
17340       BLo = DAG.getBitcast(ExVT, BLo);
17341       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17342       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17343     }
17344
17345     // Extract the hi parts and sign extend to i16
17346     SDValue AHi, BHi;
17347     if (Subtarget->hasSSE41()) {
17348       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17349                               -1, -1, -1, -1, -1, -1, -1, -1};
17350       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17351       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17352       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17353       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17354     } else {
17355       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17356                               -1, 12, -1, 13, -1, 14, -1, 15};
17357       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17358       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17359       AHi = DAG.getBitcast(ExVT, AHi);
17360       BHi = DAG.getBitcast(ExVT, BHi);
17361       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17362       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17363     }
17364
17365     // Multiply, mask the lower 8bits of the lo/hi results and pack
17366     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17367     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17368     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17369     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17370     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17371   }
17372
17373   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17374   if (VT == MVT::v4i32) {
17375     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17376            "Should not custom lower when pmuldq is available!");
17377
17378     // Extract the odd parts.
17379     static const int UnpackMask[] = { 1, -1, 3, -1 };
17380     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17381     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17382
17383     // Multiply the even parts.
17384     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17385     // Now multiply odd parts.
17386     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17387
17388     Evens = DAG.getBitcast(VT, Evens);
17389     Odds = DAG.getBitcast(VT, Odds);
17390
17391     // Merge the two vectors back together with a shuffle. This expands into 2
17392     // shuffles.
17393     static const int ShufMask[] = { 0, 4, 2, 6 };
17394     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17395   }
17396
17397   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17398          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17399
17400   //  Ahi = psrlqi(a, 32);
17401   //  Bhi = psrlqi(b, 32);
17402   //
17403   //  AloBlo = pmuludq(a, b);
17404   //  AloBhi = pmuludq(a, Bhi);
17405   //  AhiBlo = pmuludq(Ahi, b);
17406
17407   //  AloBhi = psllqi(AloBhi, 32);
17408   //  AhiBlo = psllqi(AhiBlo, 32);
17409   //  return AloBlo + AloBhi + AhiBlo;
17410
17411   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17412   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17413
17414   SDValue AhiBlo = Ahi;
17415   SDValue AloBhi = Bhi;
17416   // Bit cast to 32-bit vectors for MULUDQ
17417   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17418                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17419   A = DAG.getBitcast(MulVT, A);
17420   B = DAG.getBitcast(MulVT, B);
17421   Ahi = DAG.getBitcast(MulVT, Ahi);
17422   Bhi = DAG.getBitcast(MulVT, Bhi);
17423
17424   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17425   // After shifting right const values the result may be all-zero.
17426   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17427     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17428     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17429   }
17430   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17431     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17432     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17433   }
17434
17435   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17436   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17437 }
17438
17439 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17440   assert(Subtarget->isTargetWin64() && "Unexpected target");
17441   EVT VT = Op.getValueType();
17442   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17443          "Unexpected return type for lowering");
17444
17445   RTLIB::Libcall LC;
17446   bool isSigned;
17447   switch (Op->getOpcode()) {
17448   default: llvm_unreachable("Unexpected request for libcall!");
17449   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17450   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17451   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17452   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17453   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17454   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17455   }
17456
17457   SDLoc dl(Op);
17458   SDValue InChain = DAG.getEntryNode();
17459
17460   TargetLowering::ArgListTy Args;
17461   TargetLowering::ArgListEntry Entry;
17462   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17463     EVT ArgVT = Op->getOperand(i).getValueType();
17464     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17465            "Unexpected argument type for lowering");
17466     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17467     Entry.Node = StackPtr;
17468     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17469                            false, false, 16);
17470     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17471     Entry.Ty = PointerType::get(ArgTy,0);
17472     Entry.isSExt = false;
17473     Entry.isZExt = false;
17474     Args.push_back(Entry);
17475   }
17476
17477   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17478                                          getPointerTy(DAG.getDataLayout()));
17479
17480   TargetLowering::CallLoweringInfo CLI(DAG);
17481   CLI.setDebugLoc(dl).setChain(InChain)
17482     .setCallee(getLibcallCallingConv(LC),
17483                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17484                Callee, std::move(Args), 0)
17485     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17486
17487   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17488   return DAG.getBitcast(VT, CallInfo.first);
17489 }
17490
17491 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17492                              SelectionDAG &DAG) {
17493   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17494   EVT VT = Op0.getValueType();
17495   SDLoc dl(Op);
17496
17497   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17498          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17499
17500   // PMULxD operations multiply each even value (starting at 0) of LHS with
17501   // the related value of RHS and produce a widen result.
17502   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17503   // => <2 x i64> <ae|cg>
17504   //
17505   // In other word, to have all the results, we need to perform two PMULxD:
17506   // 1. one with the even values.
17507   // 2. one with the odd values.
17508   // To achieve #2, with need to place the odd values at an even position.
17509   //
17510   // Place the odd value at an even position (basically, shift all values 1
17511   // step to the left):
17512   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17513   // <a|b|c|d> => <b|undef|d|undef>
17514   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17515   // <e|f|g|h> => <f|undef|h|undef>
17516   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17517
17518   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17519   // ints.
17520   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17521   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17522   unsigned Opcode =
17523       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17524   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17525   // => <2 x i64> <ae|cg>
17526   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17527   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17528   // => <2 x i64> <bf|dh>
17529   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17530
17531   // Shuffle it back into the right order.
17532   SDValue Highs, Lows;
17533   if (VT == MVT::v8i32) {
17534     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17535     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17536     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17537     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17538   } else {
17539     const int HighMask[] = {1, 5, 3, 7};
17540     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17541     const int LowMask[] = {0, 4, 2, 6};
17542     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17543   }
17544
17545   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17546   // unsigned multiply.
17547   if (IsSigned && !Subtarget->hasSSE41()) {
17548     SDValue ShAmt = DAG.getConstant(
17549         31, dl,
17550         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17551     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17552                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17553     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17554                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17555
17556     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17557     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17558   }
17559
17560   // The first result of MUL_LOHI is actually the low value, followed by the
17561   // high value.
17562   SDValue Ops[] = {Lows, Highs};
17563   return DAG.getMergeValues(Ops, dl);
17564 }
17565
17566 // Return true if the required (according to Opcode) shift-imm form is natively
17567 // supported by the Subtarget
17568 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17569                                         unsigned Opcode) {
17570   if (VT.getScalarSizeInBits() < 16)
17571     return false;
17572
17573   if (VT.is512BitVector() &&
17574       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17575     return true;
17576
17577   bool LShift = VT.is128BitVector() ||
17578     (VT.is256BitVector() && Subtarget->hasInt256());
17579
17580   bool AShift = LShift && (Subtarget->hasVLX() ||
17581     (VT != MVT::v2i64 && VT != MVT::v4i64));
17582   return (Opcode == ISD::SRA) ? AShift : LShift;
17583 }
17584
17585 // The shift amount is a variable, but it is the same for all vector lanes.
17586 // These instructions are defined together with shift-immediate.
17587 static
17588 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17589                                       unsigned Opcode) {
17590   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17591 }
17592
17593 // Return true if the required (according to Opcode) variable-shift form is
17594 // natively supported by the Subtarget
17595 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17596                                     unsigned Opcode) {
17597
17598   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17599     return false;
17600
17601   // vXi16 supported only on AVX-512, BWI
17602   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17603     return false;
17604
17605   if (VT.is512BitVector() || Subtarget->hasVLX())
17606     return true;
17607
17608   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17609   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17610   return (Opcode == ISD::SRA) ? AShift : LShift;
17611 }
17612
17613 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17614                                          const X86Subtarget *Subtarget) {
17615   MVT VT = Op.getSimpleValueType();
17616   SDLoc dl(Op);
17617   SDValue R = Op.getOperand(0);
17618   SDValue Amt = Op.getOperand(1);
17619
17620   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17621     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17622
17623   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17624     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17625     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17626     SDValue Ex = DAG.getBitcast(ExVT, R);
17627
17628     if (ShiftAmt >= 32) {
17629       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17630       SDValue Upper =
17631           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17632       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17633                                                  ShiftAmt - 32, DAG);
17634       if (VT == MVT::v2i64)
17635         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17636       if (VT == MVT::v4i64)
17637         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17638                                   {9, 1, 11, 3, 13, 5, 15, 7});
17639     } else {
17640       // SRA upper i32, SHL whole i64 and select lower i32.
17641       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17642                                                  ShiftAmt, DAG);
17643       SDValue Lower =
17644           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17645       Lower = DAG.getBitcast(ExVT, Lower);
17646       if (VT == MVT::v2i64)
17647         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17648       if (VT == MVT::v4i64)
17649         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17650                                   {8, 1, 10, 3, 12, 5, 14, 7});
17651     }
17652     return DAG.getBitcast(VT, Ex);
17653   };
17654
17655   // Optimize shl/srl/sra with constant shift amount.
17656   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17657     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17658       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17659
17660       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17661         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17662
17663       // i64 SRA needs to be performed as partial shifts.
17664       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17665           Op.getOpcode() == ISD::SRA)
17666         return ArithmeticShiftRight64(ShiftAmt);
17667
17668       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17669         unsigned NumElts = VT.getVectorNumElements();
17670         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17671
17672         if (Op.getOpcode() == ISD::SHL) {
17673           // Simple i8 add case
17674           if (ShiftAmt == 1)
17675             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17676
17677           // Make a large shift.
17678           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17679                                                    R, ShiftAmt, DAG);
17680           SHL = DAG.getBitcast(VT, SHL);
17681           // Zero out the rightmost bits.
17682           SmallVector<SDValue, 32> V(
17683               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17684           return DAG.getNode(ISD::AND, dl, VT, SHL,
17685                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17686         }
17687         if (Op.getOpcode() == ISD::SRL) {
17688           // Make a large shift.
17689           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17690                                                    R, ShiftAmt, DAG);
17691           SRL = DAG.getBitcast(VT, SRL);
17692           // Zero out the leftmost bits.
17693           SmallVector<SDValue, 32> V(
17694               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17695           return DAG.getNode(ISD::AND, dl, VT, SRL,
17696                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17697         }
17698         if (Op.getOpcode() == ISD::SRA) {
17699           if (ShiftAmt == 7) {
17700             // ashr(R, 7)  === cmp_slt(R, 0)
17701             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17702             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17703           }
17704
17705           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17706           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17707           SmallVector<SDValue, 32> V(NumElts,
17708                                      DAG.getConstant(128 >> ShiftAmt, dl,
17709                                                      MVT::i8));
17710           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17711           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17712           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17713           return Res;
17714         }
17715         llvm_unreachable("Unknown shift opcode.");
17716       }
17717     }
17718   }
17719
17720   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17721   if (!Subtarget->is64Bit() &&
17722       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17723
17724     // Peek through any splat that was introduced for i64 shift vectorization.
17725     int SplatIndex = -1;
17726     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17727       if (SVN->isSplat()) {
17728         SplatIndex = SVN->getSplatIndex();
17729         Amt = Amt.getOperand(0);
17730         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17731                "Splat shuffle referencing second operand");
17732       }
17733
17734     if (Amt.getOpcode() != ISD::BITCAST ||
17735         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17736       return SDValue();
17737
17738     Amt = Amt.getOperand(0);
17739     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17740                      VT.getVectorNumElements();
17741     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17742     uint64_t ShiftAmt = 0;
17743     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17744     for (unsigned i = 0; i != Ratio; ++i) {
17745       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17746       if (!C)
17747         return SDValue();
17748       // 6 == Log2(64)
17749       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17750     }
17751
17752     // Check remaining shift amounts (if not a splat).
17753     if (SplatIndex < 0) {
17754       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17755         uint64_t ShAmt = 0;
17756         for (unsigned j = 0; j != Ratio; ++j) {
17757           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17758           if (!C)
17759             return SDValue();
17760           // 6 == Log2(64)
17761           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17762         }
17763         if (ShAmt != ShiftAmt)
17764           return SDValue();
17765       }
17766     }
17767
17768     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17769       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17770
17771     if (Op.getOpcode() == ISD::SRA)
17772       return ArithmeticShiftRight64(ShiftAmt);
17773   }
17774
17775   return SDValue();
17776 }
17777
17778 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17779                                         const X86Subtarget* Subtarget) {
17780   MVT VT = Op.getSimpleValueType();
17781   SDLoc dl(Op);
17782   SDValue R = Op.getOperand(0);
17783   SDValue Amt = Op.getOperand(1);
17784
17785   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17786     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17787
17788   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17789     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17790
17791   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17792     SDValue BaseShAmt;
17793     EVT EltVT = VT.getVectorElementType();
17794
17795     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17796       // Check if this build_vector node is doing a splat.
17797       // If so, then set BaseShAmt equal to the splat value.
17798       BaseShAmt = BV->getSplatValue();
17799       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17800         BaseShAmt = SDValue();
17801     } else {
17802       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17803         Amt = Amt.getOperand(0);
17804
17805       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17806       if (SVN && SVN->isSplat()) {
17807         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17808         SDValue InVec = Amt.getOperand(0);
17809         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17810           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17811                  "Unexpected shuffle index found!");
17812           BaseShAmt = InVec.getOperand(SplatIdx);
17813         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17814            if (ConstantSDNode *C =
17815                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17816              if (C->getZExtValue() == SplatIdx)
17817                BaseShAmt = InVec.getOperand(1);
17818            }
17819         }
17820
17821         if (!BaseShAmt)
17822           // Avoid introducing an extract element from a shuffle.
17823           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17824                                   DAG.getIntPtrConstant(SplatIdx, dl));
17825       }
17826     }
17827
17828     if (BaseShAmt.getNode()) {
17829       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17830       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17831         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17832       else if (EltVT.bitsLT(MVT::i32))
17833         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17834
17835       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17836     }
17837   }
17838
17839   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17840   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17841       Amt.getOpcode() == ISD::BITCAST &&
17842       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17843     Amt = Amt.getOperand(0);
17844     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17845                      VT.getVectorNumElements();
17846     std::vector<SDValue> Vals(Ratio);
17847     for (unsigned i = 0; i != Ratio; ++i)
17848       Vals[i] = Amt.getOperand(i);
17849     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17850       for (unsigned j = 0; j != Ratio; ++j)
17851         if (Vals[j] != Amt.getOperand(i + j))
17852           return SDValue();
17853     }
17854
17855     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17856       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17857   }
17858   return SDValue();
17859 }
17860
17861 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17862                           SelectionDAG &DAG) {
17863   MVT VT = Op.getSimpleValueType();
17864   SDLoc dl(Op);
17865   SDValue R = Op.getOperand(0);
17866   SDValue Amt = Op.getOperand(1);
17867
17868   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17869   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17870
17871   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17872     return V;
17873
17874   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17875       return V;
17876
17877   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17878     return Op;
17879
17880   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17881   // shifts per-lane and then shuffle the partial results back together.
17882   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17883     // Splat the shift amounts so the scalar shifts above will catch it.
17884     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17885     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17886     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17887     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17888     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17889   }
17890
17891   // i64 vector arithmetic shift can be emulated with the transform:
17892   // M = lshr(SIGN_BIT, Amt)
17893   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17894   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17895       Op.getOpcode() == ISD::SRA) {
17896     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17897     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17898     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17899     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17900     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17901     return R;
17902   }
17903
17904   // If possible, lower this packed shift into a vector multiply instead of
17905   // expanding it into a sequence of scalar shifts.
17906   // Do this only if the vector shift count is a constant build_vector.
17907   if (Op.getOpcode() == ISD::SHL &&
17908       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17909        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17910       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17911     SmallVector<SDValue, 8> Elts;
17912     EVT SVT = VT.getScalarType();
17913     unsigned SVTBits = SVT.getSizeInBits();
17914     const APInt &One = APInt(SVTBits, 1);
17915     unsigned NumElems = VT.getVectorNumElements();
17916
17917     for (unsigned i=0; i !=NumElems; ++i) {
17918       SDValue Op = Amt->getOperand(i);
17919       if (Op->getOpcode() == ISD::UNDEF) {
17920         Elts.push_back(Op);
17921         continue;
17922       }
17923
17924       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17925       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17926       uint64_t ShAmt = C.getZExtValue();
17927       if (ShAmt >= SVTBits) {
17928         Elts.push_back(DAG.getUNDEF(SVT));
17929         continue;
17930       }
17931       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17932     }
17933     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17934     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17935   }
17936
17937   // Lower SHL with variable shift amount.
17938   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17939     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17940
17941     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17942                      DAG.getConstant(0x3f800000U, dl, VT));
17943     Op = DAG.getBitcast(MVT::v4f32, Op);
17944     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17945     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17946   }
17947
17948   // If possible, lower this shift as a sequence of two shifts by
17949   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17950   // Example:
17951   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17952   //
17953   // Could be rewritten as:
17954   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17955   //
17956   // The advantage is that the two shifts from the example would be
17957   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17958   // the vector shift into four scalar shifts plus four pairs of vector
17959   // insert/extract.
17960   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17961       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17962     unsigned TargetOpcode = X86ISD::MOVSS;
17963     bool CanBeSimplified;
17964     // The splat value for the first packed shift (the 'X' from the example).
17965     SDValue Amt1 = Amt->getOperand(0);
17966     // The splat value for the second packed shift (the 'Y' from the example).
17967     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17968                                         Amt->getOperand(2);
17969
17970     // See if it is possible to replace this node with a sequence of
17971     // two shifts followed by a MOVSS/MOVSD
17972     if (VT == MVT::v4i32) {
17973       // Check if it is legal to use a MOVSS.
17974       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17975                         Amt2 == Amt->getOperand(3);
17976       if (!CanBeSimplified) {
17977         // Otherwise, check if we can still simplify this node using a MOVSD.
17978         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17979                           Amt->getOperand(2) == Amt->getOperand(3);
17980         TargetOpcode = X86ISD::MOVSD;
17981         Amt2 = Amt->getOperand(2);
17982       }
17983     } else {
17984       // Do similar checks for the case where the machine value type
17985       // is MVT::v8i16.
17986       CanBeSimplified = Amt1 == Amt->getOperand(1);
17987       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17988         CanBeSimplified = Amt2 == Amt->getOperand(i);
17989
17990       if (!CanBeSimplified) {
17991         TargetOpcode = X86ISD::MOVSD;
17992         CanBeSimplified = true;
17993         Amt2 = Amt->getOperand(4);
17994         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17995           CanBeSimplified = Amt1 == Amt->getOperand(i);
17996         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17997           CanBeSimplified = Amt2 == Amt->getOperand(j);
17998       }
17999     }
18000
18001     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18002         isa<ConstantSDNode>(Amt2)) {
18003       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18004       EVT CastVT = MVT::v4i32;
18005       SDValue Splat1 =
18006         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18007       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18008       SDValue Splat2 =
18009         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18010       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18011       if (TargetOpcode == X86ISD::MOVSD)
18012         CastVT = MVT::v2i64;
18013       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18014       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18015       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18016                                             BitCast1, DAG);
18017       return DAG.getBitcast(VT, Result);
18018     }
18019   }
18020
18021   // v4i32 Non Uniform Shifts.
18022   // If the shift amount is constant we can shift each lane using the SSE2
18023   // immediate shifts, else we need to zero-extend each lane to the lower i64
18024   // and shift using the SSE2 variable shifts.
18025   // The separate results can then be blended together.
18026   if (VT == MVT::v4i32) {
18027     unsigned Opc = Op.getOpcode();
18028     SDValue Amt0, Amt1, Amt2, Amt3;
18029     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18030       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18031       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18032       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18033       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18034     } else {
18035       // ISD::SHL is handled above but we include it here for completeness.
18036       switch (Opc) {
18037       default:
18038         llvm_unreachable("Unknown target vector shift node");
18039       case ISD::SHL:
18040         Opc = X86ISD::VSHL;
18041         break;
18042       case ISD::SRL:
18043         Opc = X86ISD::VSRL;
18044         break;
18045       case ISD::SRA:
18046         Opc = X86ISD::VSRA;
18047         break;
18048       }
18049       // The SSE2 shifts use the lower i64 as the same shift amount for
18050       // all lanes and the upper i64 is ignored. These shuffle masks
18051       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18052       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18053       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18054       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18055       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18056       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18057     }
18058
18059     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18060     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18061     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18062     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18063     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18064     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18065     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18066   }
18067
18068   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18069     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18070     unsigned ShiftOpcode = Op->getOpcode();
18071
18072     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18073       // On SSE41 targets we make use of the fact that VSELECT lowers
18074       // to PBLENDVB which selects bytes based just on the sign bit.
18075       if (Subtarget->hasSSE41()) {
18076         V0 = DAG.getBitcast(VT, V0);
18077         V1 = DAG.getBitcast(VT, V1);
18078         Sel = DAG.getBitcast(VT, Sel);
18079         return DAG.getBitcast(SelVT,
18080                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18081       }
18082       // On pre-SSE41 targets we test for the sign bit by comparing to
18083       // zero - a negative value will set all bits of the lanes to true
18084       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18085       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18086       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18087       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18088     };
18089
18090     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18091     // We can safely do this using i16 shifts as we're only interested in
18092     // the 3 lower bits of each byte.
18093     Amt = DAG.getBitcast(ExtVT, Amt);
18094     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18095     Amt = DAG.getBitcast(VT, Amt);
18096
18097     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18098       // r = VSELECT(r, shift(r, 4), a);
18099       SDValue M =
18100           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18101       R = SignBitSelect(VT, Amt, M, R);
18102
18103       // a += a
18104       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18105
18106       // r = VSELECT(r, shift(r, 2), a);
18107       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18108       R = SignBitSelect(VT, Amt, M, R);
18109
18110       // a += a
18111       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18112
18113       // return VSELECT(r, shift(r, 1), a);
18114       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18115       R = SignBitSelect(VT, Amt, M, R);
18116       return R;
18117     }
18118
18119     if (Op->getOpcode() == ISD::SRA) {
18120       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18121       // so we can correctly sign extend. We don't care what happens to the
18122       // lower byte.
18123       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18124       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18125       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18126       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18127       ALo = DAG.getBitcast(ExtVT, ALo);
18128       AHi = DAG.getBitcast(ExtVT, AHi);
18129       RLo = DAG.getBitcast(ExtVT, RLo);
18130       RHi = DAG.getBitcast(ExtVT, RHi);
18131
18132       // r = VSELECT(r, shift(r, 4), a);
18133       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18134                                 DAG.getConstant(4, dl, ExtVT));
18135       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18136                                 DAG.getConstant(4, dl, ExtVT));
18137       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18138       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18139
18140       // a += a
18141       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18142       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18143
18144       // r = VSELECT(r, shift(r, 2), a);
18145       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18146                         DAG.getConstant(2, dl, ExtVT));
18147       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18148                         DAG.getConstant(2, dl, ExtVT));
18149       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18150       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18151
18152       // a += a
18153       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18154       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18155
18156       // r = VSELECT(r, shift(r, 1), a);
18157       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18158                         DAG.getConstant(1, dl, ExtVT));
18159       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18160                         DAG.getConstant(1, dl, ExtVT));
18161       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18162       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18163
18164       // Logical shift the result back to the lower byte, leaving a zero upper
18165       // byte
18166       // meaning that we can safely pack with PACKUSWB.
18167       RLo =
18168           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18169       RHi =
18170           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18171       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18172     }
18173   }
18174
18175   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18176   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18177   // solution better.
18178   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18179     MVT ExtVT = MVT::v8i32;
18180     unsigned ExtOpc =
18181         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18182     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18183     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18184     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18185                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18186   }
18187
18188   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18189     MVT ExtVT = MVT::v8i32;
18190     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18191     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18192     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18193     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18194     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18195     ALo = DAG.getBitcast(ExtVT, ALo);
18196     AHi = DAG.getBitcast(ExtVT, AHi);
18197     RLo = DAG.getBitcast(ExtVT, RLo);
18198     RHi = DAG.getBitcast(ExtVT, RHi);
18199     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18200     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18201     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18202     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18203     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18204   }
18205
18206   if (VT == MVT::v8i16) {
18207     unsigned ShiftOpcode = Op->getOpcode();
18208
18209     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18210       // On SSE41 targets we make use of the fact that VSELECT lowers
18211       // to PBLENDVB which selects bytes based just on the sign bit.
18212       if (Subtarget->hasSSE41()) {
18213         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18214         V0 = DAG.getBitcast(ExtVT, V0);
18215         V1 = DAG.getBitcast(ExtVT, V1);
18216         Sel = DAG.getBitcast(ExtVT, Sel);
18217         return DAG.getBitcast(
18218             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18219       }
18220       // On pre-SSE41 targets we splat the sign bit - a negative value will
18221       // set all bits of the lanes to true and VSELECT uses that in
18222       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18223       SDValue C =
18224           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18225       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18226     };
18227
18228     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18229     if (Subtarget->hasSSE41()) {
18230       // On SSE41 targets we need to replicate the shift mask in both
18231       // bytes for PBLENDVB.
18232       Amt = DAG.getNode(
18233           ISD::OR, dl, VT,
18234           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18235           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18236     } else {
18237       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18238     }
18239
18240     // r = VSELECT(r, shift(r, 8), a);
18241     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18242     R = SignBitSelect(Amt, M, R);
18243
18244     // a += a
18245     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18246
18247     // r = VSELECT(r, shift(r, 4), a);
18248     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18249     R = SignBitSelect(Amt, M, R);
18250
18251     // a += a
18252     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18253
18254     // r = VSELECT(r, shift(r, 2), a);
18255     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18256     R = SignBitSelect(Amt, M, R);
18257
18258     // a += a
18259     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18260
18261     // return VSELECT(r, shift(r, 1), a);
18262     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18263     R = SignBitSelect(Amt, M, R);
18264     return R;
18265   }
18266
18267   // Decompose 256-bit shifts into smaller 128-bit shifts.
18268   if (VT.is256BitVector()) {
18269     unsigned NumElems = VT.getVectorNumElements();
18270     MVT EltVT = VT.getVectorElementType();
18271     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18272
18273     // Extract the two vectors
18274     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18275     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18276
18277     // Recreate the shift amount vectors
18278     SDValue Amt1, Amt2;
18279     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18280       // Constant shift amount
18281       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18282       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18283       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18284
18285       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18286       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18287     } else {
18288       // Variable shift amount
18289       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18290       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18291     }
18292
18293     // Issue new vector shifts for the smaller types
18294     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18295     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18296
18297     // Concatenate the result back
18298     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18299   }
18300
18301   return SDValue();
18302 }
18303
18304 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18305   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18306   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18307   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18308   // has only one use.
18309   SDNode *N = Op.getNode();
18310   SDValue LHS = N->getOperand(0);
18311   SDValue RHS = N->getOperand(1);
18312   unsigned BaseOp = 0;
18313   unsigned Cond = 0;
18314   SDLoc DL(Op);
18315   switch (Op.getOpcode()) {
18316   default: llvm_unreachable("Unknown ovf instruction!");
18317   case ISD::SADDO:
18318     // A subtract of one will be selected as a INC. Note that INC doesn't
18319     // set CF, so we can't do this for UADDO.
18320     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18321       if (C->isOne()) {
18322         BaseOp = X86ISD::INC;
18323         Cond = X86::COND_O;
18324         break;
18325       }
18326     BaseOp = X86ISD::ADD;
18327     Cond = X86::COND_O;
18328     break;
18329   case ISD::UADDO:
18330     BaseOp = X86ISD::ADD;
18331     Cond = X86::COND_B;
18332     break;
18333   case ISD::SSUBO:
18334     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18335     // set CF, so we can't do this for USUBO.
18336     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18337       if (C->isOne()) {
18338         BaseOp = X86ISD::DEC;
18339         Cond = X86::COND_O;
18340         break;
18341       }
18342     BaseOp = X86ISD::SUB;
18343     Cond = X86::COND_O;
18344     break;
18345   case ISD::USUBO:
18346     BaseOp = X86ISD::SUB;
18347     Cond = X86::COND_B;
18348     break;
18349   case ISD::SMULO:
18350     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18351     Cond = X86::COND_O;
18352     break;
18353   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18354     if (N->getValueType(0) == MVT::i8) {
18355       BaseOp = X86ISD::UMUL8;
18356       Cond = X86::COND_O;
18357       break;
18358     }
18359     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18360                                  MVT::i32);
18361     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18362
18363     SDValue SetCC =
18364       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18365                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18366                   SDValue(Sum.getNode(), 2));
18367
18368     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18369   }
18370   }
18371
18372   // Also sets EFLAGS.
18373   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18374   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18375
18376   SDValue SetCC =
18377     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18378                 DAG.getConstant(Cond, DL, MVT::i32),
18379                 SDValue(Sum.getNode(), 1));
18380
18381   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18382 }
18383
18384 /// Returns true if the operand type is exactly twice the native width, and
18385 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18386 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18387 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18388 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18389   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18390
18391   if (OpWidth == 64)
18392     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18393   else if (OpWidth == 128)
18394     return Subtarget->hasCmpxchg16b();
18395   else
18396     return false;
18397 }
18398
18399 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18400   return needsCmpXchgNb(SI->getValueOperand()->getType());
18401 }
18402
18403 // Note: this turns large loads into lock cmpxchg8b/16b.
18404 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18405 TargetLowering::AtomicExpansionKind
18406 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18407   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18408   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18409                                                : AtomicExpansionKind::None;
18410 }
18411
18412 TargetLowering::AtomicExpansionKind
18413 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18414   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18415   Type *MemType = AI->getType();
18416
18417   // If the operand is too big, we must see if cmpxchg8/16b is available
18418   // and default to library calls otherwise.
18419   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18420     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18421                                    : AtomicExpansionKind::None;
18422   }
18423
18424   AtomicRMWInst::BinOp Op = AI->getOperation();
18425   switch (Op) {
18426   default:
18427     llvm_unreachable("Unknown atomic operation");
18428   case AtomicRMWInst::Xchg:
18429   case AtomicRMWInst::Add:
18430   case AtomicRMWInst::Sub:
18431     // It's better to use xadd, xsub or xchg for these in all cases.
18432     return AtomicExpansionKind::None;
18433   case AtomicRMWInst::Or:
18434   case AtomicRMWInst::And:
18435   case AtomicRMWInst::Xor:
18436     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18437     // prefix to a normal instruction for these operations.
18438     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18439                             : AtomicExpansionKind::None;
18440   case AtomicRMWInst::Nand:
18441   case AtomicRMWInst::Max:
18442   case AtomicRMWInst::Min:
18443   case AtomicRMWInst::UMax:
18444   case AtomicRMWInst::UMin:
18445     // These always require a non-trivial set of data operations on x86. We must
18446     // use a cmpxchg loop.
18447     return AtomicExpansionKind::CmpXChg;
18448   }
18449 }
18450
18451 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18452   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18453   // no-sse2). There isn't any reason to disable it if the target processor
18454   // supports it.
18455   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18456 }
18457
18458 LoadInst *
18459 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18460   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18461   Type *MemType = AI->getType();
18462   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18463   // there is no benefit in turning such RMWs into loads, and it is actually
18464   // harmful as it introduces a mfence.
18465   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18466     return nullptr;
18467
18468   auto Builder = IRBuilder<>(AI);
18469   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18470   auto SynchScope = AI->getSynchScope();
18471   // We must restrict the ordering to avoid generating loads with Release or
18472   // ReleaseAcquire orderings.
18473   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18474   auto Ptr = AI->getPointerOperand();
18475
18476   // Before the load we need a fence. Here is an example lifted from
18477   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18478   // is required:
18479   // Thread 0:
18480   //   x.store(1, relaxed);
18481   //   r1 = y.fetch_add(0, release);
18482   // Thread 1:
18483   //   y.fetch_add(42, acquire);
18484   //   r2 = x.load(relaxed);
18485   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18486   // lowered to just a load without a fence. A mfence flushes the store buffer,
18487   // making the optimization clearly correct.
18488   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18489   // otherwise, we might be able to be more aggressive on relaxed idempotent
18490   // rmw. In practice, they do not look useful, so we don't try to be
18491   // especially clever.
18492   if (SynchScope == SingleThread)
18493     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18494     // the IR level, so we must wrap it in an intrinsic.
18495     return nullptr;
18496
18497   if (!hasMFENCE(*Subtarget))
18498     // FIXME: it might make sense to use a locked operation here but on a
18499     // different cache-line to prevent cache-line bouncing. In practice it
18500     // is probably a small win, and x86 processors without mfence are rare
18501     // enough that we do not bother.
18502     return nullptr;
18503
18504   Function *MFence =
18505       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18506   Builder.CreateCall(MFence, {});
18507
18508   // Finally we can emit the atomic load.
18509   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18510           AI->getType()->getPrimitiveSizeInBits());
18511   Loaded->setAtomic(Order, SynchScope);
18512   AI->replaceAllUsesWith(Loaded);
18513   AI->eraseFromParent();
18514   return Loaded;
18515 }
18516
18517 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18518                                  SelectionDAG &DAG) {
18519   SDLoc dl(Op);
18520   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18521     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18522   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18523     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18524
18525   // The only fence that needs an instruction is a sequentially-consistent
18526   // cross-thread fence.
18527   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18528     if (hasMFENCE(*Subtarget))
18529       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18530
18531     SDValue Chain = Op.getOperand(0);
18532     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18533     SDValue Ops[] = {
18534       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18535       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18536       DAG.getRegister(0, MVT::i32),            // Index
18537       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18538       DAG.getRegister(0, MVT::i32),            // Segment.
18539       Zero,
18540       Chain
18541     };
18542     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18543     return SDValue(Res, 0);
18544   }
18545
18546   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18547   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18548 }
18549
18550 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18551                              SelectionDAG &DAG) {
18552   MVT T = Op.getSimpleValueType();
18553   SDLoc DL(Op);
18554   unsigned Reg = 0;
18555   unsigned size = 0;
18556   switch(T.SimpleTy) {
18557   default: llvm_unreachable("Invalid value type!");
18558   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18559   case MVT::i16: Reg = X86::AX;  size = 2; break;
18560   case MVT::i32: Reg = X86::EAX; size = 4; break;
18561   case MVT::i64:
18562     assert(Subtarget->is64Bit() && "Node not type legal!");
18563     Reg = X86::RAX; size = 8;
18564     break;
18565   }
18566   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18567                                   Op.getOperand(2), SDValue());
18568   SDValue Ops[] = { cpIn.getValue(0),
18569                     Op.getOperand(1),
18570                     Op.getOperand(3),
18571                     DAG.getTargetConstant(size, DL, MVT::i8),
18572                     cpIn.getValue(1) };
18573   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18574   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18575   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18576                                            Ops, T, MMO);
18577
18578   SDValue cpOut =
18579     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18580   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18581                                       MVT::i32, cpOut.getValue(2));
18582   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18583                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18584                                 EFLAGS);
18585
18586   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18587   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18588   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18589   return SDValue();
18590 }
18591
18592 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18593                             SelectionDAG &DAG) {
18594   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18595   MVT DstVT = Op.getSimpleValueType();
18596
18597   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18598     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18599     if (DstVT != MVT::f64)
18600       // This conversion needs to be expanded.
18601       return SDValue();
18602
18603     SDValue InVec = Op->getOperand(0);
18604     SDLoc dl(Op);
18605     unsigned NumElts = SrcVT.getVectorNumElements();
18606     EVT SVT = SrcVT.getVectorElementType();
18607
18608     // Widen the vector in input in the case of MVT::v2i32.
18609     // Example: from MVT::v2i32 to MVT::v4i32.
18610     SmallVector<SDValue, 16> Elts;
18611     for (unsigned i = 0, e = NumElts; i != e; ++i)
18612       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18613                                  DAG.getIntPtrConstant(i, dl)));
18614
18615     // Explicitly mark the extra elements as Undef.
18616     Elts.append(NumElts, DAG.getUNDEF(SVT));
18617
18618     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18619     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18620     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18621     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18622                        DAG.getIntPtrConstant(0, dl));
18623   }
18624
18625   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18626          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18627   assert((DstVT == MVT::i64 ||
18628           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18629          "Unexpected custom BITCAST");
18630   // i64 <=> MMX conversions are Legal.
18631   if (SrcVT==MVT::i64 && DstVT.isVector())
18632     return Op;
18633   if (DstVT==MVT::i64 && SrcVT.isVector())
18634     return Op;
18635   // MMX <=> MMX conversions are Legal.
18636   if (SrcVT.isVector() && DstVT.isVector())
18637     return Op;
18638   // All other conversions need to be expanded.
18639   return SDValue();
18640 }
18641
18642 /// Compute the horizontal sum of bytes in V for the elements of VT.
18643 ///
18644 /// Requires V to be a byte vector and VT to be an integer vector type with
18645 /// wider elements than V's type. The width of the elements of VT determines
18646 /// how many bytes of V are summed horizontally to produce each element of the
18647 /// result.
18648 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18649                                       const X86Subtarget *Subtarget,
18650                                       SelectionDAG &DAG) {
18651   SDLoc DL(V);
18652   MVT ByteVecVT = V.getSimpleValueType();
18653   MVT EltVT = VT.getVectorElementType();
18654   int NumElts = VT.getVectorNumElements();
18655   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18656          "Expected value to have byte element type.");
18657   assert(EltVT != MVT::i8 &&
18658          "Horizontal byte sum only makes sense for wider elements!");
18659   unsigned VecSize = VT.getSizeInBits();
18660   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18661
18662   // PSADBW instruction horizontally add all bytes and leave the result in i64
18663   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18664   if (EltVT == MVT::i64) {
18665     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18666     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18667     return DAG.getBitcast(VT, V);
18668   }
18669
18670   if (EltVT == MVT::i32) {
18671     // We unpack the low half and high half into i32s interleaved with zeros so
18672     // that we can use PSADBW to horizontally sum them. The most useful part of
18673     // this is that it lines up the results of two PSADBW instructions to be
18674     // two v2i64 vectors which concatenated are the 4 population counts. We can
18675     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18676     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18677     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18678     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18679
18680     // Do the horizontal sums into two v2i64s.
18681     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18682     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18683                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18684     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18685                        DAG.getBitcast(ByteVecVT, High), Zeros);
18686
18687     // Merge them together.
18688     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18689     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18690                     DAG.getBitcast(ShortVecVT, Low),
18691                     DAG.getBitcast(ShortVecVT, High));
18692
18693     return DAG.getBitcast(VT, V);
18694   }
18695
18696   // The only element type left is i16.
18697   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18698
18699   // To obtain pop count for each i16 element starting from the pop count for
18700   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18701   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18702   // directly supported.
18703   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18704   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18705   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18706   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18707                   DAG.getBitcast(ByteVecVT, V));
18708   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18709 }
18710
18711 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18712                                         const X86Subtarget *Subtarget,
18713                                         SelectionDAG &DAG) {
18714   MVT VT = Op.getSimpleValueType();
18715   MVT EltVT = VT.getVectorElementType();
18716   unsigned VecSize = VT.getSizeInBits();
18717
18718   // Implement a lookup table in register by using an algorithm based on:
18719   // http://wm.ite.pl/articles/sse-popcount.html
18720   //
18721   // The general idea is that every lower byte nibble in the input vector is an
18722   // index into a in-register pre-computed pop count table. We then split up the
18723   // input vector in two new ones: (1) a vector with only the shifted-right
18724   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18725   // masked out higher ones) for each byte. PSHUB is used separately with both
18726   // to index the in-register table. Next, both are added and the result is a
18727   // i8 vector where each element contains the pop count for input byte.
18728   //
18729   // To obtain the pop count for elements != i8, we follow up with the same
18730   // approach and use additional tricks as described below.
18731   //
18732   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18733                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18734                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18735                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18736
18737   int NumByteElts = VecSize / 8;
18738   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18739   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18740   SmallVector<SDValue, 16> LUTVec;
18741   for (int i = 0; i < NumByteElts; ++i)
18742     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18743   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18744   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18745                                   DAG.getConstant(0x0F, DL, MVT::i8));
18746   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18747
18748   // High nibbles
18749   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18750   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18751   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18752
18753   // Low nibbles
18754   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18755
18756   // The input vector is used as the shuffle mask that index elements into the
18757   // LUT. After counting low and high nibbles, add the vector to obtain the
18758   // final pop count per i8 element.
18759   SDValue HighPopCnt =
18760       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18761   SDValue LowPopCnt =
18762       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18763   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18764
18765   if (EltVT == MVT::i8)
18766     return PopCnt;
18767
18768   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18769 }
18770
18771 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18772                                        const X86Subtarget *Subtarget,
18773                                        SelectionDAG &DAG) {
18774   MVT VT = Op.getSimpleValueType();
18775   assert(VT.is128BitVector() &&
18776          "Only 128-bit vector bitmath lowering supported.");
18777
18778   int VecSize = VT.getSizeInBits();
18779   MVT EltVT = VT.getVectorElementType();
18780   int Len = EltVT.getSizeInBits();
18781
18782   // This is the vectorized version of the "best" algorithm from
18783   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18784   // with a minor tweak to use a series of adds + shifts instead of vector
18785   // multiplications. Implemented for all integer vector types. We only use
18786   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18787   // much faster, even faster than using native popcnt instructions.
18788
18789   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18790     MVT VT = V.getSimpleValueType();
18791     SmallVector<SDValue, 32> Shifters(
18792         VT.getVectorNumElements(),
18793         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18794     return DAG.getNode(OpCode, DL, VT, V,
18795                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18796   };
18797   auto GetMask = [&](SDValue V, APInt Mask) {
18798     MVT VT = V.getSimpleValueType();
18799     SmallVector<SDValue, 32> Masks(
18800         VT.getVectorNumElements(),
18801         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18802     return DAG.getNode(ISD::AND, DL, VT, V,
18803                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18804   };
18805
18806   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18807   // x86, so set the SRL type to have elements at least i16 wide. This is
18808   // correct because all of our SRLs are followed immediately by a mask anyways
18809   // that handles any bits that sneak into the high bits of the byte elements.
18810   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18811
18812   SDValue V = Op;
18813
18814   // v = v - ((v >> 1) & 0x55555555...)
18815   SDValue Srl =
18816       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18817   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18818   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18819
18820   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18821   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18822   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18823   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18824   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18825
18826   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18827   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18828   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18829   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18830
18831   // At this point, V contains the byte-wise population count, and we are
18832   // merely doing a horizontal sum if necessary to get the wider element
18833   // counts.
18834   if (EltVT == MVT::i8)
18835     return V;
18836
18837   return LowerHorizontalByteSum(
18838       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18839       DAG);
18840 }
18841
18842 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18843                                 SelectionDAG &DAG) {
18844   MVT VT = Op.getSimpleValueType();
18845   // FIXME: Need to add AVX-512 support here!
18846   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18847          "Unknown CTPOP type to handle");
18848   SDLoc DL(Op.getNode());
18849   SDValue Op0 = Op.getOperand(0);
18850
18851   if (!Subtarget->hasSSSE3()) {
18852     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18853     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18854     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18855   }
18856
18857   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18858     unsigned NumElems = VT.getVectorNumElements();
18859
18860     // Extract each 128-bit vector, compute pop count and concat the result.
18861     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18862     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18863
18864     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18865                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18866                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18867   }
18868
18869   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18870 }
18871
18872 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18873                           SelectionDAG &DAG) {
18874   assert(Op.getValueType().isVector() &&
18875          "We only do custom lowering for vector population count.");
18876   return LowerVectorCTPOP(Op, Subtarget, DAG);
18877 }
18878
18879 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18880   SDNode *Node = Op.getNode();
18881   SDLoc dl(Node);
18882   EVT T = Node->getValueType(0);
18883   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18884                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18885   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18886                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18887                        Node->getOperand(0),
18888                        Node->getOperand(1), negOp,
18889                        cast<AtomicSDNode>(Node)->getMemOperand(),
18890                        cast<AtomicSDNode>(Node)->getOrdering(),
18891                        cast<AtomicSDNode>(Node)->getSynchScope());
18892 }
18893
18894 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18895   SDNode *Node = Op.getNode();
18896   SDLoc dl(Node);
18897   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18898
18899   // Convert seq_cst store -> xchg
18900   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18901   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18902   //        (The only way to get a 16-byte store is cmpxchg16b)
18903   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18904   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18905       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18906     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18907                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18908                                  Node->getOperand(0),
18909                                  Node->getOperand(1), Node->getOperand(2),
18910                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18911                                  cast<AtomicSDNode>(Node)->getOrdering(),
18912                                  cast<AtomicSDNode>(Node)->getSynchScope());
18913     return Swap.getValue(1);
18914   }
18915   // Other atomic stores have a simple pattern.
18916   return Op;
18917 }
18918
18919 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18920   EVT VT = Op.getNode()->getSimpleValueType(0);
18921
18922   // Let legalize expand this if it isn't a legal type yet.
18923   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18924     return SDValue();
18925
18926   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18927
18928   unsigned Opc;
18929   bool ExtraOp = false;
18930   switch (Op.getOpcode()) {
18931   default: llvm_unreachable("Invalid code");
18932   case ISD::ADDC: Opc = X86ISD::ADD; break;
18933   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18934   case ISD::SUBC: Opc = X86ISD::SUB; break;
18935   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18936   }
18937
18938   if (!ExtraOp)
18939     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18940                        Op.getOperand(1));
18941   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18942                      Op.getOperand(1), Op.getOperand(2));
18943 }
18944
18945 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18946                             SelectionDAG &DAG) {
18947   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18948
18949   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18950   // which returns the values as { float, float } (in XMM0) or
18951   // { double, double } (which is returned in XMM0, XMM1).
18952   SDLoc dl(Op);
18953   SDValue Arg = Op.getOperand(0);
18954   EVT ArgVT = Arg.getValueType();
18955   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18956
18957   TargetLowering::ArgListTy Args;
18958   TargetLowering::ArgListEntry Entry;
18959
18960   Entry.Node = Arg;
18961   Entry.Ty = ArgTy;
18962   Entry.isSExt = false;
18963   Entry.isZExt = false;
18964   Args.push_back(Entry);
18965
18966   bool isF64 = ArgVT == MVT::f64;
18967   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18968   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18969   // the results are returned via SRet in memory.
18970   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18972   SDValue Callee =
18973       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18974
18975   Type *RetTy = isF64
18976     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18977     : (Type*)VectorType::get(ArgTy, 4);
18978
18979   TargetLowering::CallLoweringInfo CLI(DAG);
18980   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18981     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18982
18983   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18984
18985   if (isF64)
18986     // Returned in xmm0 and xmm1.
18987     return CallResult.first;
18988
18989   // Returned in bits 0:31 and 32:64 xmm0.
18990   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18991                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18992   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18993                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18994   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18995   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18996 }
18997
18998 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18999                              SelectionDAG &DAG) {
19000   assert(Subtarget->hasAVX512() &&
19001          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19002
19003   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19004   EVT VT = N->getValue().getValueType();
19005   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19006   SDLoc dl(Op);
19007
19008   // X86 scatter kills mask register, so its type should be added to
19009   // the list of return values
19010   if (N->getNumValues() == 1) {
19011     SDValue Index = N->getIndex();
19012     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19013         !Index.getValueType().is512BitVector())
19014       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19015
19016     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19017     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19018                       N->getOperand(3), Index };
19019
19020     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19021     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19022     return SDValue(NewScatter.getNode(), 0);
19023   }
19024   return Op;
19025 }
19026
19027 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19028                             SelectionDAG &DAG) {
19029   assert(Subtarget->hasAVX512() &&
19030          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19031
19032   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19033   EVT VT = Op.getValueType();
19034   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19035   SDLoc dl(Op);
19036
19037   SDValue Index = N->getIndex();
19038   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19039       !Index.getValueType().is512BitVector()) {
19040     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19041     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19042                       N->getOperand(3), Index };
19043     DAG.UpdateNodeOperands(N, Ops);
19044   }
19045   return Op;
19046 }
19047
19048 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19049                                                     SelectionDAG &DAG) const {
19050   // TODO: Eventually, the lowering of these nodes should be informed by or
19051   // deferred to the GC strategy for the function in which they appear. For
19052   // now, however, they must be lowered to something. Since they are logically
19053   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19054   // require special handling for these nodes), lower them as literal NOOPs for
19055   // the time being.
19056   SmallVector<SDValue, 2> Ops;
19057
19058   Ops.push_back(Op.getOperand(0));
19059   if (Op->getGluedNode())
19060     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19061
19062   SDLoc OpDL(Op);
19063   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19064   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19065
19066   return NOOP;
19067 }
19068
19069 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19070                                                   SelectionDAG &DAG) const {
19071   // TODO: Eventually, the lowering of these nodes should be informed by or
19072   // deferred to the GC strategy for the function in which they appear. For
19073   // now, however, they must be lowered to something. Since they are logically
19074   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19075   // require special handling for these nodes), lower them as literal NOOPs for
19076   // the time being.
19077   SmallVector<SDValue, 2> Ops;
19078
19079   Ops.push_back(Op.getOperand(0));
19080   if (Op->getGluedNode())
19081     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19082
19083   SDLoc OpDL(Op);
19084   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19085   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19086
19087   return NOOP;
19088 }
19089
19090 /// LowerOperation - Provide custom lowering hooks for some operations.
19091 ///
19092 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19093   switch (Op.getOpcode()) {
19094   default: llvm_unreachable("Should not custom lower this!");
19095   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19096   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19097     return LowerCMP_SWAP(Op, Subtarget, DAG);
19098   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19099   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19100   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19101   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19102   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19103   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19104   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19105   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19106   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19107   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19108   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19109   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19110   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19111   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19112   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19113   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19114   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19115   case ISD::SHL_PARTS:
19116   case ISD::SRA_PARTS:
19117   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19118   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19119   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19120   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19121   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19122   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19123   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19124   case ISD::SIGN_EXTEND_VECTOR_INREG:
19125     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19126   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19127   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19128   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19129   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19130   case ISD::FABS:
19131   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19132   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19133   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19134   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19135   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19136   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19137   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19138   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19139   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19140   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19141   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19142   case ISD::INTRINSIC_VOID:
19143   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19144   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19145   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19146   case ISD::FRAME_TO_ARGS_OFFSET:
19147                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19148   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19149   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19150   case ISD::CLEANUPRET:         return LowerCLEANUPRET(Op, DAG);
19151   case ISD::CATCHRET:           return LowerCATCHRET(Op, DAG);
19152   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19153   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19154   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19155   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19156   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19157   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19158   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19159   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19160   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19161   case ISD::UMUL_LOHI:
19162   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19163   case ISD::SRA:
19164   case ISD::SRL:
19165   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19166   case ISD::SADDO:
19167   case ISD::UADDO:
19168   case ISD::SSUBO:
19169   case ISD::USUBO:
19170   case ISD::SMULO:
19171   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19172   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19173   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19174   case ISD::ADDC:
19175   case ISD::ADDE:
19176   case ISD::SUBC:
19177   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19178   case ISD::ADD:                return LowerADD(Op, DAG);
19179   case ISD::SUB:                return LowerSUB(Op, DAG);
19180   case ISD::SMAX:
19181   case ISD::SMIN:
19182   case ISD::UMAX:
19183   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19184   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19185   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19186   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19187   case ISD::GC_TRANSITION_START:
19188                                 return LowerGC_TRANSITION_START(Op, DAG);
19189   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19190   }
19191 }
19192
19193 /// ReplaceNodeResults - Replace a node with an illegal result type
19194 /// with a new node built out of custom code.
19195 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19196                                            SmallVectorImpl<SDValue>&Results,
19197                                            SelectionDAG &DAG) const {
19198   SDLoc dl(N);
19199   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19200   switch (N->getOpcode()) {
19201   default:
19202     llvm_unreachable("Do not know how to custom type legalize this operation!");
19203   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19204   case X86ISD::FMINC:
19205   case X86ISD::FMIN:
19206   case X86ISD::FMAXC:
19207   case X86ISD::FMAX: {
19208     EVT VT = N->getValueType(0);
19209     if (VT != MVT::v2f32)
19210       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19211     SDValue UNDEF = DAG.getUNDEF(VT);
19212     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19213                               N->getOperand(0), UNDEF);
19214     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19215                               N->getOperand(1), UNDEF);
19216     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19217     return;
19218   }
19219   case ISD::SIGN_EXTEND_INREG:
19220   case ISD::ADDC:
19221   case ISD::ADDE:
19222   case ISD::SUBC:
19223   case ISD::SUBE:
19224     // We don't want to expand or promote these.
19225     return;
19226   case ISD::SDIV:
19227   case ISD::UDIV:
19228   case ISD::SREM:
19229   case ISD::UREM:
19230   case ISD::SDIVREM:
19231   case ISD::UDIVREM: {
19232     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19233     Results.push_back(V);
19234     return;
19235   }
19236   case ISD::FP_TO_SINT:
19237   case ISD::FP_TO_UINT: {
19238     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19239
19240     std::pair<SDValue,SDValue> Vals =
19241         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19242     SDValue FIST = Vals.first, StackSlot = Vals.second;
19243     if (FIST.getNode()) {
19244       EVT VT = N->getValueType(0);
19245       // Return a load from the stack slot.
19246       if (StackSlot.getNode())
19247         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19248                                       MachinePointerInfo(),
19249                                       false, false, false, 0));
19250       else
19251         Results.push_back(FIST);
19252     }
19253     return;
19254   }
19255   case ISD::UINT_TO_FP: {
19256     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19257     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19258         N->getValueType(0) != MVT::v2f32)
19259       return;
19260     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19261                                  N->getOperand(0));
19262     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19263                                      MVT::f64);
19264     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19265     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19266                              DAG.getBitcast(MVT::v2i64, VBias));
19267     Or = DAG.getBitcast(MVT::v2f64, Or);
19268     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19269     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19270     return;
19271   }
19272   case ISD::FP_ROUND: {
19273     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19274         return;
19275     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19276     Results.push_back(V);
19277     return;
19278   }
19279   case ISD::FP_EXTEND: {
19280     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19281     // No other ValueType for FP_EXTEND should reach this point.
19282     assert(N->getValueType(0) == MVT::v2f32 &&
19283            "Do not know how to legalize this Node");
19284     return;
19285   }
19286   case ISD::INTRINSIC_W_CHAIN: {
19287     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19288     switch (IntNo) {
19289     default : llvm_unreachable("Do not know how to custom type "
19290                                "legalize this intrinsic operation!");
19291     case Intrinsic::x86_rdtsc:
19292       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19293                                      Results);
19294     case Intrinsic::x86_rdtscp:
19295       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19296                                      Results);
19297     case Intrinsic::x86_rdpmc:
19298       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19299     }
19300   }
19301   case ISD::READCYCLECOUNTER: {
19302     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19303                                    Results);
19304   }
19305   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19306     EVT T = N->getValueType(0);
19307     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19308     bool Regs64bit = T == MVT::i128;
19309     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19310     SDValue cpInL, cpInH;
19311     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19312                         DAG.getConstant(0, dl, HalfT));
19313     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19314                         DAG.getConstant(1, dl, HalfT));
19315     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19316                              Regs64bit ? X86::RAX : X86::EAX,
19317                              cpInL, SDValue());
19318     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19319                              Regs64bit ? X86::RDX : X86::EDX,
19320                              cpInH, cpInL.getValue(1));
19321     SDValue swapInL, swapInH;
19322     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19323                           DAG.getConstant(0, dl, HalfT));
19324     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19325                           DAG.getConstant(1, dl, HalfT));
19326     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19327                                Regs64bit ? X86::RBX : X86::EBX,
19328                                swapInL, cpInH.getValue(1));
19329     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19330                                Regs64bit ? X86::RCX : X86::ECX,
19331                                swapInH, swapInL.getValue(1));
19332     SDValue Ops[] = { swapInH.getValue(0),
19333                       N->getOperand(1),
19334                       swapInH.getValue(1) };
19335     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19336     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19337     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19338                                   X86ISD::LCMPXCHG8_DAG;
19339     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19340     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19341                                         Regs64bit ? X86::RAX : X86::EAX,
19342                                         HalfT, Result.getValue(1));
19343     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19344                                         Regs64bit ? X86::RDX : X86::EDX,
19345                                         HalfT, cpOutL.getValue(2));
19346     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19347
19348     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19349                                         MVT::i32, cpOutH.getValue(2));
19350     SDValue Success =
19351         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19352                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19353     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19354
19355     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19356     Results.push_back(Success);
19357     Results.push_back(EFLAGS.getValue(1));
19358     return;
19359   }
19360   case ISD::ATOMIC_SWAP:
19361   case ISD::ATOMIC_LOAD_ADD:
19362   case ISD::ATOMIC_LOAD_SUB:
19363   case ISD::ATOMIC_LOAD_AND:
19364   case ISD::ATOMIC_LOAD_OR:
19365   case ISD::ATOMIC_LOAD_XOR:
19366   case ISD::ATOMIC_LOAD_NAND:
19367   case ISD::ATOMIC_LOAD_MIN:
19368   case ISD::ATOMIC_LOAD_MAX:
19369   case ISD::ATOMIC_LOAD_UMIN:
19370   case ISD::ATOMIC_LOAD_UMAX:
19371   case ISD::ATOMIC_LOAD: {
19372     // Delegate to generic TypeLegalization. Situations we can really handle
19373     // should have already been dealt with by AtomicExpandPass.cpp.
19374     break;
19375   }
19376   case ISD::BITCAST: {
19377     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19378     EVT DstVT = N->getValueType(0);
19379     EVT SrcVT = N->getOperand(0)->getValueType(0);
19380
19381     if (SrcVT != MVT::f64 ||
19382         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19383       return;
19384
19385     unsigned NumElts = DstVT.getVectorNumElements();
19386     EVT SVT = DstVT.getVectorElementType();
19387     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19388     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19389                                    MVT::v2f64, N->getOperand(0));
19390     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19391
19392     if (ExperimentalVectorWideningLegalization) {
19393       // If we are legalizing vectors by widening, we already have the desired
19394       // legal vector type, just return it.
19395       Results.push_back(ToVecInt);
19396       return;
19397     }
19398
19399     SmallVector<SDValue, 8> Elts;
19400     for (unsigned i = 0, e = NumElts; i != e; ++i)
19401       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19402                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19403
19404     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19405   }
19406   }
19407 }
19408
19409 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19410   switch ((X86ISD::NodeType)Opcode) {
19411   case X86ISD::FIRST_NUMBER:       break;
19412   case X86ISD::BSF:                return "X86ISD::BSF";
19413   case X86ISD::BSR:                return "X86ISD::BSR";
19414   case X86ISD::SHLD:               return "X86ISD::SHLD";
19415   case X86ISD::SHRD:               return "X86ISD::SHRD";
19416   case X86ISD::FAND:               return "X86ISD::FAND";
19417   case X86ISD::FANDN:              return "X86ISD::FANDN";
19418   case X86ISD::FOR:                return "X86ISD::FOR";
19419   case X86ISD::FXOR:               return "X86ISD::FXOR";
19420   case X86ISD::FILD:               return "X86ISD::FILD";
19421   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19422   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19423   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19424   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19425   case X86ISD::FLD:                return "X86ISD::FLD";
19426   case X86ISD::FST:                return "X86ISD::FST";
19427   case X86ISD::CALL:               return "X86ISD::CALL";
19428   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19429   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19430   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19431   case X86ISD::BT:                 return "X86ISD::BT";
19432   case X86ISD::CMP:                return "X86ISD::CMP";
19433   case X86ISD::COMI:               return "X86ISD::COMI";
19434   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19435   case X86ISD::CMPM:               return "X86ISD::CMPM";
19436   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19437   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19438   case X86ISD::SETCC:              return "X86ISD::SETCC";
19439   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19440   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19441   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19442   case X86ISD::CMOV:               return "X86ISD::CMOV";
19443   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19444   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19445   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19446   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19447   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19448   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19449   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19450   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19451   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19452   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19453   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19454   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19455   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19456   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19457   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19458   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19459   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19460   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19461   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19462   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19463   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19464   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19465   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19466   case X86ISD::HADD:               return "X86ISD::HADD";
19467   case X86ISD::HSUB:               return "X86ISD::HSUB";
19468   case X86ISD::FHADD:              return "X86ISD::FHADD";
19469   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19470   case X86ISD::ABS:                return "X86ISD::ABS";
19471   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19472   case X86ISD::FMAX:               return "X86ISD::FMAX";
19473   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19474   case X86ISD::FMIN:               return "X86ISD::FMIN";
19475   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19476   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19477   case X86ISD::FMINC:              return "X86ISD::FMINC";
19478   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19479   case X86ISD::FRCP:               return "X86ISD::FRCP";
19480   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19481   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19482   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19483   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19484   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19485   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19486   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19487   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19488   case X86ISD::CATCHRET:           return "X86ISD::CATCHRET";
19489   case X86ISD::CLEANUPRET:         return "X86ISD::CLEANUPRET";
19490   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19491   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19492   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19493   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19494   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19495   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19496   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19497   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19498   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19499   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19500   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19501   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19502   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19503   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19504   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19505   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19506   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19507   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19508   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19509   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19510   case X86ISD::VSHL:               return "X86ISD::VSHL";
19511   case X86ISD::VSRL:               return "X86ISD::VSRL";
19512   case X86ISD::VSRA:               return "X86ISD::VSRA";
19513   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19514   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19515   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19516   case X86ISD::CMPP:               return "X86ISD::CMPP";
19517   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19518   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19519   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19520   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19521   case X86ISD::ADD:                return "X86ISD::ADD";
19522   case X86ISD::SUB:                return "X86ISD::SUB";
19523   case X86ISD::ADC:                return "X86ISD::ADC";
19524   case X86ISD::SBB:                return "X86ISD::SBB";
19525   case X86ISD::SMUL:               return "X86ISD::SMUL";
19526   case X86ISD::UMUL:               return "X86ISD::UMUL";
19527   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19528   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19529   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19530   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19531   case X86ISD::INC:                return "X86ISD::INC";
19532   case X86ISD::DEC:                return "X86ISD::DEC";
19533   case X86ISD::OR:                 return "X86ISD::OR";
19534   case X86ISD::XOR:                return "X86ISD::XOR";
19535   case X86ISD::AND:                return "X86ISD::AND";
19536   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19537   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19538   case X86ISD::PTEST:              return "X86ISD::PTEST";
19539   case X86ISD::TESTP:              return "X86ISD::TESTP";
19540   case X86ISD::TESTM:              return "X86ISD::TESTM";
19541   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19542   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19543   case X86ISD::KTEST:              return "X86ISD::KTEST";
19544   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19545   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19546   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19547   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19548   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19549   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19550   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19551   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19552   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19553   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19554   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19555   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19556   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19557   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19558   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19559   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19560   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19561   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19562   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19563   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19564   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19565   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19566   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19567   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19568   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19569   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19570   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19571   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19572   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19573   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19574   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19575   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19576   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19577   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19578   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19579   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19580   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19581   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19582   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19583   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19584   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19585   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19586   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19587   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19588   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19589   case X86ISD::SAHF:               return "X86ISD::SAHF";
19590   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19591   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19592   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19593   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19594   case X86ISD::FMADD:              return "X86ISD::FMADD";
19595   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19596   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19597   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19598   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19599   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19600   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19601   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19602   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19603   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19604   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19605   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19606   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19607   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19608   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19609   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19610   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19611   case X86ISD::XTEST:              return "X86ISD::XTEST";
19612   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19613   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19614   case X86ISD::SELECT:             return "X86ISD::SELECT";
19615   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19616   case X86ISD::RCP28:              return "X86ISD::RCP28";
19617   case X86ISD::EXP2:               return "X86ISD::EXP2";
19618   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19619   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19620   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19621   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19622   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19623   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19624   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19625   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19626   case X86ISD::ADDS:               return "X86ISD::ADDS";
19627   case X86ISD::SUBS:               return "X86ISD::SUBS";
19628   case X86ISD::AVG:                return "X86ISD::AVG";
19629   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19630   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19631   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19632   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19633   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19634   }
19635   return nullptr;
19636 }
19637
19638 // isLegalAddressingMode - Return true if the addressing mode represented
19639 // by AM is legal for this target, for a load/store of the specified type.
19640 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19641                                               const AddrMode &AM, Type *Ty,
19642                                               unsigned AS) const {
19643   // X86 supports extremely general addressing modes.
19644   CodeModel::Model M = getTargetMachine().getCodeModel();
19645   Reloc::Model R = getTargetMachine().getRelocationModel();
19646
19647   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19648   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19649     return false;
19650
19651   if (AM.BaseGV) {
19652     unsigned GVFlags =
19653       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19654
19655     // If a reference to this global requires an extra load, we can't fold it.
19656     if (isGlobalStubReference(GVFlags))
19657       return false;
19658
19659     // If BaseGV requires a register for the PIC base, we cannot also have a
19660     // BaseReg specified.
19661     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19662       return false;
19663
19664     // If lower 4G is not available, then we must use rip-relative addressing.
19665     if ((M != CodeModel::Small || R != Reloc::Static) &&
19666         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19667       return false;
19668   }
19669
19670   switch (AM.Scale) {
19671   case 0:
19672   case 1:
19673   case 2:
19674   case 4:
19675   case 8:
19676     // These scales always work.
19677     break;
19678   case 3:
19679   case 5:
19680   case 9:
19681     // These scales are formed with basereg+scalereg.  Only accept if there is
19682     // no basereg yet.
19683     if (AM.HasBaseReg)
19684       return false;
19685     break;
19686   default:  // Other stuff never works.
19687     return false;
19688   }
19689
19690   return true;
19691 }
19692
19693 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19694   unsigned Bits = Ty->getScalarSizeInBits();
19695
19696   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19697   // particularly cheaper than those without.
19698   if (Bits == 8)
19699     return false;
19700
19701   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19702   // variable shifts just as cheap as scalar ones.
19703   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19704     return false;
19705
19706   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19707   // fully general vector.
19708   return true;
19709 }
19710
19711 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19712   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19713     return false;
19714   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19715   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19716   return NumBits1 > NumBits2;
19717 }
19718
19719 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19720   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19721     return false;
19722
19723   if (!isTypeLegal(EVT::getEVT(Ty1)))
19724     return false;
19725
19726   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19727
19728   // Assuming the caller doesn't have a zeroext or signext return parameter,
19729   // truncation all the way down to i1 is valid.
19730   return true;
19731 }
19732
19733 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19734   return isInt<32>(Imm);
19735 }
19736
19737 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19738   // Can also use sub to handle negated immediates.
19739   return isInt<32>(Imm);
19740 }
19741
19742 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19743   if (!VT1.isInteger() || !VT2.isInteger())
19744     return false;
19745   unsigned NumBits1 = VT1.getSizeInBits();
19746   unsigned NumBits2 = VT2.getSizeInBits();
19747   return NumBits1 > NumBits2;
19748 }
19749
19750 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19751   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19752   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19753 }
19754
19755 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19756   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19757   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19758 }
19759
19760 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19761   EVT VT1 = Val.getValueType();
19762   if (isZExtFree(VT1, VT2))
19763     return true;
19764
19765   if (Val.getOpcode() != ISD::LOAD)
19766     return false;
19767
19768   if (!VT1.isSimple() || !VT1.isInteger() ||
19769       !VT2.isSimple() || !VT2.isInteger())
19770     return false;
19771
19772   switch (VT1.getSimpleVT().SimpleTy) {
19773   default: break;
19774   case MVT::i8:
19775   case MVT::i16:
19776   case MVT::i32:
19777     // X86 has 8, 16, and 32-bit zero-extending loads.
19778     return true;
19779   }
19780
19781   return false;
19782 }
19783
19784 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19785
19786 bool
19787 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19788   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19789     return false;
19790
19791   VT = VT.getScalarType();
19792
19793   if (!VT.isSimple())
19794     return false;
19795
19796   switch (VT.getSimpleVT().SimpleTy) {
19797   case MVT::f32:
19798   case MVT::f64:
19799     return true;
19800   default:
19801     break;
19802   }
19803
19804   return false;
19805 }
19806
19807 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19808   // i16 instructions are longer (0x66 prefix) and potentially slower.
19809   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19810 }
19811
19812 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19813 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19814 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19815 /// are assumed to be legal.
19816 bool
19817 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19818                                       EVT VT) const {
19819   if (!VT.isSimple())
19820     return false;
19821
19822   // Not for i1 vectors
19823   if (VT.getScalarType() == MVT::i1)
19824     return false;
19825
19826   // Very little shuffling can be done for 64-bit vectors right now.
19827   if (VT.getSizeInBits() == 64)
19828     return false;
19829
19830   // We only care that the types being shuffled are legal. The lowering can
19831   // handle any possible shuffle mask that results.
19832   return isTypeLegal(VT.getSimpleVT());
19833 }
19834
19835 bool
19836 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19837                                           EVT VT) const {
19838   // Just delegate to the generic legality, clear masks aren't special.
19839   return isShuffleMaskLegal(Mask, VT);
19840 }
19841
19842 //===----------------------------------------------------------------------===//
19843 //                           X86 Scheduler Hooks
19844 //===----------------------------------------------------------------------===//
19845
19846 /// Utility function to emit xbegin specifying the start of an RTM region.
19847 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19848                                      const TargetInstrInfo *TII) {
19849   DebugLoc DL = MI->getDebugLoc();
19850
19851   const BasicBlock *BB = MBB->getBasicBlock();
19852   MachineFunction::iterator I = MBB;
19853   ++I;
19854
19855   // For the v = xbegin(), we generate
19856   //
19857   // thisMBB:
19858   //  xbegin sinkMBB
19859   //
19860   // mainMBB:
19861   //  eax = -1
19862   //
19863   // sinkMBB:
19864   //  v = eax
19865
19866   MachineBasicBlock *thisMBB = MBB;
19867   MachineFunction *MF = MBB->getParent();
19868   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19869   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19870   MF->insert(I, mainMBB);
19871   MF->insert(I, sinkMBB);
19872
19873   // Transfer the remainder of BB and its successor edges to sinkMBB.
19874   sinkMBB->splice(sinkMBB->begin(), MBB,
19875                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19876   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19877
19878   // thisMBB:
19879   //  xbegin sinkMBB
19880   //  # fallthrough to mainMBB
19881   //  # abortion to sinkMBB
19882   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19883   thisMBB->addSuccessor(mainMBB);
19884   thisMBB->addSuccessor(sinkMBB);
19885
19886   // mainMBB:
19887   //  EAX = -1
19888   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19889   mainMBB->addSuccessor(sinkMBB);
19890
19891   // sinkMBB:
19892   // EAX is live into the sinkMBB
19893   sinkMBB->addLiveIn(X86::EAX);
19894   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19895           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19896     .addReg(X86::EAX);
19897
19898   MI->eraseFromParent();
19899   return sinkMBB;
19900 }
19901
19902 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19903 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19904 // in the .td file.
19905 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19906                                        const TargetInstrInfo *TII) {
19907   unsigned Opc;
19908   switch (MI->getOpcode()) {
19909   default: llvm_unreachable("illegal opcode!");
19910   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19911   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19912   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19913   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19914   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19915   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19916   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19917   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19918   }
19919
19920   DebugLoc dl = MI->getDebugLoc();
19921   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19922
19923   unsigned NumArgs = MI->getNumOperands();
19924   for (unsigned i = 1; i < NumArgs; ++i) {
19925     MachineOperand &Op = MI->getOperand(i);
19926     if (!(Op.isReg() && Op.isImplicit()))
19927       MIB.addOperand(Op);
19928   }
19929   if (MI->hasOneMemOperand())
19930     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19931
19932   BuildMI(*BB, MI, dl,
19933     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19934     .addReg(X86::XMM0);
19935
19936   MI->eraseFromParent();
19937   return BB;
19938 }
19939
19940 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19941 // defs in an instruction pattern
19942 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19943                                        const TargetInstrInfo *TII) {
19944   unsigned Opc;
19945   switch (MI->getOpcode()) {
19946   default: llvm_unreachable("illegal opcode!");
19947   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19948   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19949   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19950   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19951   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19952   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19953   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19954   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19955   }
19956
19957   DebugLoc dl = MI->getDebugLoc();
19958   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19959
19960   unsigned NumArgs = MI->getNumOperands(); // remove the results
19961   for (unsigned i = 1; i < NumArgs; ++i) {
19962     MachineOperand &Op = MI->getOperand(i);
19963     if (!(Op.isReg() && Op.isImplicit()))
19964       MIB.addOperand(Op);
19965   }
19966   if (MI->hasOneMemOperand())
19967     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19968
19969   BuildMI(*BB, MI, dl,
19970     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19971     .addReg(X86::ECX);
19972
19973   MI->eraseFromParent();
19974   return BB;
19975 }
19976
19977 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19978                                       const X86Subtarget *Subtarget) {
19979   DebugLoc dl = MI->getDebugLoc();
19980   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19981   // Address into RAX/EAX, other two args into ECX, EDX.
19982   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19983   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19984   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19985   for (int i = 0; i < X86::AddrNumOperands; ++i)
19986     MIB.addOperand(MI->getOperand(i));
19987
19988   unsigned ValOps = X86::AddrNumOperands;
19989   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19990     .addReg(MI->getOperand(ValOps).getReg());
19991   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19992     .addReg(MI->getOperand(ValOps+1).getReg());
19993
19994   // The instruction doesn't actually take any operands though.
19995   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19996
19997   MI->eraseFromParent(); // The pseudo is gone now.
19998   return BB;
19999 }
20000
20001 MachineBasicBlock *
20002 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20003                                                  MachineBasicBlock *MBB) const {
20004   // Emit va_arg instruction on X86-64.
20005
20006   // Operands to this pseudo-instruction:
20007   // 0  ) Output        : destination address (reg)
20008   // 1-5) Input         : va_list address (addr, i64mem)
20009   // 6  ) ArgSize       : Size (in bytes) of vararg type
20010   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20011   // 8  ) Align         : Alignment of type
20012   // 9  ) EFLAGS (implicit-def)
20013
20014   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20015   static_assert(X86::AddrNumOperands == 5,
20016                 "VAARG_64 assumes 5 address operands");
20017
20018   unsigned DestReg = MI->getOperand(0).getReg();
20019   MachineOperand &Base = MI->getOperand(1);
20020   MachineOperand &Scale = MI->getOperand(2);
20021   MachineOperand &Index = MI->getOperand(3);
20022   MachineOperand &Disp = MI->getOperand(4);
20023   MachineOperand &Segment = MI->getOperand(5);
20024   unsigned ArgSize = MI->getOperand(6).getImm();
20025   unsigned ArgMode = MI->getOperand(7).getImm();
20026   unsigned Align = MI->getOperand(8).getImm();
20027
20028   // Memory Reference
20029   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20030   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20031   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20032
20033   // Machine Information
20034   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20035   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20036   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20037   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20038   DebugLoc DL = MI->getDebugLoc();
20039
20040   // struct va_list {
20041   //   i32   gp_offset
20042   //   i32   fp_offset
20043   //   i64   overflow_area (address)
20044   //   i64   reg_save_area (address)
20045   // }
20046   // sizeof(va_list) = 24
20047   // alignment(va_list) = 8
20048
20049   unsigned TotalNumIntRegs = 6;
20050   unsigned TotalNumXMMRegs = 8;
20051   bool UseGPOffset = (ArgMode == 1);
20052   bool UseFPOffset = (ArgMode == 2);
20053   unsigned MaxOffset = TotalNumIntRegs * 8 +
20054                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20055
20056   /* Align ArgSize to a multiple of 8 */
20057   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20058   bool NeedsAlign = (Align > 8);
20059
20060   MachineBasicBlock *thisMBB = MBB;
20061   MachineBasicBlock *overflowMBB;
20062   MachineBasicBlock *offsetMBB;
20063   MachineBasicBlock *endMBB;
20064
20065   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20066   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20067   unsigned OffsetReg = 0;
20068
20069   if (!UseGPOffset && !UseFPOffset) {
20070     // If we only pull from the overflow region, we don't create a branch.
20071     // We don't need to alter control flow.
20072     OffsetDestReg = 0; // unused
20073     OverflowDestReg = DestReg;
20074
20075     offsetMBB = nullptr;
20076     overflowMBB = thisMBB;
20077     endMBB = thisMBB;
20078   } else {
20079     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20080     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20081     // If not, pull from overflow_area. (branch to overflowMBB)
20082     //
20083     //       thisMBB
20084     //         |     .
20085     //         |        .
20086     //     offsetMBB   overflowMBB
20087     //         |        .
20088     //         |     .
20089     //        endMBB
20090
20091     // Registers for the PHI in endMBB
20092     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20093     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20094
20095     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20096     MachineFunction *MF = MBB->getParent();
20097     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20098     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20099     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20100
20101     MachineFunction::iterator MBBIter = MBB;
20102     ++MBBIter;
20103
20104     // Insert the new basic blocks
20105     MF->insert(MBBIter, offsetMBB);
20106     MF->insert(MBBIter, overflowMBB);
20107     MF->insert(MBBIter, endMBB);
20108
20109     // Transfer the remainder of MBB and its successor edges to endMBB.
20110     endMBB->splice(endMBB->begin(), thisMBB,
20111                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20112     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20113
20114     // Make offsetMBB and overflowMBB successors of thisMBB
20115     thisMBB->addSuccessor(offsetMBB);
20116     thisMBB->addSuccessor(overflowMBB);
20117
20118     // endMBB is a successor of both offsetMBB and overflowMBB
20119     offsetMBB->addSuccessor(endMBB);
20120     overflowMBB->addSuccessor(endMBB);
20121
20122     // Load the offset value into a register
20123     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20124     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20125       .addOperand(Base)
20126       .addOperand(Scale)
20127       .addOperand(Index)
20128       .addDisp(Disp, UseFPOffset ? 4 : 0)
20129       .addOperand(Segment)
20130       .setMemRefs(MMOBegin, MMOEnd);
20131
20132     // Check if there is enough room left to pull this argument.
20133     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20134       .addReg(OffsetReg)
20135       .addImm(MaxOffset + 8 - ArgSizeA8);
20136
20137     // Branch to "overflowMBB" if offset >= max
20138     // Fall through to "offsetMBB" otherwise
20139     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20140       .addMBB(overflowMBB);
20141   }
20142
20143   // In offsetMBB, emit code to use the reg_save_area.
20144   if (offsetMBB) {
20145     assert(OffsetReg != 0);
20146
20147     // Read the reg_save_area address.
20148     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20149     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20150       .addOperand(Base)
20151       .addOperand(Scale)
20152       .addOperand(Index)
20153       .addDisp(Disp, 16)
20154       .addOperand(Segment)
20155       .setMemRefs(MMOBegin, MMOEnd);
20156
20157     // Zero-extend the offset
20158     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20159       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20160         .addImm(0)
20161         .addReg(OffsetReg)
20162         .addImm(X86::sub_32bit);
20163
20164     // Add the offset to the reg_save_area to get the final address.
20165     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20166       .addReg(OffsetReg64)
20167       .addReg(RegSaveReg);
20168
20169     // Compute the offset for the next argument
20170     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20171     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20172       .addReg(OffsetReg)
20173       .addImm(UseFPOffset ? 16 : 8);
20174
20175     // Store it back into the va_list.
20176     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20177       .addOperand(Base)
20178       .addOperand(Scale)
20179       .addOperand(Index)
20180       .addDisp(Disp, UseFPOffset ? 4 : 0)
20181       .addOperand(Segment)
20182       .addReg(NextOffsetReg)
20183       .setMemRefs(MMOBegin, MMOEnd);
20184
20185     // Jump to endMBB
20186     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20187       .addMBB(endMBB);
20188   }
20189
20190   //
20191   // Emit code to use overflow area
20192   //
20193
20194   // Load the overflow_area address into a register.
20195   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20196   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20197     .addOperand(Base)
20198     .addOperand(Scale)
20199     .addOperand(Index)
20200     .addDisp(Disp, 8)
20201     .addOperand(Segment)
20202     .setMemRefs(MMOBegin, MMOEnd);
20203
20204   // If we need to align it, do so. Otherwise, just copy the address
20205   // to OverflowDestReg.
20206   if (NeedsAlign) {
20207     // Align the overflow address
20208     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20209     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20210
20211     // aligned_addr = (addr + (align-1)) & ~(align-1)
20212     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20213       .addReg(OverflowAddrReg)
20214       .addImm(Align-1);
20215
20216     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20217       .addReg(TmpReg)
20218       .addImm(~(uint64_t)(Align-1));
20219   } else {
20220     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20221       .addReg(OverflowAddrReg);
20222   }
20223
20224   // Compute the next overflow address after this argument.
20225   // (the overflow address should be kept 8-byte aligned)
20226   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20227   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20228     .addReg(OverflowDestReg)
20229     .addImm(ArgSizeA8);
20230
20231   // Store the new overflow address.
20232   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20233     .addOperand(Base)
20234     .addOperand(Scale)
20235     .addOperand(Index)
20236     .addDisp(Disp, 8)
20237     .addOperand(Segment)
20238     .addReg(NextAddrReg)
20239     .setMemRefs(MMOBegin, MMOEnd);
20240
20241   // If we branched, emit the PHI to the front of endMBB.
20242   if (offsetMBB) {
20243     BuildMI(*endMBB, endMBB->begin(), DL,
20244             TII->get(X86::PHI), DestReg)
20245       .addReg(OffsetDestReg).addMBB(offsetMBB)
20246       .addReg(OverflowDestReg).addMBB(overflowMBB);
20247   }
20248
20249   // Erase the pseudo instruction
20250   MI->eraseFromParent();
20251
20252   return endMBB;
20253 }
20254
20255 MachineBasicBlock *
20256 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20257                                                  MachineInstr *MI,
20258                                                  MachineBasicBlock *MBB) const {
20259   // Emit code to save XMM registers to the stack. The ABI says that the
20260   // number of registers to save is given in %al, so it's theoretically
20261   // possible to do an indirect jump trick to avoid saving all of them,
20262   // however this code takes a simpler approach and just executes all
20263   // of the stores if %al is non-zero. It's less code, and it's probably
20264   // easier on the hardware branch predictor, and stores aren't all that
20265   // expensive anyway.
20266
20267   // Create the new basic blocks. One block contains all the XMM stores,
20268   // and one block is the final destination regardless of whether any
20269   // stores were performed.
20270   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20271   MachineFunction *F = MBB->getParent();
20272   MachineFunction::iterator MBBIter = MBB;
20273   ++MBBIter;
20274   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20275   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20276   F->insert(MBBIter, XMMSaveMBB);
20277   F->insert(MBBIter, EndMBB);
20278
20279   // Transfer the remainder of MBB and its successor edges to EndMBB.
20280   EndMBB->splice(EndMBB->begin(), MBB,
20281                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20282   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20283
20284   // The original block will now fall through to the XMM save block.
20285   MBB->addSuccessor(XMMSaveMBB);
20286   // The XMMSaveMBB will fall through to the end block.
20287   XMMSaveMBB->addSuccessor(EndMBB);
20288
20289   // Now add the instructions.
20290   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20291   DebugLoc DL = MI->getDebugLoc();
20292
20293   unsigned CountReg = MI->getOperand(0).getReg();
20294   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20295   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20296
20297   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20298     // If %al is 0, branch around the XMM save block.
20299     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20300     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20301     MBB->addSuccessor(EndMBB);
20302   }
20303
20304   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20305   // that was just emitted, but clearly shouldn't be "saved".
20306   assert((MI->getNumOperands() <= 3 ||
20307           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20308           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20309          && "Expected last argument to be EFLAGS");
20310   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20311   // In the XMM save block, save all the XMM argument registers.
20312   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20313     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20314     MachineMemOperand *MMO = F->getMachineMemOperand(
20315         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20316         MachineMemOperand::MOStore,
20317         /*Size=*/16, /*Align=*/16);
20318     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20319       .addFrameIndex(RegSaveFrameIndex)
20320       .addImm(/*Scale=*/1)
20321       .addReg(/*IndexReg=*/0)
20322       .addImm(/*Disp=*/Offset)
20323       .addReg(/*Segment=*/0)
20324       .addReg(MI->getOperand(i).getReg())
20325       .addMemOperand(MMO);
20326   }
20327
20328   MI->eraseFromParent();   // The pseudo instruction is gone now.
20329
20330   return EndMBB;
20331 }
20332
20333 // The EFLAGS operand of SelectItr might be missing a kill marker
20334 // because there were multiple uses of EFLAGS, and ISel didn't know
20335 // which to mark. Figure out whether SelectItr should have had a
20336 // kill marker, and set it if it should. Returns the correct kill
20337 // marker value.
20338 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20339                                      MachineBasicBlock* BB,
20340                                      const TargetRegisterInfo* TRI) {
20341   // Scan forward through BB for a use/def of EFLAGS.
20342   MachineBasicBlock::iterator miI(std::next(SelectItr));
20343   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20344     const MachineInstr& mi = *miI;
20345     if (mi.readsRegister(X86::EFLAGS))
20346       return false;
20347     if (mi.definesRegister(X86::EFLAGS))
20348       break; // Should have kill-flag - update below.
20349   }
20350
20351   // If we hit the end of the block, check whether EFLAGS is live into a
20352   // successor.
20353   if (miI == BB->end()) {
20354     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20355                                           sEnd = BB->succ_end();
20356          sItr != sEnd; ++sItr) {
20357       MachineBasicBlock* succ = *sItr;
20358       if (succ->isLiveIn(X86::EFLAGS))
20359         return false;
20360     }
20361   }
20362
20363   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20364   // out. SelectMI should have a kill flag on EFLAGS.
20365   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20366   return true;
20367 }
20368
20369 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20370 // together with other CMOV pseudo-opcodes into a single basic-block with
20371 // conditional jump around it.
20372 static bool isCMOVPseudo(MachineInstr *MI) {
20373   switch (MI->getOpcode()) {
20374   case X86::CMOV_FR32:
20375   case X86::CMOV_FR64:
20376   case X86::CMOV_GR8:
20377   case X86::CMOV_GR16:
20378   case X86::CMOV_GR32:
20379   case X86::CMOV_RFP32:
20380   case X86::CMOV_RFP64:
20381   case X86::CMOV_RFP80:
20382   case X86::CMOV_V2F64:
20383   case X86::CMOV_V2I64:
20384   case X86::CMOV_V4F32:
20385   case X86::CMOV_V4F64:
20386   case X86::CMOV_V4I64:
20387   case X86::CMOV_V16F32:
20388   case X86::CMOV_V8F32:
20389   case X86::CMOV_V8F64:
20390   case X86::CMOV_V8I64:
20391   case X86::CMOV_V8I1:
20392   case X86::CMOV_V16I1:
20393   case X86::CMOV_V32I1:
20394   case X86::CMOV_V64I1:
20395     return true;
20396
20397   default:
20398     return false;
20399   }
20400 }
20401
20402 MachineBasicBlock *
20403 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20404                                      MachineBasicBlock *BB) const {
20405   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20406   DebugLoc DL = MI->getDebugLoc();
20407
20408   // To "insert" a SELECT_CC instruction, we actually have to insert the
20409   // diamond control-flow pattern.  The incoming instruction knows the
20410   // destination vreg to set, the condition code register to branch on, the
20411   // true/false values to select between, and a branch opcode to use.
20412   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20413   MachineFunction::iterator It = BB;
20414   ++It;
20415
20416   //  thisMBB:
20417   //  ...
20418   //   TrueVal = ...
20419   //   cmpTY ccX, r1, r2
20420   //   bCC copy1MBB
20421   //   fallthrough --> copy0MBB
20422   MachineBasicBlock *thisMBB = BB;
20423   MachineFunction *F = BB->getParent();
20424
20425   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20426   // as described above, by inserting a BB, and then making a PHI at the join
20427   // point to select the true and false operands of the CMOV in the PHI.
20428   //
20429   // The code also handles two different cases of multiple CMOV opcodes
20430   // in a row.
20431   //
20432   // Case 1:
20433   // In this case, there are multiple CMOVs in a row, all which are based on
20434   // the same condition setting (or the exact opposite condition setting).
20435   // In this case we can lower all the CMOVs using a single inserted BB, and
20436   // then make a number of PHIs at the join point to model the CMOVs. The only
20437   // trickiness here, is that in a case like:
20438   //
20439   // t2 = CMOV cond1 t1, f1
20440   // t3 = CMOV cond1 t2, f2
20441   //
20442   // when rewriting this into PHIs, we have to perform some renaming on the
20443   // temps since you cannot have a PHI operand refer to a PHI result earlier
20444   // in the same block.  The "simple" but wrong lowering would be:
20445   //
20446   // t2 = PHI t1(BB1), f1(BB2)
20447   // t3 = PHI t2(BB1), f2(BB2)
20448   //
20449   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20450   // renaming is to note that on the path through BB1, t2 is really just a
20451   // copy of t1, and do that renaming, properly generating:
20452   //
20453   // t2 = PHI t1(BB1), f1(BB2)
20454   // t3 = PHI t1(BB1), f2(BB2)
20455   //
20456   // Case 2, we lower cascaded CMOVs such as
20457   //
20458   //   (CMOV (CMOV F, T, cc1), T, cc2)
20459   //
20460   // to two successives branches.  For that, we look for another CMOV as the
20461   // following instruction.
20462   //
20463   // Without this, we would add a PHI between the two jumps, which ends up
20464   // creating a few copies all around. For instance, for
20465   //
20466   //    (sitofp (zext (fcmp une)))
20467   //
20468   // we would generate:
20469   //
20470   //         ucomiss %xmm1, %xmm0
20471   //         movss  <1.0f>, %xmm0
20472   //         movaps  %xmm0, %xmm1
20473   //         jne     .LBB5_2
20474   //         xorps   %xmm1, %xmm1
20475   // .LBB5_2:
20476   //         jp      .LBB5_4
20477   //         movaps  %xmm1, %xmm0
20478   // .LBB5_4:
20479   //         retq
20480   //
20481   // because this custom-inserter would have generated:
20482   //
20483   //   A
20484   //   | \
20485   //   |  B
20486   //   | /
20487   //   C
20488   //   | \
20489   //   |  D
20490   //   | /
20491   //   E
20492   //
20493   // A: X = ...; Y = ...
20494   // B: empty
20495   // C: Z = PHI [X, A], [Y, B]
20496   // D: empty
20497   // E: PHI [X, C], [Z, D]
20498   //
20499   // If we lower both CMOVs in a single step, we can instead generate:
20500   //
20501   //   A
20502   //   | \
20503   //   |  C
20504   //   | /|
20505   //   |/ |
20506   //   |  |
20507   //   |  D
20508   //   | /
20509   //   E
20510   //
20511   // A: X = ...; Y = ...
20512   // D: empty
20513   // E: PHI [X, A], [X, C], [Y, D]
20514   //
20515   // Which, in our sitofp/fcmp example, gives us something like:
20516   //
20517   //         ucomiss %xmm1, %xmm0
20518   //         movss  <1.0f>, %xmm0
20519   //         jne     .LBB5_4
20520   //         jp      .LBB5_4
20521   //         xorps   %xmm0, %xmm0
20522   // .LBB5_4:
20523   //         retq
20524   //
20525   MachineInstr *CascadedCMOV = nullptr;
20526   MachineInstr *LastCMOV = MI;
20527   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20528   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20529   MachineBasicBlock::iterator NextMIIt =
20530       std::next(MachineBasicBlock::iterator(MI));
20531
20532   // Check for case 1, where there are multiple CMOVs with the same condition
20533   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20534   // number of jumps the most.
20535
20536   if (isCMOVPseudo(MI)) {
20537     // See if we have a string of CMOVS with the same condition.
20538     while (NextMIIt != BB->end() &&
20539            isCMOVPseudo(NextMIIt) &&
20540            (NextMIIt->getOperand(3).getImm() == CC ||
20541             NextMIIt->getOperand(3).getImm() == OppCC)) {
20542       LastCMOV = &*NextMIIt;
20543       ++NextMIIt;
20544     }
20545   }
20546
20547   // This checks for case 2, but only do this if we didn't already find
20548   // case 1, as indicated by LastCMOV == MI.
20549   if (LastCMOV == MI &&
20550       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20551       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20552       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20553     CascadedCMOV = &*NextMIIt;
20554   }
20555
20556   MachineBasicBlock *jcc1MBB = nullptr;
20557
20558   // If we have a cascaded CMOV, we lower it to two successive branches to
20559   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20560   if (CascadedCMOV) {
20561     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20562     F->insert(It, jcc1MBB);
20563     jcc1MBB->addLiveIn(X86::EFLAGS);
20564   }
20565
20566   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20567   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20568   F->insert(It, copy0MBB);
20569   F->insert(It, sinkMBB);
20570
20571   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20572   // live into the sink and copy blocks.
20573   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20574
20575   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20576   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20577       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20578     copy0MBB->addLiveIn(X86::EFLAGS);
20579     sinkMBB->addLiveIn(X86::EFLAGS);
20580   }
20581
20582   // Transfer the remainder of BB and its successor edges to sinkMBB.
20583   sinkMBB->splice(sinkMBB->begin(), BB,
20584                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20585   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20586
20587   // Add the true and fallthrough blocks as its successors.
20588   if (CascadedCMOV) {
20589     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20590     BB->addSuccessor(jcc1MBB);
20591
20592     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20593     // jump to the sinkMBB.
20594     jcc1MBB->addSuccessor(copy0MBB);
20595     jcc1MBB->addSuccessor(sinkMBB);
20596   } else {
20597     BB->addSuccessor(copy0MBB);
20598   }
20599
20600   // The true block target of the first (or only) branch is always sinkMBB.
20601   BB->addSuccessor(sinkMBB);
20602
20603   // Create the conditional branch instruction.
20604   unsigned Opc = X86::GetCondBranchFromCond(CC);
20605   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20606
20607   if (CascadedCMOV) {
20608     unsigned Opc2 = X86::GetCondBranchFromCond(
20609         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20610     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20611   }
20612
20613   //  copy0MBB:
20614   //   %FalseValue = ...
20615   //   # fallthrough to sinkMBB
20616   copy0MBB->addSuccessor(sinkMBB);
20617
20618   //  sinkMBB:
20619   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20620   //  ...
20621   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20622   MachineBasicBlock::iterator MIItEnd =
20623     std::next(MachineBasicBlock::iterator(LastCMOV));
20624   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20625   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20626   MachineInstrBuilder MIB;
20627
20628   // As we are creating the PHIs, we have to be careful if there is more than
20629   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20630   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20631   // That also means that PHI construction must work forward from earlier to
20632   // later, and that the code must maintain a mapping from earlier PHI's
20633   // destination registers, and the registers that went into the PHI.
20634
20635   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20636     unsigned DestReg = MIIt->getOperand(0).getReg();
20637     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20638     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20639
20640     // If this CMOV we are generating is the opposite condition from
20641     // the jump we generated, then we have to swap the operands for the
20642     // PHI that is going to be generated.
20643     if (MIIt->getOperand(3).getImm() == OppCC)
20644         std::swap(Op1Reg, Op2Reg);
20645
20646     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20647       Op1Reg = RegRewriteTable[Op1Reg].first;
20648
20649     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20650       Op2Reg = RegRewriteTable[Op2Reg].second;
20651
20652     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20653                   TII->get(X86::PHI), DestReg)
20654           .addReg(Op1Reg).addMBB(copy0MBB)
20655           .addReg(Op2Reg).addMBB(thisMBB);
20656
20657     // Add this PHI to the rewrite table.
20658     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20659   }
20660
20661   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20662   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20663   if (CascadedCMOV) {
20664     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20665     // Copy the PHI result to the register defined by the second CMOV.
20666     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20667             DL, TII->get(TargetOpcode::COPY),
20668             CascadedCMOV->getOperand(0).getReg())
20669         .addReg(MI->getOperand(0).getReg());
20670     CascadedCMOV->eraseFromParent();
20671   }
20672
20673   // Now remove the CMOV(s).
20674   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20675     (MIIt++)->eraseFromParent();
20676
20677   return sinkMBB;
20678 }
20679
20680 MachineBasicBlock *
20681 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20682                                        MachineBasicBlock *BB) const {
20683   // Combine the following atomic floating-point modification pattern:
20684   //   a.store(reg OP a.load(acquire), release)
20685   // Transform them into:
20686   //   OPss (%gpr), %xmm
20687   //   movss %xmm, (%gpr)
20688   // Or sd equivalent for 64-bit operations.
20689   unsigned MOp, FOp;
20690   switch (MI->getOpcode()) {
20691   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20692   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20693   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20694   }
20695   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20696   DebugLoc DL = MI->getDebugLoc();
20697   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20698   unsigned MSrc = MI->getOperand(0).getReg();
20699   unsigned VSrc = MI->getOperand(5).getReg();
20700   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20701                                 .addReg(/*Base=*/MSrc)
20702                                 .addImm(/*Scale=*/1)
20703                                 .addReg(/*Index=*/0)
20704                                 .addImm(0)
20705                                 .addReg(0);
20706   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20707                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20708                           .addReg(VSrc)
20709                           .addReg(/*Base=*/MSrc)
20710                           .addImm(/*Scale=*/1)
20711                           .addReg(/*Index=*/0)
20712                           .addImm(/*Disp=*/0)
20713                           .addReg(/*Segment=*/0);
20714   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20715   MI->eraseFromParent(); // The pseudo instruction is gone now.
20716   return BB;
20717 }
20718
20719 MachineBasicBlock *
20720 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20721                                         MachineBasicBlock *BB) const {
20722   MachineFunction *MF = BB->getParent();
20723   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20724   DebugLoc DL = MI->getDebugLoc();
20725   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20726
20727   assert(MF->shouldSplitStack());
20728
20729   const bool Is64Bit = Subtarget->is64Bit();
20730   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20731
20732   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20733   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20734
20735   // BB:
20736   //  ... [Till the alloca]
20737   // If stacklet is not large enough, jump to mallocMBB
20738   //
20739   // bumpMBB:
20740   //  Allocate by subtracting from RSP
20741   //  Jump to continueMBB
20742   //
20743   // mallocMBB:
20744   //  Allocate by call to runtime
20745   //
20746   // continueMBB:
20747   //  ...
20748   //  [rest of original BB]
20749   //
20750
20751   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20752   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20753   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20754
20755   MachineRegisterInfo &MRI = MF->getRegInfo();
20756   const TargetRegisterClass *AddrRegClass =
20757       getRegClassFor(getPointerTy(MF->getDataLayout()));
20758
20759   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20760     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20761     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20762     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20763     sizeVReg = MI->getOperand(1).getReg(),
20764     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20765
20766   MachineFunction::iterator MBBIter = BB;
20767   ++MBBIter;
20768
20769   MF->insert(MBBIter, bumpMBB);
20770   MF->insert(MBBIter, mallocMBB);
20771   MF->insert(MBBIter, continueMBB);
20772
20773   continueMBB->splice(continueMBB->begin(), BB,
20774                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20775   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20776
20777   // Add code to the main basic block to check if the stack limit has been hit,
20778   // and if so, jump to mallocMBB otherwise to bumpMBB.
20779   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20780   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20781     .addReg(tmpSPVReg).addReg(sizeVReg);
20782   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20783     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20784     .addReg(SPLimitVReg);
20785   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20786
20787   // bumpMBB simply decreases the stack pointer, since we know the current
20788   // stacklet has enough space.
20789   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20790     .addReg(SPLimitVReg);
20791   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20792     .addReg(SPLimitVReg);
20793   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20794
20795   // Calls into a routine in libgcc to allocate more space from the heap.
20796   const uint32_t *RegMask =
20797       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20798   if (IsLP64) {
20799     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20800       .addReg(sizeVReg);
20801     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20802       .addExternalSymbol("__morestack_allocate_stack_space")
20803       .addRegMask(RegMask)
20804       .addReg(X86::RDI, RegState::Implicit)
20805       .addReg(X86::RAX, RegState::ImplicitDefine);
20806   } else if (Is64Bit) {
20807     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20808       .addReg(sizeVReg);
20809     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20810       .addExternalSymbol("__morestack_allocate_stack_space")
20811       .addRegMask(RegMask)
20812       .addReg(X86::EDI, RegState::Implicit)
20813       .addReg(X86::EAX, RegState::ImplicitDefine);
20814   } else {
20815     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20816       .addImm(12);
20817     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20818     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20819       .addExternalSymbol("__morestack_allocate_stack_space")
20820       .addRegMask(RegMask)
20821       .addReg(X86::EAX, RegState::ImplicitDefine);
20822   }
20823
20824   if (!Is64Bit)
20825     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20826       .addImm(16);
20827
20828   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20829     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20830   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20831
20832   // Set up the CFG correctly.
20833   BB->addSuccessor(bumpMBB);
20834   BB->addSuccessor(mallocMBB);
20835   mallocMBB->addSuccessor(continueMBB);
20836   bumpMBB->addSuccessor(continueMBB);
20837
20838   // Take care of the PHI nodes.
20839   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20840           MI->getOperand(0).getReg())
20841     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20842     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20843
20844   // Delete the original pseudo instruction.
20845   MI->eraseFromParent();
20846
20847   // And we're done.
20848   return continueMBB;
20849 }
20850
20851 MachineBasicBlock *
20852 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20853                                         MachineBasicBlock *BB) const {
20854   DebugLoc DL = MI->getDebugLoc();
20855
20856   assert(!Subtarget->isTargetMachO());
20857
20858   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20859                                                     DL);
20860
20861   MI->eraseFromParent();   // The pseudo instruction is gone now.
20862   return BB;
20863 }
20864
20865 MachineBasicBlock *
20866 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20867                                       MachineBasicBlock *BB) const {
20868   // This is pretty easy.  We're taking the value that we received from
20869   // our load from the relocation, sticking it in either RDI (x86-64)
20870   // or EAX and doing an indirect call.  The return value will then
20871   // be in the normal return register.
20872   MachineFunction *F = BB->getParent();
20873   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20874   DebugLoc DL = MI->getDebugLoc();
20875
20876   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20877   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20878
20879   // Get a register mask for the lowered call.
20880   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20881   // proper register mask.
20882   const uint32_t *RegMask =
20883       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20884   if (Subtarget->is64Bit()) {
20885     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20886                                       TII->get(X86::MOV64rm), X86::RDI)
20887     .addReg(X86::RIP)
20888     .addImm(0).addReg(0)
20889     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20890                       MI->getOperand(3).getTargetFlags())
20891     .addReg(0);
20892     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20893     addDirectMem(MIB, X86::RDI);
20894     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20895   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20896     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20897                                       TII->get(X86::MOV32rm), X86::EAX)
20898     .addReg(0)
20899     .addImm(0).addReg(0)
20900     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20901                       MI->getOperand(3).getTargetFlags())
20902     .addReg(0);
20903     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20904     addDirectMem(MIB, X86::EAX);
20905     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20906   } else {
20907     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20908                                       TII->get(X86::MOV32rm), X86::EAX)
20909     .addReg(TII->getGlobalBaseReg(F))
20910     .addImm(0).addReg(0)
20911     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20912                       MI->getOperand(3).getTargetFlags())
20913     .addReg(0);
20914     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20915     addDirectMem(MIB, X86::EAX);
20916     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20917   }
20918
20919   MI->eraseFromParent(); // The pseudo instruction is gone now.
20920   return BB;
20921 }
20922
20923 MachineBasicBlock *
20924 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20925                                     MachineBasicBlock *MBB) const {
20926   DebugLoc DL = MI->getDebugLoc();
20927   MachineFunction *MF = MBB->getParent();
20928   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20929   MachineRegisterInfo &MRI = MF->getRegInfo();
20930
20931   const BasicBlock *BB = MBB->getBasicBlock();
20932   MachineFunction::iterator I = MBB;
20933   ++I;
20934
20935   // Memory Reference
20936   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20937   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20938
20939   unsigned DstReg;
20940   unsigned MemOpndSlot = 0;
20941
20942   unsigned CurOp = 0;
20943
20944   DstReg = MI->getOperand(CurOp++).getReg();
20945   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20946   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20947   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20948   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20949
20950   MemOpndSlot = CurOp;
20951
20952   MVT PVT = getPointerTy(MF->getDataLayout());
20953   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20954          "Invalid Pointer Size!");
20955
20956   // For v = setjmp(buf), we generate
20957   //
20958   // thisMBB:
20959   //  buf[LabelOffset] = restoreMBB
20960   //  SjLjSetup restoreMBB
20961   //
20962   // mainMBB:
20963   //  v_main = 0
20964   //
20965   // sinkMBB:
20966   //  v = phi(main, restore)
20967   //
20968   // restoreMBB:
20969   //  if base pointer being used, load it from frame
20970   //  v_restore = 1
20971
20972   MachineBasicBlock *thisMBB = MBB;
20973   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20974   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20975   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20976   MF->insert(I, mainMBB);
20977   MF->insert(I, sinkMBB);
20978   MF->push_back(restoreMBB);
20979
20980   MachineInstrBuilder MIB;
20981
20982   // Transfer the remainder of BB and its successor edges to sinkMBB.
20983   sinkMBB->splice(sinkMBB->begin(), MBB,
20984                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20985   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20986
20987   // thisMBB:
20988   unsigned PtrStoreOpc = 0;
20989   unsigned LabelReg = 0;
20990   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20991   Reloc::Model RM = MF->getTarget().getRelocationModel();
20992   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20993                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20994
20995   // Prepare IP either in reg or imm.
20996   if (!UseImmLabel) {
20997     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20998     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20999     LabelReg = MRI.createVirtualRegister(PtrRC);
21000     if (Subtarget->is64Bit()) {
21001       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21002               .addReg(X86::RIP)
21003               .addImm(0)
21004               .addReg(0)
21005               .addMBB(restoreMBB)
21006               .addReg(0);
21007     } else {
21008       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21009       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21010               .addReg(XII->getGlobalBaseReg(MF))
21011               .addImm(0)
21012               .addReg(0)
21013               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21014               .addReg(0);
21015     }
21016   } else
21017     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21018   // Store IP
21019   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21020   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21021     if (i == X86::AddrDisp)
21022       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21023     else
21024       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21025   }
21026   if (!UseImmLabel)
21027     MIB.addReg(LabelReg);
21028   else
21029     MIB.addMBB(restoreMBB);
21030   MIB.setMemRefs(MMOBegin, MMOEnd);
21031   // Setup
21032   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21033           .addMBB(restoreMBB);
21034
21035   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21036   MIB.addRegMask(RegInfo->getNoPreservedMask());
21037   thisMBB->addSuccessor(mainMBB);
21038   thisMBB->addSuccessor(restoreMBB);
21039
21040   // mainMBB:
21041   //  EAX = 0
21042   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21043   mainMBB->addSuccessor(sinkMBB);
21044
21045   // sinkMBB:
21046   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21047           TII->get(X86::PHI), DstReg)
21048     .addReg(mainDstReg).addMBB(mainMBB)
21049     .addReg(restoreDstReg).addMBB(restoreMBB);
21050
21051   // restoreMBB:
21052   if (RegInfo->hasBasePointer(*MF)) {
21053     const bool Uses64BitFramePtr =
21054         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21055     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21056     X86FI->setRestoreBasePointer(MF);
21057     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21058     unsigned BasePtr = RegInfo->getBaseRegister();
21059     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21060     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21061                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21062       .setMIFlag(MachineInstr::FrameSetup);
21063   }
21064   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21065   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21066   restoreMBB->addSuccessor(sinkMBB);
21067
21068   MI->eraseFromParent();
21069   return sinkMBB;
21070 }
21071
21072 MachineBasicBlock *
21073 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21074                                      MachineBasicBlock *MBB) const {
21075   DebugLoc DL = MI->getDebugLoc();
21076   MachineFunction *MF = MBB->getParent();
21077   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21078   MachineRegisterInfo &MRI = MF->getRegInfo();
21079
21080   // Memory Reference
21081   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21082   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21083
21084   MVT PVT = getPointerTy(MF->getDataLayout());
21085   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21086          "Invalid Pointer Size!");
21087
21088   const TargetRegisterClass *RC =
21089     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21090   unsigned Tmp = MRI.createVirtualRegister(RC);
21091   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21092   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21093   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21094   unsigned SP = RegInfo->getStackRegister();
21095
21096   MachineInstrBuilder MIB;
21097
21098   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21099   const int64_t SPOffset = 2 * PVT.getStoreSize();
21100
21101   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21102   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21103
21104   // Reload FP
21105   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21106   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21107     MIB.addOperand(MI->getOperand(i));
21108   MIB.setMemRefs(MMOBegin, MMOEnd);
21109   // Reload IP
21110   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21111   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21112     if (i == X86::AddrDisp)
21113       MIB.addDisp(MI->getOperand(i), LabelOffset);
21114     else
21115       MIB.addOperand(MI->getOperand(i));
21116   }
21117   MIB.setMemRefs(MMOBegin, MMOEnd);
21118   // Reload SP
21119   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21120   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21121     if (i == X86::AddrDisp)
21122       MIB.addDisp(MI->getOperand(i), SPOffset);
21123     else
21124       MIB.addOperand(MI->getOperand(i));
21125   }
21126   MIB.setMemRefs(MMOBegin, MMOEnd);
21127   // Jump
21128   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21129
21130   MI->eraseFromParent();
21131   return MBB;
21132 }
21133
21134 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21135 // accumulator loops. Writing back to the accumulator allows the coalescer
21136 // to remove extra copies in the loop.
21137 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21138 MachineBasicBlock *
21139 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21140                                  MachineBasicBlock *MBB) const {
21141   MachineOperand &AddendOp = MI->getOperand(3);
21142
21143   // Bail out early if the addend isn't a register - we can't switch these.
21144   if (!AddendOp.isReg())
21145     return MBB;
21146
21147   MachineFunction &MF = *MBB->getParent();
21148   MachineRegisterInfo &MRI = MF.getRegInfo();
21149
21150   // Check whether the addend is defined by a PHI:
21151   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21152   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21153   if (!AddendDef.isPHI())
21154     return MBB;
21155
21156   // Look for the following pattern:
21157   // loop:
21158   //   %addend = phi [%entry, 0], [%loop, %result]
21159   //   ...
21160   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21161
21162   // Replace with:
21163   //   loop:
21164   //   %addend = phi [%entry, 0], [%loop, %result]
21165   //   ...
21166   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21167
21168   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21169     assert(AddendDef.getOperand(i).isReg());
21170     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21171     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21172     if (&PHISrcInst == MI) {
21173       // Found a matching instruction.
21174       unsigned NewFMAOpc = 0;
21175       switch (MI->getOpcode()) {
21176         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21177         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21178         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21179         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21180         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21181         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21182         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21183         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21184         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21185         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21186         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21187         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21188         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21189         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21190         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21191         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21192         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21193         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21194         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21195         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21196
21197         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21198         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21199         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21200         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21201         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21202         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21203         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21204         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21205         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21206         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21207         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21208         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21209         default: llvm_unreachable("Unrecognized FMA variant.");
21210       }
21211
21212       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21213       MachineInstrBuilder MIB =
21214         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21215         .addOperand(MI->getOperand(0))
21216         .addOperand(MI->getOperand(3))
21217         .addOperand(MI->getOperand(2))
21218         .addOperand(MI->getOperand(1));
21219       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21220       MI->eraseFromParent();
21221     }
21222   }
21223
21224   return MBB;
21225 }
21226
21227 MachineBasicBlock *
21228 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21229                                                MachineBasicBlock *BB) const {
21230   switch (MI->getOpcode()) {
21231   default: llvm_unreachable("Unexpected instr type to insert");
21232   case X86::TAILJMPd64:
21233   case X86::TAILJMPr64:
21234   case X86::TAILJMPm64:
21235   case X86::TAILJMPd64_REX:
21236   case X86::TAILJMPr64_REX:
21237   case X86::TAILJMPm64_REX:
21238     llvm_unreachable("TAILJMP64 would not be touched here.");
21239   case X86::TCRETURNdi64:
21240   case X86::TCRETURNri64:
21241   case X86::TCRETURNmi64:
21242     return BB;
21243   case X86::WIN_ALLOCA:
21244     return EmitLoweredWinAlloca(MI, BB);
21245   case X86::SEG_ALLOCA_32:
21246   case X86::SEG_ALLOCA_64:
21247     return EmitLoweredSegAlloca(MI, BB);
21248   case X86::TLSCall_32:
21249   case X86::TLSCall_64:
21250     return EmitLoweredTLSCall(MI, BB);
21251   case X86::CMOV_FR32:
21252   case X86::CMOV_FR64:
21253   case X86::CMOV_GR8:
21254   case X86::CMOV_GR16:
21255   case X86::CMOV_GR32:
21256   case X86::CMOV_RFP32:
21257   case X86::CMOV_RFP64:
21258   case X86::CMOV_RFP80:
21259   case X86::CMOV_V2F64:
21260   case X86::CMOV_V2I64:
21261   case X86::CMOV_V4F32:
21262   case X86::CMOV_V4F64:
21263   case X86::CMOV_V4I64:
21264   case X86::CMOV_V16F32:
21265   case X86::CMOV_V8F32:
21266   case X86::CMOV_V8F64:
21267   case X86::CMOV_V8I64:
21268   case X86::CMOV_V8I1:
21269   case X86::CMOV_V16I1:
21270   case X86::CMOV_V32I1:
21271   case X86::CMOV_V64I1:
21272     return EmitLoweredSelect(MI, BB);
21273
21274   case X86::RELEASE_FADD32mr:
21275   case X86::RELEASE_FADD64mr:
21276     return EmitLoweredAtomicFP(MI, BB);
21277
21278   case X86::FP32_TO_INT16_IN_MEM:
21279   case X86::FP32_TO_INT32_IN_MEM:
21280   case X86::FP32_TO_INT64_IN_MEM:
21281   case X86::FP64_TO_INT16_IN_MEM:
21282   case X86::FP64_TO_INT32_IN_MEM:
21283   case X86::FP64_TO_INT64_IN_MEM:
21284   case X86::FP80_TO_INT16_IN_MEM:
21285   case X86::FP80_TO_INT32_IN_MEM:
21286   case X86::FP80_TO_INT64_IN_MEM: {
21287     MachineFunction *F = BB->getParent();
21288     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21289     DebugLoc DL = MI->getDebugLoc();
21290
21291     // Change the floating point control register to use "round towards zero"
21292     // mode when truncating to an integer value.
21293     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21294     addFrameReference(BuildMI(*BB, MI, DL,
21295                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21296
21297     // Load the old value of the high byte of the control word...
21298     unsigned OldCW =
21299       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21300     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21301                       CWFrameIdx);
21302
21303     // Set the high part to be round to zero...
21304     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21305       .addImm(0xC7F);
21306
21307     // Reload the modified control word now...
21308     addFrameReference(BuildMI(*BB, MI, DL,
21309                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21310
21311     // Restore the memory image of control word to original value
21312     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21313       .addReg(OldCW);
21314
21315     // Get the X86 opcode to use.
21316     unsigned Opc;
21317     switch (MI->getOpcode()) {
21318     default: llvm_unreachable("illegal opcode!");
21319     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21320     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21321     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21322     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21323     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21324     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21325     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21326     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21327     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21328     }
21329
21330     X86AddressMode AM;
21331     MachineOperand &Op = MI->getOperand(0);
21332     if (Op.isReg()) {
21333       AM.BaseType = X86AddressMode::RegBase;
21334       AM.Base.Reg = Op.getReg();
21335     } else {
21336       AM.BaseType = X86AddressMode::FrameIndexBase;
21337       AM.Base.FrameIndex = Op.getIndex();
21338     }
21339     Op = MI->getOperand(1);
21340     if (Op.isImm())
21341       AM.Scale = Op.getImm();
21342     Op = MI->getOperand(2);
21343     if (Op.isImm())
21344       AM.IndexReg = Op.getImm();
21345     Op = MI->getOperand(3);
21346     if (Op.isGlobal()) {
21347       AM.GV = Op.getGlobal();
21348     } else {
21349       AM.Disp = Op.getImm();
21350     }
21351     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21352                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21353
21354     // Reload the original control word now.
21355     addFrameReference(BuildMI(*BB, MI, DL,
21356                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21357
21358     MI->eraseFromParent();   // The pseudo instruction is gone now.
21359     return BB;
21360   }
21361     // String/text processing lowering.
21362   case X86::PCMPISTRM128REG:
21363   case X86::VPCMPISTRM128REG:
21364   case X86::PCMPISTRM128MEM:
21365   case X86::VPCMPISTRM128MEM:
21366   case X86::PCMPESTRM128REG:
21367   case X86::VPCMPESTRM128REG:
21368   case X86::PCMPESTRM128MEM:
21369   case X86::VPCMPESTRM128MEM:
21370     assert(Subtarget->hasSSE42() &&
21371            "Target must have SSE4.2 or AVX features enabled");
21372     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21373
21374   // String/text processing lowering.
21375   case X86::PCMPISTRIREG:
21376   case X86::VPCMPISTRIREG:
21377   case X86::PCMPISTRIMEM:
21378   case X86::VPCMPISTRIMEM:
21379   case X86::PCMPESTRIREG:
21380   case X86::VPCMPESTRIREG:
21381   case X86::PCMPESTRIMEM:
21382   case X86::VPCMPESTRIMEM:
21383     assert(Subtarget->hasSSE42() &&
21384            "Target must have SSE4.2 or AVX features enabled");
21385     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21386
21387   // Thread synchronization.
21388   case X86::MONITOR:
21389     return EmitMonitor(MI, BB, Subtarget);
21390
21391   // xbegin
21392   case X86::XBEGIN:
21393     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21394
21395   case X86::VASTART_SAVE_XMM_REGS:
21396     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21397
21398   case X86::VAARG_64:
21399     return EmitVAARG64WithCustomInserter(MI, BB);
21400
21401   case X86::EH_SjLj_SetJmp32:
21402   case X86::EH_SjLj_SetJmp64:
21403     return emitEHSjLjSetJmp(MI, BB);
21404
21405   case X86::EH_SjLj_LongJmp32:
21406   case X86::EH_SjLj_LongJmp64:
21407     return emitEHSjLjLongJmp(MI, BB);
21408
21409   case TargetOpcode::STATEPOINT:
21410     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21411     // this point in the process.  We diverge later.
21412     return emitPatchPoint(MI, BB);
21413
21414   case TargetOpcode::STACKMAP:
21415   case TargetOpcode::PATCHPOINT:
21416     return emitPatchPoint(MI, BB);
21417
21418   case X86::VFMADDPDr213r:
21419   case X86::VFMADDPSr213r:
21420   case X86::VFMADDSDr213r:
21421   case X86::VFMADDSSr213r:
21422   case X86::VFMSUBPDr213r:
21423   case X86::VFMSUBPSr213r:
21424   case X86::VFMSUBSDr213r:
21425   case X86::VFMSUBSSr213r:
21426   case X86::VFNMADDPDr213r:
21427   case X86::VFNMADDPSr213r:
21428   case X86::VFNMADDSDr213r:
21429   case X86::VFNMADDSSr213r:
21430   case X86::VFNMSUBPDr213r:
21431   case X86::VFNMSUBPSr213r:
21432   case X86::VFNMSUBSDr213r:
21433   case X86::VFNMSUBSSr213r:
21434   case X86::VFMADDSUBPDr213r:
21435   case X86::VFMADDSUBPSr213r:
21436   case X86::VFMSUBADDPDr213r:
21437   case X86::VFMSUBADDPSr213r:
21438   case X86::VFMADDPDr213rY:
21439   case X86::VFMADDPSr213rY:
21440   case X86::VFMSUBPDr213rY:
21441   case X86::VFMSUBPSr213rY:
21442   case X86::VFNMADDPDr213rY:
21443   case X86::VFNMADDPSr213rY:
21444   case X86::VFNMSUBPDr213rY:
21445   case X86::VFNMSUBPSr213rY:
21446   case X86::VFMADDSUBPDr213rY:
21447   case X86::VFMADDSUBPSr213rY:
21448   case X86::VFMSUBADDPDr213rY:
21449   case X86::VFMSUBADDPSr213rY:
21450     return emitFMA3Instr(MI, BB);
21451   }
21452 }
21453
21454 //===----------------------------------------------------------------------===//
21455 //                           X86 Optimization Hooks
21456 //===----------------------------------------------------------------------===//
21457
21458 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21459                                                       APInt &KnownZero,
21460                                                       APInt &KnownOne,
21461                                                       const SelectionDAG &DAG,
21462                                                       unsigned Depth) const {
21463   unsigned BitWidth = KnownZero.getBitWidth();
21464   unsigned Opc = Op.getOpcode();
21465   assert((Opc >= ISD::BUILTIN_OP_END ||
21466           Opc == ISD::INTRINSIC_WO_CHAIN ||
21467           Opc == ISD::INTRINSIC_W_CHAIN ||
21468           Opc == ISD::INTRINSIC_VOID) &&
21469          "Should use MaskedValueIsZero if you don't know whether Op"
21470          " is a target node!");
21471
21472   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21473   switch (Opc) {
21474   default: break;
21475   case X86ISD::ADD:
21476   case X86ISD::SUB:
21477   case X86ISD::ADC:
21478   case X86ISD::SBB:
21479   case X86ISD::SMUL:
21480   case X86ISD::UMUL:
21481   case X86ISD::INC:
21482   case X86ISD::DEC:
21483   case X86ISD::OR:
21484   case X86ISD::XOR:
21485   case X86ISD::AND:
21486     // These nodes' second result is a boolean.
21487     if (Op.getResNo() == 0)
21488       break;
21489     // Fallthrough
21490   case X86ISD::SETCC:
21491     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21492     break;
21493   case ISD::INTRINSIC_WO_CHAIN: {
21494     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21495     unsigned NumLoBits = 0;
21496     switch (IntId) {
21497     default: break;
21498     case Intrinsic::x86_sse_movmsk_ps:
21499     case Intrinsic::x86_avx_movmsk_ps_256:
21500     case Intrinsic::x86_sse2_movmsk_pd:
21501     case Intrinsic::x86_avx_movmsk_pd_256:
21502     case Intrinsic::x86_mmx_pmovmskb:
21503     case Intrinsic::x86_sse2_pmovmskb_128:
21504     case Intrinsic::x86_avx2_pmovmskb: {
21505       // High bits of movmskp{s|d}, pmovmskb are known zero.
21506       switch (IntId) {
21507         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21508         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21509         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21510         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21511         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21512         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21513         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21514         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21515       }
21516       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21517       break;
21518     }
21519     }
21520     break;
21521   }
21522   }
21523 }
21524
21525 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21526   SDValue Op,
21527   const SelectionDAG &,
21528   unsigned Depth) const {
21529   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21530   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21531     return Op.getValueType().getScalarType().getSizeInBits();
21532
21533   // Fallback case.
21534   return 1;
21535 }
21536
21537 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21538 /// node is a GlobalAddress + offset.
21539 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21540                                        const GlobalValue* &GA,
21541                                        int64_t &Offset) const {
21542   if (N->getOpcode() == X86ISD::Wrapper) {
21543     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21544       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21545       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21546       return true;
21547     }
21548   }
21549   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21550 }
21551
21552 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21553 /// same as extracting the high 128-bit part of 256-bit vector and then
21554 /// inserting the result into the low part of a new 256-bit vector
21555 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21556   EVT VT = SVOp->getValueType(0);
21557   unsigned NumElems = VT.getVectorNumElements();
21558
21559   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21560   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21561     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21562         SVOp->getMaskElt(j) >= 0)
21563       return false;
21564
21565   return true;
21566 }
21567
21568 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21569 /// same as extracting the low 128-bit part of 256-bit vector and then
21570 /// inserting the result into the high part of a new 256-bit vector
21571 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21572   EVT VT = SVOp->getValueType(0);
21573   unsigned NumElems = VT.getVectorNumElements();
21574
21575   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21576   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21577     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21578         SVOp->getMaskElt(j) >= 0)
21579       return false;
21580
21581   return true;
21582 }
21583
21584 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21585 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21586                                         TargetLowering::DAGCombinerInfo &DCI,
21587                                         const X86Subtarget* Subtarget) {
21588   SDLoc dl(N);
21589   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21590   SDValue V1 = SVOp->getOperand(0);
21591   SDValue V2 = SVOp->getOperand(1);
21592   EVT VT = SVOp->getValueType(0);
21593   unsigned NumElems = VT.getVectorNumElements();
21594
21595   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21596       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21597     //
21598     //                   0,0,0,...
21599     //                      |
21600     //    V      UNDEF    BUILD_VECTOR    UNDEF
21601     //     \      /           \           /
21602     //  CONCAT_VECTOR         CONCAT_VECTOR
21603     //         \                  /
21604     //          \                /
21605     //          RESULT: V + zero extended
21606     //
21607     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21608         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21609         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21610       return SDValue();
21611
21612     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21613       return SDValue();
21614
21615     // To match the shuffle mask, the first half of the mask should
21616     // be exactly the first vector, and all the rest a splat with the
21617     // first element of the second one.
21618     for (unsigned i = 0; i != NumElems/2; ++i)
21619       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21620           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21621         return SDValue();
21622
21623     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21624     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21625       if (Ld->hasNUsesOfValue(1, 0)) {
21626         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21627         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21628         SDValue ResNode =
21629           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21630                                   Ld->getMemoryVT(),
21631                                   Ld->getPointerInfo(),
21632                                   Ld->getAlignment(),
21633                                   false/*isVolatile*/, true/*ReadMem*/,
21634                                   false/*WriteMem*/);
21635
21636         // Make sure the newly-created LOAD is in the same position as Ld in
21637         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21638         // and update uses of Ld's output chain to use the TokenFactor.
21639         if (Ld->hasAnyUseOfValue(1)) {
21640           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21641                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21642           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21643           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21644                                  SDValue(ResNode.getNode(), 1));
21645         }
21646
21647         return DAG.getBitcast(VT, ResNode);
21648       }
21649     }
21650
21651     // Emit a zeroed vector and insert the desired subvector on its
21652     // first half.
21653     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21654     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21655     return DCI.CombineTo(N, InsV);
21656   }
21657
21658   //===--------------------------------------------------------------------===//
21659   // Combine some shuffles into subvector extracts and inserts:
21660   //
21661
21662   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21663   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21664     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21665     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21666     return DCI.CombineTo(N, InsV);
21667   }
21668
21669   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21670   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21671     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21672     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21673     return DCI.CombineTo(N, InsV);
21674   }
21675
21676   return SDValue();
21677 }
21678
21679 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21680 /// possible.
21681 ///
21682 /// This is the leaf of the recursive combinine below. When we have found some
21683 /// chain of single-use x86 shuffle instructions and accumulated the combined
21684 /// shuffle mask represented by them, this will try to pattern match that mask
21685 /// into either a single instruction if there is a special purpose instruction
21686 /// for this operation, or into a PSHUFB instruction which is a fully general
21687 /// instruction but should only be used to replace chains over a certain depth.
21688 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21689                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21690                                    TargetLowering::DAGCombinerInfo &DCI,
21691                                    const X86Subtarget *Subtarget) {
21692   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21693
21694   // Find the operand that enters the chain. Note that multiple uses are OK
21695   // here, we're not going to remove the operand we find.
21696   SDValue Input = Op.getOperand(0);
21697   while (Input.getOpcode() == ISD::BITCAST)
21698     Input = Input.getOperand(0);
21699
21700   MVT VT = Input.getSimpleValueType();
21701   MVT RootVT = Root.getSimpleValueType();
21702   SDLoc DL(Root);
21703
21704   // Just remove no-op shuffle masks.
21705   if (Mask.size() == 1) {
21706     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21707                   /*AddTo*/ true);
21708     return true;
21709   }
21710
21711   // Use the float domain if the operand type is a floating point type.
21712   bool FloatDomain = VT.isFloatingPoint();
21713
21714   // For floating point shuffles, we don't have free copies in the shuffle
21715   // instructions or the ability to load as part of the instruction, so
21716   // canonicalize their shuffles to UNPCK or MOV variants.
21717   //
21718   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21719   // vectors because it can have a load folded into it that UNPCK cannot. This
21720   // doesn't preclude something switching to the shorter encoding post-RA.
21721   //
21722   // FIXME: Should teach these routines about AVX vector widths.
21723   if (FloatDomain && VT.getSizeInBits() == 128) {
21724     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21725       bool Lo = Mask.equals({0, 0});
21726       unsigned Shuffle;
21727       MVT ShuffleVT;
21728       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21729       // is no slower than UNPCKLPD but has the option to fold the input operand
21730       // into even an unaligned memory load.
21731       if (Lo && Subtarget->hasSSE3()) {
21732         Shuffle = X86ISD::MOVDDUP;
21733         ShuffleVT = MVT::v2f64;
21734       } else {
21735         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21736         // than the UNPCK variants.
21737         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21738         ShuffleVT = MVT::v4f32;
21739       }
21740       if (Depth == 1 && Root->getOpcode() == Shuffle)
21741         return false; // Nothing to do!
21742       Op = DAG.getBitcast(ShuffleVT, Input);
21743       DCI.AddToWorklist(Op.getNode());
21744       if (Shuffle == X86ISD::MOVDDUP)
21745         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21746       else
21747         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21748       DCI.AddToWorklist(Op.getNode());
21749       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21750                     /*AddTo*/ true);
21751       return true;
21752     }
21753     if (Subtarget->hasSSE3() &&
21754         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21755       bool Lo = Mask.equals({0, 0, 2, 2});
21756       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21757       MVT ShuffleVT = MVT::v4f32;
21758       if (Depth == 1 && Root->getOpcode() == Shuffle)
21759         return false; // Nothing to do!
21760       Op = DAG.getBitcast(ShuffleVT, Input);
21761       DCI.AddToWorklist(Op.getNode());
21762       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21763       DCI.AddToWorklist(Op.getNode());
21764       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21765                     /*AddTo*/ true);
21766       return true;
21767     }
21768     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21769       bool Lo = Mask.equals({0, 0, 1, 1});
21770       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21771       MVT ShuffleVT = MVT::v4f32;
21772       if (Depth == 1 && Root->getOpcode() == Shuffle)
21773         return false; // Nothing to do!
21774       Op = DAG.getBitcast(ShuffleVT, Input);
21775       DCI.AddToWorklist(Op.getNode());
21776       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21777       DCI.AddToWorklist(Op.getNode());
21778       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21779                     /*AddTo*/ true);
21780       return true;
21781     }
21782   }
21783
21784   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21785   // variants as none of these have single-instruction variants that are
21786   // superior to the UNPCK formulation.
21787   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21788       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21789        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21790        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21791        Mask.equals(
21792            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21793     bool Lo = Mask[0] == 0;
21794     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21795     if (Depth == 1 && Root->getOpcode() == Shuffle)
21796       return false; // Nothing to do!
21797     MVT ShuffleVT;
21798     switch (Mask.size()) {
21799     case 8:
21800       ShuffleVT = MVT::v8i16;
21801       break;
21802     case 16:
21803       ShuffleVT = MVT::v16i8;
21804       break;
21805     default:
21806       llvm_unreachable("Impossible mask size!");
21807     };
21808     Op = DAG.getBitcast(ShuffleVT, Input);
21809     DCI.AddToWorklist(Op.getNode());
21810     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21811     DCI.AddToWorklist(Op.getNode());
21812     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21813                   /*AddTo*/ true);
21814     return true;
21815   }
21816
21817   // Don't try to re-form single instruction chains under any circumstances now
21818   // that we've done encoding canonicalization for them.
21819   if (Depth < 2)
21820     return false;
21821
21822   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21823   // can replace them with a single PSHUFB instruction profitably. Intel's
21824   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21825   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21826   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21827     SmallVector<SDValue, 16> PSHUFBMask;
21828     int NumBytes = VT.getSizeInBits() / 8;
21829     int Ratio = NumBytes / Mask.size();
21830     for (int i = 0; i < NumBytes; ++i) {
21831       if (Mask[i / Ratio] == SM_SentinelUndef) {
21832         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21833         continue;
21834       }
21835       int M = Mask[i / Ratio] != SM_SentinelZero
21836                   ? Ratio * Mask[i / Ratio] + i % Ratio
21837                   : 255;
21838       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21839     }
21840     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21841     Op = DAG.getBitcast(ByteVT, Input);
21842     DCI.AddToWorklist(Op.getNode());
21843     SDValue PSHUFBMaskOp =
21844         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21845     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21846     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21847     DCI.AddToWorklist(Op.getNode());
21848     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21849                   /*AddTo*/ true);
21850     return true;
21851   }
21852
21853   // Failed to find any combines.
21854   return false;
21855 }
21856
21857 /// \brief Fully generic combining of x86 shuffle instructions.
21858 ///
21859 /// This should be the last combine run over the x86 shuffle instructions. Once
21860 /// they have been fully optimized, this will recursively consider all chains
21861 /// of single-use shuffle instructions, build a generic model of the cumulative
21862 /// shuffle operation, and check for simpler instructions which implement this
21863 /// operation. We use this primarily for two purposes:
21864 ///
21865 /// 1) Collapse generic shuffles to specialized single instructions when
21866 ///    equivalent. In most cases, this is just an encoding size win, but
21867 ///    sometimes we will collapse multiple generic shuffles into a single
21868 ///    special-purpose shuffle.
21869 /// 2) Look for sequences of shuffle instructions with 3 or more total
21870 ///    instructions, and replace them with the slightly more expensive SSSE3
21871 ///    PSHUFB instruction if available. We do this as the last combining step
21872 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21873 ///    a suitable short sequence of other instructions. The PHUFB will either
21874 ///    use a register or have to read from memory and so is slightly (but only
21875 ///    slightly) more expensive than the other shuffle instructions.
21876 ///
21877 /// Because this is inherently a quadratic operation (for each shuffle in
21878 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21879 /// This should never be an issue in practice as the shuffle lowering doesn't
21880 /// produce sequences of more than 8 instructions.
21881 ///
21882 /// FIXME: We will currently miss some cases where the redundant shuffling
21883 /// would simplify under the threshold for PSHUFB formation because of
21884 /// combine-ordering. To fix this, we should do the redundant instruction
21885 /// combining in this recursive walk.
21886 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21887                                           ArrayRef<int> RootMask,
21888                                           int Depth, bool HasPSHUFB,
21889                                           SelectionDAG &DAG,
21890                                           TargetLowering::DAGCombinerInfo &DCI,
21891                                           const X86Subtarget *Subtarget) {
21892   // Bound the depth of our recursive combine because this is ultimately
21893   // quadratic in nature.
21894   if (Depth > 8)
21895     return false;
21896
21897   // Directly rip through bitcasts to find the underlying operand.
21898   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21899     Op = Op.getOperand(0);
21900
21901   MVT VT = Op.getSimpleValueType();
21902   if (!VT.isVector())
21903     return false; // Bail if we hit a non-vector.
21904
21905   assert(Root.getSimpleValueType().isVector() &&
21906          "Shuffles operate on vector types!");
21907   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21908          "Can only combine shuffles of the same vector register size.");
21909
21910   if (!isTargetShuffle(Op.getOpcode()))
21911     return false;
21912   SmallVector<int, 16> OpMask;
21913   bool IsUnary;
21914   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21915   // We only can combine unary shuffles which we can decode the mask for.
21916   if (!HaveMask || !IsUnary)
21917     return false;
21918
21919   assert(VT.getVectorNumElements() == OpMask.size() &&
21920          "Different mask size from vector size!");
21921   assert(((RootMask.size() > OpMask.size() &&
21922            RootMask.size() % OpMask.size() == 0) ||
21923           (OpMask.size() > RootMask.size() &&
21924            OpMask.size() % RootMask.size() == 0) ||
21925           OpMask.size() == RootMask.size()) &&
21926          "The smaller number of elements must divide the larger.");
21927   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21928   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21929   assert(((RootRatio == 1 && OpRatio == 1) ||
21930           (RootRatio == 1) != (OpRatio == 1)) &&
21931          "Must not have a ratio for both incoming and op masks!");
21932
21933   SmallVector<int, 16> Mask;
21934   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21935
21936   // Merge this shuffle operation's mask into our accumulated mask. Note that
21937   // this shuffle's mask will be the first applied to the input, followed by the
21938   // root mask to get us all the way to the root value arrangement. The reason
21939   // for this order is that we are recursing up the operation chain.
21940   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21941     int RootIdx = i / RootRatio;
21942     if (RootMask[RootIdx] < 0) {
21943       // This is a zero or undef lane, we're done.
21944       Mask.push_back(RootMask[RootIdx]);
21945       continue;
21946     }
21947
21948     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21949     int OpIdx = RootMaskedIdx / OpRatio;
21950     if (OpMask[OpIdx] < 0) {
21951       // The incoming lanes are zero or undef, it doesn't matter which ones we
21952       // are using.
21953       Mask.push_back(OpMask[OpIdx]);
21954       continue;
21955     }
21956
21957     // Ok, we have non-zero lanes, map them through.
21958     Mask.push_back(OpMask[OpIdx] * OpRatio +
21959                    RootMaskedIdx % OpRatio);
21960   }
21961
21962   // See if we can recurse into the operand to combine more things.
21963   switch (Op.getOpcode()) {
21964     case X86ISD::PSHUFB:
21965       HasPSHUFB = true;
21966     case X86ISD::PSHUFD:
21967     case X86ISD::PSHUFHW:
21968     case X86ISD::PSHUFLW:
21969       if (Op.getOperand(0).hasOneUse() &&
21970           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21971                                         HasPSHUFB, DAG, DCI, Subtarget))
21972         return true;
21973       break;
21974
21975     case X86ISD::UNPCKL:
21976     case X86ISD::UNPCKH:
21977       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21978       // We can't check for single use, we have to check that this shuffle is the only user.
21979       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21980           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21981                                         HasPSHUFB, DAG, DCI, Subtarget))
21982           return true;
21983       break;
21984   }
21985
21986   // Minor canonicalization of the accumulated shuffle mask to make it easier
21987   // to match below. All this does is detect masks with squential pairs of
21988   // elements, and shrink them to the half-width mask. It does this in a loop
21989   // so it will reduce the size of the mask to the minimal width mask which
21990   // performs an equivalent shuffle.
21991   SmallVector<int, 16> WidenedMask;
21992   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21993     Mask = std::move(WidenedMask);
21994     WidenedMask.clear();
21995   }
21996
21997   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21998                                 Subtarget);
21999 }
22000
22001 /// \brief Get the PSHUF-style mask from PSHUF node.
22002 ///
22003 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22004 /// PSHUF-style masks that can be reused with such instructions.
22005 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22006   MVT VT = N.getSimpleValueType();
22007   SmallVector<int, 4> Mask;
22008   bool IsUnary;
22009   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22010   (void)HaveMask;
22011   assert(HaveMask);
22012
22013   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22014   // matter. Check that the upper masks are repeats and remove them.
22015   if (VT.getSizeInBits() > 128) {
22016     int LaneElts = 128 / VT.getScalarSizeInBits();
22017 #ifndef NDEBUG
22018     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22019       for (int j = 0; j < LaneElts; ++j)
22020         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22021                "Mask doesn't repeat in high 128-bit lanes!");
22022 #endif
22023     Mask.resize(LaneElts);
22024   }
22025
22026   switch (N.getOpcode()) {
22027   case X86ISD::PSHUFD:
22028     return Mask;
22029   case X86ISD::PSHUFLW:
22030     Mask.resize(4);
22031     return Mask;
22032   case X86ISD::PSHUFHW:
22033     Mask.erase(Mask.begin(), Mask.begin() + 4);
22034     for (int &M : Mask)
22035       M -= 4;
22036     return Mask;
22037   default:
22038     llvm_unreachable("No valid shuffle instruction found!");
22039   }
22040 }
22041
22042 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22043 ///
22044 /// We walk up the chain and look for a combinable shuffle, skipping over
22045 /// shuffles that we could hoist this shuffle's transformation past without
22046 /// altering anything.
22047 static SDValue
22048 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22049                              SelectionDAG &DAG,
22050                              TargetLowering::DAGCombinerInfo &DCI) {
22051   assert(N.getOpcode() == X86ISD::PSHUFD &&
22052          "Called with something other than an x86 128-bit half shuffle!");
22053   SDLoc DL(N);
22054
22055   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22056   // of the shuffles in the chain so that we can form a fresh chain to replace
22057   // this one.
22058   SmallVector<SDValue, 8> Chain;
22059   SDValue V = N.getOperand(0);
22060   for (; V.hasOneUse(); V = V.getOperand(0)) {
22061     switch (V.getOpcode()) {
22062     default:
22063       return SDValue(); // Nothing combined!
22064
22065     case ISD::BITCAST:
22066       // Skip bitcasts as we always know the type for the target specific
22067       // instructions.
22068       continue;
22069
22070     case X86ISD::PSHUFD:
22071       // Found another dword shuffle.
22072       break;
22073
22074     case X86ISD::PSHUFLW:
22075       // Check that the low words (being shuffled) are the identity in the
22076       // dword shuffle, and the high words are self-contained.
22077       if (Mask[0] != 0 || Mask[1] != 1 ||
22078           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22079         return SDValue();
22080
22081       Chain.push_back(V);
22082       continue;
22083
22084     case X86ISD::PSHUFHW:
22085       // Check that the high words (being shuffled) are the identity in the
22086       // dword shuffle, and the low words are self-contained.
22087       if (Mask[2] != 2 || Mask[3] != 3 ||
22088           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22089         return SDValue();
22090
22091       Chain.push_back(V);
22092       continue;
22093
22094     case X86ISD::UNPCKL:
22095     case X86ISD::UNPCKH:
22096       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22097       // shuffle into a preceding word shuffle.
22098       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22099           V.getSimpleValueType().getScalarType() != MVT::i16)
22100         return SDValue();
22101
22102       // Search for a half-shuffle which we can combine with.
22103       unsigned CombineOp =
22104           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22105       if (V.getOperand(0) != V.getOperand(1) ||
22106           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22107         return SDValue();
22108       Chain.push_back(V);
22109       V = V.getOperand(0);
22110       do {
22111         switch (V.getOpcode()) {
22112         default:
22113           return SDValue(); // Nothing to combine.
22114
22115         case X86ISD::PSHUFLW:
22116         case X86ISD::PSHUFHW:
22117           if (V.getOpcode() == CombineOp)
22118             break;
22119
22120           Chain.push_back(V);
22121
22122           // Fallthrough!
22123         case ISD::BITCAST:
22124           V = V.getOperand(0);
22125           continue;
22126         }
22127         break;
22128       } while (V.hasOneUse());
22129       break;
22130     }
22131     // Break out of the loop if we break out of the switch.
22132     break;
22133   }
22134
22135   if (!V.hasOneUse())
22136     // We fell out of the loop without finding a viable combining instruction.
22137     return SDValue();
22138
22139   // Merge this node's mask and our incoming mask.
22140   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22141   for (int &M : Mask)
22142     M = VMask[M];
22143   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22144                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22145
22146   // Rebuild the chain around this new shuffle.
22147   while (!Chain.empty()) {
22148     SDValue W = Chain.pop_back_val();
22149
22150     if (V.getValueType() != W.getOperand(0).getValueType())
22151       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22152
22153     switch (W.getOpcode()) {
22154     default:
22155       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22156
22157     case X86ISD::UNPCKL:
22158     case X86ISD::UNPCKH:
22159       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22160       break;
22161
22162     case X86ISD::PSHUFD:
22163     case X86ISD::PSHUFLW:
22164     case X86ISD::PSHUFHW:
22165       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22166       break;
22167     }
22168   }
22169   if (V.getValueType() != N.getValueType())
22170     V = DAG.getBitcast(N.getValueType(), V);
22171
22172   // Return the new chain to replace N.
22173   return V;
22174 }
22175
22176 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22177 ///
22178 /// We walk up the chain, skipping shuffles of the other half and looking
22179 /// through shuffles which switch halves trying to find a shuffle of the same
22180 /// pair of dwords.
22181 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22182                                         SelectionDAG &DAG,
22183                                         TargetLowering::DAGCombinerInfo &DCI) {
22184   assert(
22185       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22186       "Called with something other than an x86 128-bit half shuffle!");
22187   SDLoc DL(N);
22188   unsigned CombineOpcode = N.getOpcode();
22189
22190   // Walk up a single-use chain looking for a combinable shuffle.
22191   SDValue V = N.getOperand(0);
22192   for (; V.hasOneUse(); V = V.getOperand(0)) {
22193     switch (V.getOpcode()) {
22194     default:
22195       return false; // Nothing combined!
22196
22197     case ISD::BITCAST:
22198       // Skip bitcasts as we always know the type for the target specific
22199       // instructions.
22200       continue;
22201
22202     case X86ISD::PSHUFLW:
22203     case X86ISD::PSHUFHW:
22204       if (V.getOpcode() == CombineOpcode)
22205         break;
22206
22207       // Other-half shuffles are no-ops.
22208       continue;
22209     }
22210     // Break out of the loop if we break out of the switch.
22211     break;
22212   }
22213
22214   if (!V.hasOneUse())
22215     // We fell out of the loop without finding a viable combining instruction.
22216     return false;
22217
22218   // Combine away the bottom node as its shuffle will be accumulated into
22219   // a preceding shuffle.
22220   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22221
22222   // Record the old value.
22223   SDValue Old = V;
22224
22225   // Merge this node's mask and our incoming mask (adjusted to account for all
22226   // the pshufd instructions encountered).
22227   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22228   for (int &M : Mask)
22229     M = VMask[M];
22230   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22231                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22232
22233   // Check that the shuffles didn't cancel each other out. If not, we need to
22234   // combine to the new one.
22235   if (Old != V)
22236     // Replace the combinable shuffle with the combined one, updating all users
22237     // so that we re-evaluate the chain here.
22238     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22239
22240   return true;
22241 }
22242
22243 /// \brief Try to combine x86 target specific shuffles.
22244 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22245                                            TargetLowering::DAGCombinerInfo &DCI,
22246                                            const X86Subtarget *Subtarget) {
22247   SDLoc DL(N);
22248   MVT VT = N.getSimpleValueType();
22249   SmallVector<int, 4> Mask;
22250
22251   switch (N.getOpcode()) {
22252   case X86ISD::PSHUFD:
22253   case X86ISD::PSHUFLW:
22254   case X86ISD::PSHUFHW:
22255     Mask = getPSHUFShuffleMask(N);
22256     assert(Mask.size() == 4);
22257     break;
22258   default:
22259     return SDValue();
22260   }
22261
22262   // Nuke no-op shuffles that show up after combining.
22263   if (isNoopShuffleMask(Mask))
22264     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22265
22266   // Look for simplifications involving one or two shuffle instructions.
22267   SDValue V = N.getOperand(0);
22268   switch (N.getOpcode()) {
22269   default:
22270     break;
22271   case X86ISD::PSHUFLW:
22272   case X86ISD::PSHUFHW:
22273     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22274
22275     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22276       return SDValue(); // We combined away this shuffle, so we're done.
22277
22278     // See if this reduces to a PSHUFD which is no more expensive and can
22279     // combine with more operations. Note that it has to at least flip the
22280     // dwords as otherwise it would have been removed as a no-op.
22281     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22282       int DMask[] = {0, 1, 2, 3};
22283       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22284       DMask[DOffset + 0] = DOffset + 1;
22285       DMask[DOffset + 1] = DOffset + 0;
22286       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22287       V = DAG.getBitcast(DVT, V);
22288       DCI.AddToWorklist(V.getNode());
22289       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22290                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22291       DCI.AddToWorklist(V.getNode());
22292       return DAG.getBitcast(VT, V);
22293     }
22294
22295     // Look for shuffle patterns which can be implemented as a single unpack.
22296     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22297     // only works when we have a PSHUFD followed by two half-shuffles.
22298     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22299         (V.getOpcode() == X86ISD::PSHUFLW ||
22300          V.getOpcode() == X86ISD::PSHUFHW) &&
22301         V.getOpcode() != N.getOpcode() &&
22302         V.hasOneUse()) {
22303       SDValue D = V.getOperand(0);
22304       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22305         D = D.getOperand(0);
22306       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22307         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22308         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22309         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22310         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22311         int WordMask[8];
22312         for (int i = 0; i < 4; ++i) {
22313           WordMask[i + NOffset] = Mask[i] + NOffset;
22314           WordMask[i + VOffset] = VMask[i] + VOffset;
22315         }
22316         // Map the word mask through the DWord mask.
22317         int MappedMask[8];
22318         for (int i = 0; i < 8; ++i)
22319           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22320         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22321             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22322           // We can replace all three shuffles with an unpack.
22323           V = DAG.getBitcast(VT, D.getOperand(0));
22324           DCI.AddToWorklist(V.getNode());
22325           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22326                                                 : X86ISD::UNPCKH,
22327                              DL, VT, V, V);
22328         }
22329       }
22330     }
22331
22332     break;
22333
22334   case X86ISD::PSHUFD:
22335     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22336       return NewN;
22337
22338     break;
22339   }
22340
22341   return SDValue();
22342 }
22343
22344 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22345 ///
22346 /// We combine this directly on the abstract vector shuffle nodes so it is
22347 /// easier to generically match. We also insert dummy vector shuffle nodes for
22348 /// the operands which explicitly discard the lanes which are unused by this
22349 /// operation to try to flow through the rest of the combiner the fact that
22350 /// they're unused.
22351 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22352   SDLoc DL(N);
22353   EVT VT = N->getValueType(0);
22354
22355   // We only handle target-independent shuffles.
22356   // FIXME: It would be easy and harmless to use the target shuffle mask
22357   // extraction tool to support more.
22358   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22359     return SDValue();
22360
22361   auto *SVN = cast<ShuffleVectorSDNode>(N);
22362   ArrayRef<int> Mask = SVN->getMask();
22363   SDValue V1 = N->getOperand(0);
22364   SDValue V2 = N->getOperand(1);
22365
22366   // We require the first shuffle operand to be the SUB node, and the second to
22367   // be the ADD node.
22368   // FIXME: We should support the commuted patterns.
22369   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22370     return SDValue();
22371
22372   // If there are other uses of these operations we can't fold them.
22373   if (!V1->hasOneUse() || !V2->hasOneUse())
22374     return SDValue();
22375
22376   // Ensure that both operations have the same operands. Note that we can
22377   // commute the FADD operands.
22378   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22379   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22380       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22381     return SDValue();
22382
22383   // We're looking for blends between FADD and FSUB nodes. We insist on these
22384   // nodes being lined up in a specific expected pattern.
22385   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22386         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22387         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22388     return SDValue();
22389
22390   // Only specific types are legal at this point, assert so we notice if and
22391   // when these change.
22392   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22393           VT == MVT::v4f64) &&
22394          "Unknown vector type encountered!");
22395
22396   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22397 }
22398
22399 /// PerformShuffleCombine - Performs several different shuffle combines.
22400 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22401                                      TargetLowering::DAGCombinerInfo &DCI,
22402                                      const X86Subtarget *Subtarget) {
22403   SDLoc dl(N);
22404   SDValue N0 = N->getOperand(0);
22405   SDValue N1 = N->getOperand(1);
22406   EVT VT = N->getValueType(0);
22407
22408   // Don't create instructions with illegal types after legalize types has run.
22409   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22410   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22411     return SDValue();
22412
22413   // If we have legalized the vector types, look for blends of FADD and FSUB
22414   // nodes that we can fuse into an ADDSUB node.
22415   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22416     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22417       return AddSub;
22418
22419   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22420   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22421       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22422     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22423
22424   // During Type Legalization, when promoting illegal vector types,
22425   // the backend might introduce new shuffle dag nodes and bitcasts.
22426   //
22427   // This code performs the following transformation:
22428   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22429   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22430   //
22431   // We do this only if both the bitcast and the BINOP dag nodes have
22432   // one use. Also, perform this transformation only if the new binary
22433   // operation is legal. This is to avoid introducing dag nodes that
22434   // potentially need to be further expanded (or custom lowered) into a
22435   // less optimal sequence of dag nodes.
22436   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22437       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22438       N0.getOpcode() == ISD::BITCAST) {
22439     SDValue BC0 = N0.getOperand(0);
22440     EVT SVT = BC0.getValueType();
22441     unsigned Opcode = BC0.getOpcode();
22442     unsigned NumElts = VT.getVectorNumElements();
22443
22444     if (BC0.hasOneUse() && SVT.isVector() &&
22445         SVT.getVectorNumElements() * 2 == NumElts &&
22446         TLI.isOperationLegal(Opcode, VT)) {
22447       bool CanFold = false;
22448       switch (Opcode) {
22449       default : break;
22450       case ISD::ADD :
22451       case ISD::FADD :
22452       case ISD::SUB :
22453       case ISD::FSUB :
22454       case ISD::MUL :
22455       case ISD::FMUL :
22456         CanFold = true;
22457       }
22458
22459       unsigned SVTNumElts = SVT.getVectorNumElements();
22460       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22461       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22462         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22463       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22464         CanFold = SVOp->getMaskElt(i) < 0;
22465
22466       if (CanFold) {
22467         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22468         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22469         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22470         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22471       }
22472     }
22473   }
22474
22475   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22476   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22477   // consecutive, non-overlapping, and in the right order.
22478   SmallVector<SDValue, 16> Elts;
22479   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22480     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22481
22482   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22483     return LD;
22484
22485   if (isTargetShuffle(N->getOpcode())) {
22486     SDValue Shuffle =
22487         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22488     if (Shuffle.getNode())
22489       return Shuffle;
22490
22491     // Try recursively combining arbitrary sequences of x86 shuffle
22492     // instructions into higher-order shuffles. We do this after combining
22493     // specific PSHUF instruction sequences into their minimal form so that we
22494     // can evaluate how many specialized shuffle instructions are involved in
22495     // a particular chain.
22496     SmallVector<int, 1> NonceMask; // Just a placeholder.
22497     NonceMask.push_back(0);
22498     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22499                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22500                                       DCI, Subtarget))
22501       return SDValue(); // This routine will use CombineTo to replace N.
22502   }
22503
22504   return SDValue();
22505 }
22506
22507 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22508 /// specific shuffle of a load can be folded into a single element load.
22509 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22510 /// shuffles have been custom lowered so we need to handle those here.
22511 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22512                                          TargetLowering::DAGCombinerInfo &DCI) {
22513   if (DCI.isBeforeLegalizeOps())
22514     return SDValue();
22515
22516   SDValue InVec = N->getOperand(0);
22517   SDValue EltNo = N->getOperand(1);
22518
22519   if (!isa<ConstantSDNode>(EltNo))
22520     return SDValue();
22521
22522   EVT OriginalVT = InVec.getValueType();
22523
22524   if (InVec.getOpcode() == ISD::BITCAST) {
22525     // Don't duplicate a load with other uses.
22526     if (!InVec.hasOneUse())
22527       return SDValue();
22528     EVT BCVT = InVec.getOperand(0).getValueType();
22529     if (!BCVT.isVector() ||
22530         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22531       return SDValue();
22532     InVec = InVec.getOperand(0);
22533   }
22534
22535   EVT CurrentVT = InVec.getValueType();
22536
22537   if (!isTargetShuffle(InVec.getOpcode()))
22538     return SDValue();
22539
22540   // Don't duplicate a load with other uses.
22541   if (!InVec.hasOneUse())
22542     return SDValue();
22543
22544   SmallVector<int, 16> ShuffleMask;
22545   bool UnaryShuffle;
22546   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22547                             ShuffleMask, UnaryShuffle))
22548     return SDValue();
22549
22550   // Select the input vector, guarding against out of range extract vector.
22551   unsigned NumElems = CurrentVT.getVectorNumElements();
22552   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22553   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22554   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22555                                          : InVec.getOperand(1);
22556
22557   // If inputs to shuffle are the same for both ops, then allow 2 uses
22558   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22559                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22560
22561   if (LdNode.getOpcode() == ISD::BITCAST) {
22562     // Don't duplicate a load with other uses.
22563     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22564       return SDValue();
22565
22566     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22567     LdNode = LdNode.getOperand(0);
22568   }
22569
22570   if (!ISD::isNormalLoad(LdNode.getNode()))
22571     return SDValue();
22572
22573   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22574
22575   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22576     return SDValue();
22577
22578   EVT EltVT = N->getValueType(0);
22579   // If there's a bitcast before the shuffle, check if the load type and
22580   // alignment is valid.
22581   unsigned Align = LN0->getAlignment();
22582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22583   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22584       EltVT.getTypeForEVT(*DAG.getContext()));
22585
22586   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22587     return SDValue();
22588
22589   // All checks match so transform back to vector_shuffle so that DAG combiner
22590   // can finish the job
22591   SDLoc dl(N);
22592
22593   // Create shuffle node taking into account the case that its a unary shuffle
22594   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22595                                    : InVec.getOperand(1);
22596   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22597                                  InVec.getOperand(0), Shuffle,
22598                                  &ShuffleMask[0]);
22599   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22600   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22601                      EltNo);
22602 }
22603
22604 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22605 /// special and don't usually play with other vector types, it's better to
22606 /// handle them early to be sure we emit efficient code by avoiding
22607 /// store-load conversions.
22608 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22609   if (N->getValueType(0) != MVT::x86mmx ||
22610       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22611       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22612     return SDValue();
22613
22614   SDValue V = N->getOperand(0);
22615   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22616   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22617     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22618                        N->getValueType(0), V.getOperand(0));
22619
22620   return SDValue();
22621 }
22622
22623 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22624 /// generation and convert it from being a bunch of shuffles and extracts
22625 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22626 /// storing the value and loading scalars back, while for x64 we should
22627 /// use 64-bit extracts and shifts.
22628 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22629                                          TargetLowering::DAGCombinerInfo &DCI) {
22630   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22631     return NewOp;
22632
22633   SDValue InputVector = N->getOperand(0);
22634   SDLoc dl(InputVector);
22635   // Detect mmx to i32 conversion through a v2i32 elt extract.
22636   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22637       N->getValueType(0) == MVT::i32 &&
22638       InputVector.getValueType() == MVT::v2i32) {
22639
22640     // The bitcast source is a direct mmx result.
22641     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22642     if (MMXSrc.getValueType() == MVT::x86mmx)
22643       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22644                          N->getValueType(0),
22645                          InputVector.getNode()->getOperand(0));
22646
22647     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22648     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22649     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22650         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22651         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22652         MMXSrcOp.getValueType() == MVT::v1i64 &&
22653         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22654       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22655                          N->getValueType(0),
22656                          MMXSrcOp.getOperand(0));
22657   }
22658
22659   EVT VT = N->getValueType(0);
22660
22661   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22662       InputVector.getOpcode() == ISD::BITCAST &&
22663       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22664     uint64_t ExtractedElt =
22665           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22666     uint64_t InputValue =
22667           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22668     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22669     return DAG.getConstant(Res, dl, MVT::i1);
22670   }
22671   // Only operate on vectors of 4 elements, where the alternative shuffling
22672   // gets to be more expensive.
22673   if (InputVector.getValueType() != MVT::v4i32)
22674     return SDValue();
22675
22676   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22677   // single use which is a sign-extend or zero-extend, and all elements are
22678   // used.
22679   SmallVector<SDNode *, 4> Uses;
22680   unsigned ExtractedElements = 0;
22681   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22682        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22683     if (UI.getUse().getResNo() != InputVector.getResNo())
22684       return SDValue();
22685
22686     SDNode *Extract = *UI;
22687     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22688       return SDValue();
22689
22690     if (Extract->getValueType(0) != MVT::i32)
22691       return SDValue();
22692     if (!Extract->hasOneUse())
22693       return SDValue();
22694     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22695         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22696       return SDValue();
22697     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22698       return SDValue();
22699
22700     // Record which element was extracted.
22701     ExtractedElements |=
22702       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22703
22704     Uses.push_back(Extract);
22705   }
22706
22707   // If not all the elements were used, this may not be worthwhile.
22708   if (ExtractedElements != 15)
22709     return SDValue();
22710
22711   // Ok, we've now decided to do the transformation.
22712   // If 64-bit shifts are legal, use the extract-shift sequence,
22713   // otherwise bounce the vector off the cache.
22714   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22715   SDValue Vals[4];
22716
22717   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22718     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22719     auto &DL = DAG.getDataLayout();
22720     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22721     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22722       DAG.getConstant(0, dl, VecIdxTy));
22723     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22724       DAG.getConstant(1, dl, VecIdxTy));
22725
22726     SDValue ShAmt = DAG.getConstant(
22727         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22728     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22729     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22730       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22731     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22732     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22733       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22734   } else {
22735     // Store the value to a temporary stack slot.
22736     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22737     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22738       MachinePointerInfo(), false, false, 0);
22739
22740     EVT ElementType = InputVector.getValueType().getVectorElementType();
22741     unsigned EltSize = ElementType.getSizeInBits() / 8;
22742
22743     // Replace each use (extract) with a load of the appropriate element.
22744     for (unsigned i = 0; i < 4; ++i) {
22745       uint64_t Offset = EltSize * i;
22746       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22747       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22748
22749       SDValue ScalarAddr =
22750           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22751
22752       // Load the scalar.
22753       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22754                             ScalarAddr, MachinePointerInfo(),
22755                             false, false, false, 0);
22756
22757     }
22758   }
22759
22760   // Replace the extracts
22761   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22762     UE = Uses.end(); UI != UE; ++UI) {
22763     SDNode *Extract = *UI;
22764
22765     SDValue Idx = Extract->getOperand(1);
22766     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22767     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22768   }
22769
22770   // The replacement was made in place; don't return anything.
22771   return SDValue();
22772 }
22773
22774 static SDValue
22775 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22776                                       const X86Subtarget *Subtarget) {
22777   SDLoc dl(N);
22778   SDValue Cond = N->getOperand(0);
22779   SDValue LHS = N->getOperand(1);
22780   SDValue RHS = N->getOperand(2);
22781
22782   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22783     SDValue CondSrc = Cond->getOperand(0);
22784     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22785       Cond = CondSrc->getOperand(0);
22786   }
22787
22788   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22789     return SDValue();
22790
22791   // A vselect where all conditions and data are constants can be optimized into
22792   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22793   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22794       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22795     return SDValue();
22796
22797   unsigned MaskValue = 0;
22798   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22799     return SDValue();
22800
22801   MVT VT = N->getSimpleValueType(0);
22802   unsigned NumElems = VT.getVectorNumElements();
22803   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22804   for (unsigned i = 0; i < NumElems; ++i) {
22805     // Be sure we emit undef where we can.
22806     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22807       ShuffleMask[i] = -1;
22808     else
22809       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22810   }
22811
22812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22813   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22814     return SDValue();
22815   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22816 }
22817
22818 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22819 /// nodes.
22820 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22821                                     TargetLowering::DAGCombinerInfo &DCI,
22822                                     const X86Subtarget *Subtarget) {
22823   SDLoc DL(N);
22824   SDValue Cond = N->getOperand(0);
22825   // Get the LHS/RHS of the select.
22826   SDValue LHS = N->getOperand(1);
22827   SDValue RHS = N->getOperand(2);
22828   EVT VT = LHS.getValueType();
22829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22830
22831   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22832   // instructions match the semantics of the common C idiom x<y?x:y but not
22833   // x<=y?x:y, because of how they handle negative zero (which can be
22834   // ignored in unsafe-math mode).
22835   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22836   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22837       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22838       (Subtarget->hasSSE2() ||
22839        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22840     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22841
22842     unsigned Opcode = 0;
22843     // Check for x CC y ? x : y.
22844     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22845         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22846       switch (CC) {
22847       default: break;
22848       case ISD::SETULT:
22849         // Converting this to a min would handle NaNs incorrectly, and swapping
22850         // the operands would cause it to handle comparisons between positive
22851         // and negative zero incorrectly.
22852         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22853           if (!DAG.getTarget().Options.UnsafeFPMath &&
22854               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22855             break;
22856           std::swap(LHS, RHS);
22857         }
22858         Opcode = X86ISD::FMIN;
22859         break;
22860       case ISD::SETOLE:
22861         // Converting this to a min would handle comparisons between positive
22862         // and negative zero incorrectly.
22863         if (!DAG.getTarget().Options.UnsafeFPMath &&
22864             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22865           break;
22866         Opcode = X86ISD::FMIN;
22867         break;
22868       case ISD::SETULE:
22869         // Converting this to a min would handle both negative zeros and NaNs
22870         // incorrectly, but we can swap the operands to fix both.
22871         std::swap(LHS, RHS);
22872       case ISD::SETOLT:
22873       case ISD::SETLT:
22874       case ISD::SETLE:
22875         Opcode = X86ISD::FMIN;
22876         break;
22877
22878       case ISD::SETOGE:
22879         // Converting this to a max would handle comparisons between positive
22880         // and negative zero incorrectly.
22881         if (!DAG.getTarget().Options.UnsafeFPMath &&
22882             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22883           break;
22884         Opcode = X86ISD::FMAX;
22885         break;
22886       case ISD::SETUGT:
22887         // Converting this to a max would handle NaNs incorrectly, and swapping
22888         // the operands would cause it to handle comparisons between positive
22889         // and negative zero incorrectly.
22890         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22891           if (!DAG.getTarget().Options.UnsafeFPMath &&
22892               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22893             break;
22894           std::swap(LHS, RHS);
22895         }
22896         Opcode = X86ISD::FMAX;
22897         break;
22898       case ISD::SETUGE:
22899         // Converting this to a max would handle both negative zeros and NaNs
22900         // incorrectly, but we can swap the operands to fix both.
22901         std::swap(LHS, RHS);
22902       case ISD::SETOGT:
22903       case ISD::SETGT:
22904       case ISD::SETGE:
22905         Opcode = X86ISD::FMAX;
22906         break;
22907       }
22908     // Check for x CC y ? y : x -- a min/max with reversed arms.
22909     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22910                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22911       switch (CC) {
22912       default: break;
22913       case ISD::SETOGE:
22914         // Converting this to a min would handle comparisons between positive
22915         // and negative zero incorrectly, and swapping the operands would
22916         // cause it to handle NaNs incorrectly.
22917         if (!DAG.getTarget().Options.UnsafeFPMath &&
22918             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22919           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22920             break;
22921           std::swap(LHS, RHS);
22922         }
22923         Opcode = X86ISD::FMIN;
22924         break;
22925       case ISD::SETUGT:
22926         // Converting this to a min would handle NaNs incorrectly.
22927         if (!DAG.getTarget().Options.UnsafeFPMath &&
22928             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22929           break;
22930         Opcode = X86ISD::FMIN;
22931         break;
22932       case ISD::SETUGE:
22933         // Converting this to a min would handle both negative zeros and NaNs
22934         // incorrectly, but we can swap the operands to fix both.
22935         std::swap(LHS, RHS);
22936       case ISD::SETOGT:
22937       case ISD::SETGT:
22938       case ISD::SETGE:
22939         Opcode = X86ISD::FMIN;
22940         break;
22941
22942       case ISD::SETULT:
22943         // Converting this to a max would handle NaNs incorrectly.
22944         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22945           break;
22946         Opcode = X86ISD::FMAX;
22947         break;
22948       case ISD::SETOLE:
22949         // Converting this to a max would handle comparisons between positive
22950         // and negative zero incorrectly, and swapping the operands would
22951         // cause it to handle NaNs incorrectly.
22952         if (!DAG.getTarget().Options.UnsafeFPMath &&
22953             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22954           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22955             break;
22956           std::swap(LHS, RHS);
22957         }
22958         Opcode = X86ISD::FMAX;
22959         break;
22960       case ISD::SETULE:
22961         // Converting this to a max would handle both negative zeros and NaNs
22962         // incorrectly, but we can swap the operands to fix both.
22963         std::swap(LHS, RHS);
22964       case ISD::SETOLT:
22965       case ISD::SETLT:
22966       case ISD::SETLE:
22967         Opcode = X86ISD::FMAX;
22968         break;
22969       }
22970     }
22971
22972     if (Opcode)
22973       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22974   }
22975
22976   EVT CondVT = Cond.getValueType();
22977   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22978       CondVT.getVectorElementType() == MVT::i1) {
22979     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22980     // lowering on KNL. In this case we convert it to
22981     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22982     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22983     // Since SKX these selects have a proper lowering.
22984     EVT OpVT = LHS.getValueType();
22985     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22986         (OpVT.getVectorElementType() == MVT::i8 ||
22987          OpVT.getVectorElementType() == MVT::i16) &&
22988         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22989       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22990       DCI.AddToWorklist(Cond.getNode());
22991       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22992     }
22993   }
22994   // If this is a select between two integer constants, try to do some
22995   // optimizations.
22996   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22997     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22998       // Don't do this for crazy integer types.
22999       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23000         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23001         // so that TrueC (the true value) is larger than FalseC.
23002         bool NeedsCondInvert = false;
23003
23004         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23005             // Efficiently invertible.
23006             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23007              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23008               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23009           NeedsCondInvert = true;
23010           std::swap(TrueC, FalseC);
23011         }
23012
23013         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23014         if (FalseC->getAPIntValue() == 0 &&
23015             TrueC->getAPIntValue().isPowerOf2()) {
23016           if (NeedsCondInvert) // Invert the condition if needed.
23017             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23018                                DAG.getConstant(1, DL, Cond.getValueType()));
23019
23020           // Zero extend the condition if needed.
23021           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23022
23023           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23024           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23025                              DAG.getConstant(ShAmt, DL, MVT::i8));
23026         }
23027
23028         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23029         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23030           if (NeedsCondInvert) // Invert the condition if needed.
23031             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23032                                DAG.getConstant(1, DL, Cond.getValueType()));
23033
23034           // Zero extend the condition if needed.
23035           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23036                              FalseC->getValueType(0), Cond);
23037           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23038                              SDValue(FalseC, 0));
23039         }
23040
23041         // Optimize cases that will turn into an LEA instruction.  This requires
23042         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23043         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23044           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23045           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23046
23047           bool isFastMultiplier = false;
23048           if (Diff < 10) {
23049             switch ((unsigned char)Diff) {
23050               default: break;
23051               case 1:  // result = add base, cond
23052               case 2:  // result = lea base(    , cond*2)
23053               case 3:  // result = lea base(cond, cond*2)
23054               case 4:  // result = lea base(    , cond*4)
23055               case 5:  // result = lea base(cond, cond*4)
23056               case 8:  // result = lea base(    , cond*8)
23057               case 9:  // result = lea base(cond, cond*8)
23058                 isFastMultiplier = true;
23059                 break;
23060             }
23061           }
23062
23063           if (isFastMultiplier) {
23064             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23065             if (NeedsCondInvert) // Invert the condition if needed.
23066               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23067                                  DAG.getConstant(1, DL, Cond.getValueType()));
23068
23069             // Zero extend the condition if needed.
23070             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23071                                Cond);
23072             // Scale the condition by the difference.
23073             if (Diff != 1)
23074               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23075                                  DAG.getConstant(Diff, DL,
23076                                                  Cond.getValueType()));
23077
23078             // Add the base if non-zero.
23079             if (FalseC->getAPIntValue() != 0)
23080               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23081                                  SDValue(FalseC, 0));
23082             return Cond;
23083           }
23084         }
23085       }
23086   }
23087
23088   // Canonicalize max and min:
23089   // (x > y) ? x : y -> (x >= y) ? x : y
23090   // (x < y) ? x : y -> (x <= y) ? x : y
23091   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23092   // the need for an extra compare
23093   // against zero. e.g.
23094   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23095   // subl   %esi, %edi
23096   // testl  %edi, %edi
23097   // movl   $0, %eax
23098   // cmovgl %edi, %eax
23099   // =>
23100   // xorl   %eax, %eax
23101   // subl   %esi, $edi
23102   // cmovsl %eax, %edi
23103   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23104       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23105       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23106     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23107     switch (CC) {
23108     default: break;
23109     case ISD::SETLT:
23110     case ISD::SETGT: {
23111       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23112       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23113                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23114       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23115     }
23116     }
23117   }
23118
23119   // Early exit check
23120   if (!TLI.isTypeLegal(VT))
23121     return SDValue();
23122
23123   // Match VSELECTs into subs with unsigned saturation.
23124   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23125       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23126       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23127        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23128     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23129
23130     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23131     // left side invert the predicate to simplify logic below.
23132     SDValue Other;
23133     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23134       Other = RHS;
23135       CC = ISD::getSetCCInverse(CC, true);
23136     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23137       Other = LHS;
23138     }
23139
23140     if (Other.getNode() && Other->getNumOperands() == 2 &&
23141         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23142       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23143       SDValue CondRHS = Cond->getOperand(1);
23144
23145       // Look for a general sub with unsigned saturation first.
23146       // x >= y ? x-y : 0 --> subus x, y
23147       // x >  y ? x-y : 0 --> subus x, y
23148       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23149           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23150         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23151
23152       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23153         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23154           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23155             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23156               // If the RHS is a constant we have to reverse the const
23157               // canonicalization.
23158               // x > C-1 ? x+-C : 0 --> subus x, C
23159               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23160                   CondRHSConst->getAPIntValue() ==
23161                       (-OpRHSConst->getAPIntValue() - 1))
23162                 return DAG.getNode(
23163                     X86ISD::SUBUS, DL, VT, OpLHS,
23164                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23165
23166           // Another special case: If C was a sign bit, the sub has been
23167           // canonicalized into a xor.
23168           // FIXME: Would it be better to use computeKnownBits to determine
23169           //        whether it's safe to decanonicalize the xor?
23170           // x s< 0 ? x^C : 0 --> subus x, C
23171           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23172               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23173               OpRHSConst->getAPIntValue().isSignBit())
23174             // Note that we have to rebuild the RHS constant here to ensure we
23175             // don't rely on particular values of undef lanes.
23176             return DAG.getNode(
23177                 X86ISD::SUBUS, DL, VT, OpLHS,
23178                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23179         }
23180     }
23181   }
23182
23183   // Simplify vector selection if condition value type matches vselect
23184   // operand type
23185   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23186     assert(Cond.getValueType().isVector() &&
23187            "vector select expects a vector selector!");
23188
23189     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23190     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23191
23192     // Try invert the condition if true value is not all 1s and false value
23193     // is not all 0s.
23194     if (!TValIsAllOnes && !FValIsAllZeros &&
23195         // Check if the selector will be produced by CMPP*/PCMP*
23196         Cond.getOpcode() == ISD::SETCC &&
23197         // Check if SETCC has already been promoted
23198         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23199             CondVT) {
23200       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23201       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23202
23203       if (TValIsAllZeros || FValIsAllOnes) {
23204         SDValue CC = Cond.getOperand(2);
23205         ISD::CondCode NewCC =
23206           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23207                                Cond.getOperand(0).getValueType().isInteger());
23208         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23209         std::swap(LHS, RHS);
23210         TValIsAllOnes = FValIsAllOnes;
23211         FValIsAllZeros = TValIsAllZeros;
23212       }
23213     }
23214
23215     if (TValIsAllOnes || FValIsAllZeros) {
23216       SDValue Ret;
23217
23218       if (TValIsAllOnes && FValIsAllZeros)
23219         Ret = Cond;
23220       else if (TValIsAllOnes)
23221         Ret =
23222             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23223       else if (FValIsAllZeros)
23224         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23225                           DAG.getBitcast(CondVT, LHS));
23226
23227       return DAG.getBitcast(VT, Ret);
23228     }
23229   }
23230
23231   // We should generate an X86ISD::BLENDI from a vselect if its argument
23232   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23233   // constants. This specific pattern gets generated when we split a
23234   // selector for a 512 bit vector in a machine without AVX512 (but with
23235   // 256-bit vectors), during legalization:
23236   //
23237   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23238   //
23239   // Iff we find this pattern and the build_vectors are built from
23240   // constants, we translate the vselect into a shuffle_vector that we
23241   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23242   if ((N->getOpcode() == ISD::VSELECT ||
23243        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23244       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23245     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23246     if (Shuffle.getNode())
23247       return Shuffle;
23248   }
23249
23250   // If this is a *dynamic* select (non-constant condition) and we can match
23251   // this node with one of the variable blend instructions, restructure the
23252   // condition so that the blends can use the high bit of each element and use
23253   // SimplifyDemandedBits to simplify the condition operand.
23254   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23255       !DCI.isBeforeLegalize() &&
23256       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23257     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23258
23259     // Don't optimize vector selects that map to mask-registers.
23260     if (BitWidth == 1)
23261       return SDValue();
23262
23263     // We can only handle the cases where VSELECT is directly legal on the
23264     // subtarget. We custom lower VSELECT nodes with constant conditions and
23265     // this makes it hard to see whether a dynamic VSELECT will correctly
23266     // lower, so we both check the operation's status and explicitly handle the
23267     // cases where a *dynamic* blend will fail even though a constant-condition
23268     // blend could be custom lowered.
23269     // FIXME: We should find a better way to handle this class of problems.
23270     // Potentially, we should combine constant-condition vselect nodes
23271     // pre-legalization into shuffles and not mark as many types as custom
23272     // lowered.
23273     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23274       return SDValue();
23275     // FIXME: We don't support i16-element blends currently. We could and
23276     // should support them by making *all* the bits in the condition be set
23277     // rather than just the high bit and using an i8-element blend.
23278     if (VT.getScalarType() == MVT::i16)
23279       return SDValue();
23280     // Dynamic blending was only available from SSE4.1 onward.
23281     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23282       return SDValue();
23283     // Byte blends are only available in AVX2
23284     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23285         !Subtarget->hasAVX2())
23286       return SDValue();
23287
23288     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23289     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23290
23291     APInt KnownZero, KnownOne;
23292     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23293                                           DCI.isBeforeLegalizeOps());
23294     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23295         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23296                                  TLO)) {
23297       // If we changed the computation somewhere in the DAG, this change
23298       // will affect all users of Cond.
23299       // Make sure it is fine and update all the nodes so that we do not
23300       // use the generic VSELECT anymore. Otherwise, we may perform
23301       // wrong optimizations as we messed up with the actual expectation
23302       // for the vector boolean values.
23303       if (Cond != TLO.Old) {
23304         // Check all uses of that condition operand to check whether it will be
23305         // consumed by non-BLEND instructions, which may depend on all bits are
23306         // set properly.
23307         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23308              I != E; ++I)
23309           if (I->getOpcode() != ISD::VSELECT)
23310             // TODO: Add other opcodes eventually lowered into BLEND.
23311             return SDValue();
23312
23313         // Update all the users of the condition, before committing the change,
23314         // so that the VSELECT optimizations that expect the correct vector
23315         // boolean value will not be triggered.
23316         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23317              I != E; ++I)
23318           DAG.ReplaceAllUsesOfValueWith(
23319               SDValue(*I, 0),
23320               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23321                           Cond, I->getOperand(1), I->getOperand(2)));
23322         DCI.CommitTargetLoweringOpt(TLO);
23323         return SDValue();
23324       }
23325       // At this point, only Cond is changed. Change the condition
23326       // just for N to keep the opportunity to optimize all other
23327       // users their own way.
23328       DAG.ReplaceAllUsesOfValueWith(
23329           SDValue(N, 0),
23330           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23331                       TLO.New, N->getOperand(1), N->getOperand(2)));
23332       return SDValue();
23333     }
23334   }
23335
23336   return SDValue();
23337 }
23338
23339 // Check whether a boolean test is testing a boolean value generated by
23340 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23341 // code.
23342 //
23343 // Simplify the following patterns:
23344 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23345 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23346 // to (Op EFLAGS Cond)
23347 //
23348 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23349 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23350 // to (Op EFLAGS !Cond)
23351 //
23352 // where Op could be BRCOND or CMOV.
23353 //
23354 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23355   // Quit if not CMP and SUB with its value result used.
23356   if (Cmp.getOpcode() != X86ISD::CMP &&
23357       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23358       return SDValue();
23359
23360   // Quit if not used as a boolean value.
23361   if (CC != X86::COND_E && CC != X86::COND_NE)
23362     return SDValue();
23363
23364   // Check CMP operands. One of them should be 0 or 1 and the other should be
23365   // an SetCC or extended from it.
23366   SDValue Op1 = Cmp.getOperand(0);
23367   SDValue Op2 = Cmp.getOperand(1);
23368
23369   SDValue SetCC;
23370   const ConstantSDNode* C = nullptr;
23371   bool needOppositeCond = (CC == X86::COND_E);
23372   bool checkAgainstTrue = false; // Is it a comparison against 1?
23373
23374   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23375     SetCC = Op2;
23376   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23377     SetCC = Op1;
23378   else // Quit if all operands are not constants.
23379     return SDValue();
23380
23381   if (C->getZExtValue() == 1) {
23382     needOppositeCond = !needOppositeCond;
23383     checkAgainstTrue = true;
23384   } else if (C->getZExtValue() != 0)
23385     // Quit if the constant is neither 0 or 1.
23386     return SDValue();
23387
23388   bool truncatedToBoolWithAnd = false;
23389   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23390   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23391          SetCC.getOpcode() == ISD::TRUNCATE ||
23392          SetCC.getOpcode() == ISD::AND) {
23393     if (SetCC.getOpcode() == ISD::AND) {
23394       int OpIdx = -1;
23395       ConstantSDNode *CS;
23396       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23397           CS->getZExtValue() == 1)
23398         OpIdx = 1;
23399       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23400           CS->getZExtValue() == 1)
23401         OpIdx = 0;
23402       if (OpIdx == -1)
23403         break;
23404       SetCC = SetCC.getOperand(OpIdx);
23405       truncatedToBoolWithAnd = true;
23406     } else
23407       SetCC = SetCC.getOperand(0);
23408   }
23409
23410   switch (SetCC.getOpcode()) {
23411   case X86ISD::SETCC_CARRY:
23412     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23413     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23414     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23415     // truncated to i1 using 'and'.
23416     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23417       break;
23418     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23419            "Invalid use of SETCC_CARRY!");
23420     // FALL THROUGH
23421   case X86ISD::SETCC:
23422     // Set the condition code or opposite one if necessary.
23423     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23424     if (needOppositeCond)
23425       CC = X86::GetOppositeBranchCondition(CC);
23426     return SetCC.getOperand(1);
23427   case X86ISD::CMOV: {
23428     // Check whether false/true value has canonical one, i.e. 0 or 1.
23429     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23430     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23431     // Quit if true value is not a constant.
23432     if (!TVal)
23433       return SDValue();
23434     // Quit if false value is not a constant.
23435     if (!FVal) {
23436       SDValue Op = SetCC.getOperand(0);
23437       // Skip 'zext' or 'trunc' node.
23438       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23439           Op.getOpcode() == ISD::TRUNCATE)
23440         Op = Op.getOperand(0);
23441       // A special case for rdrand/rdseed, where 0 is set if false cond is
23442       // found.
23443       if ((Op.getOpcode() != X86ISD::RDRAND &&
23444            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23445         return SDValue();
23446     }
23447     // Quit if false value is not the constant 0 or 1.
23448     bool FValIsFalse = true;
23449     if (FVal && FVal->getZExtValue() != 0) {
23450       if (FVal->getZExtValue() != 1)
23451         return SDValue();
23452       // If FVal is 1, opposite cond is needed.
23453       needOppositeCond = !needOppositeCond;
23454       FValIsFalse = false;
23455     }
23456     // Quit if TVal is not the constant opposite of FVal.
23457     if (FValIsFalse && TVal->getZExtValue() != 1)
23458       return SDValue();
23459     if (!FValIsFalse && TVal->getZExtValue() != 0)
23460       return SDValue();
23461     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23462     if (needOppositeCond)
23463       CC = X86::GetOppositeBranchCondition(CC);
23464     return SetCC.getOperand(3);
23465   }
23466   }
23467
23468   return SDValue();
23469 }
23470
23471 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23472 /// Match:
23473 ///   (X86or (X86setcc) (X86setcc))
23474 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23475 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23476                                            X86::CondCode &CC1, SDValue &Flags,
23477                                            bool &isAnd) {
23478   if (Cond->getOpcode() == X86ISD::CMP) {
23479     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23480     if (!CondOp1C || !CondOp1C->isNullValue())
23481       return false;
23482
23483     Cond = Cond->getOperand(0);
23484   }
23485
23486   isAnd = false;
23487
23488   SDValue SetCC0, SetCC1;
23489   switch (Cond->getOpcode()) {
23490   default: return false;
23491   case ISD::AND:
23492   case X86ISD::AND:
23493     isAnd = true;
23494     // fallthru
23495   case ISD::OR:
23496   case X86ISD::OR:
23497     SetCC0 = Cond->getOperand(0);
23498     SetCC1 = Cond->getOperand(1);
23499     break;
23500   };
23501
23502   // Make sure we have SETCC nodes, using the same flags value.
23503   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23504       SetCC1.getOpcode() != X86ISD::SETCC ||
23505       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23506     return false;
23507
23508   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23509   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23510   Flags = SetCC0->getOperand(1);
23511   return true;
23512 }
23513
23514 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23515 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23516                                   TargetLowering::DAGCombinerInfo &DCI,
23517                                   const X86Subtarget *Subtarget) {
23518   SDLoc DL(N);
23519
23520   // If the flag operand isn't dead, don't touch this CMOV.
23521   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23522     return SDValue();
23523
23524   SDValue FalseOp = N->getOperand(0);
23525   SDValue TrueOp = N->getOperand(1);
23526   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23527   SDValue Cond = N->getOperand(3);
23528
23529   if (CC == X86::COND_E || CC == X86::COND_NE) {
23530     switch (Cond.getOpcode()) {
23531     default: break;
23532     case X86ISD::BSR:
23533     case X86ISD::BSF:
23534       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23535       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23536         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23537     }
23538   }
23539
23540   SDValue Flags;
23541
23542   Flags = checkBoolTestSetCCCombine(Cond, CC);
23543   if (Flags.getNode() &&
23544       // Extra check as FCMOV only supports a subset of X86 cond.
23545       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23546     SDValue Ops[] = { FalseOp, TrueOp,
23547                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23548     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23549   }
23550
23551   // If this is a select between two integer constants, try to do some
23552   // optimizations.  Note that the operands are ordered the opposite of SELECT
23553   // operands.
23554   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23555     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23556       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23557       // larger than FalseC (the false value).
23558       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23559         CC = X86::GetOppositeBranchCondition(CC);
23560         std::swap(TrueC, FalseC);
23561         std::swap(TrueOp, FalseOp);
23562       }
23563
23564       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23565       // This is efficient for any integer data type (including i8/i16) and
23566       // shift amount.
23567       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23568         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23569                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23570
23571         // Zero extend the condition if needed.
23572         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23573
23574         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23575         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23576                            DAG.getConstant(ShAmt, DL, MVT::i8));
23577         if (N->getNumValues() == 2)  // Dead flag value?
23578           return DCI.CombineTo(N, Cond, SDValue());
23579         return Cond;
23580       }
23581
23582       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23583       // for any integer data type, including i8/i16.
23584       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23585         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23586                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23587
23588         // Zero extend the condition if needed.
23589         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23590                            FalseC->getValueType(0), Cond);
23591         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23592                            SDValue(FalseC, 0));
23593
23594         if (N->getNumValues() == 2)  // Dead flag value?
23595           return DCI.CombineTo(N, Cond, SDValue());
23596         return Cond;
23597       }
23598
23599       // Optimize cases that will turn into an LEA instruction.  This requires
23600       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23601       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23602         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23603         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23604
23605         bool isFastMultiplier = false;
23606         if (Diff < 10) {
23607           switch ((unsigned char)Diff) {
23608           default: break;
23609           case 1:  // result = add base, cond
23610           case 2:  // result = lea base(    , cond*2)
23611           case 3:  // result = lea base(cond, cond*2)
23612           case 4:  // result = lea base(    , cond*4)
23613           case 5:  // result = lea base(cond, cond*4)
23614           case 8:  // result = lea base(    , cond*8)
23615           case 9:  // result = lea base(cond, cond*8)
23616             isFastMultiplier = true;
23617             break;
23618           }
23619         }
23620
23621         if (isFastMultiplier) {
23622           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23623           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23624                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23625           // Zero extend the condition if needed.
23626           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23627                              Cond);
23628           // Scale the condition by the difference.
23629           if (Diff != 1)
23630             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23631                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23632
23633           // Add the base if non-zero.
23634           if (FalseC->getAPIntValue() != 0)
23635             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23636                                SDValue(FalseC, 0));
23637           if (N->getNumValues() == 2)  // Dead flag value?
23638             return DCI.CombineTo(N, Cond, SDValue());
23639           return Cond;
23640         }
23641       }
23642     }
23643   }
23644
23645   // Handle these cases:
23646   //   (select (x != c), e, c) -> select (x != c), e, x),
23647   //   (select (x == c), c, e) -> select (x == c), x, e)
23648   // where the c is an integer constant, and the "select" is the combination
23649   // of CMOV and CMP.
23650   //
23651   // The rationale for this change is that the conditional-move from a constant
23652   // needs two instructions, however, conditional-move from a register needs
23653   // only one instruction.
23654   //
23655   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23656   //  some instruction-combining opportunities. This opt needs to be
23657   //  postponed as late as possible.
23658   //
23659   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23660     // the DCI.xxxx conditions are provided to postpone the optimization as
23661     // late as possible.
23662
23663     ConstantSDNode *CmpAgainst = nullptr;
23664     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23665         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23666         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23667
23668       if (CC == X86::COND_NE &&
23669           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23670         CC = X86::GetOppositeBranchCondition(CC);
23671         std::swap(TrueOp, FalseOp);
23672       }
23673
23674       if (CC == X86::COND_E &&
23675           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23676         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23677                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23678         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23679       }
23680     }
23681   }
23682
23683   // Fold and/or of setcc's to double CMOV:
23684   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23685   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23686   //
23687   // This combine lets us generate:
23688   //   cmovcc1 (jcc1 if we don't have CMOV)
23689   //   cmovcc2 (same)
23690   // instead of:
23691   //   setcc1
23692   //   setcc2
23693   //   and/or
23694   //   cmovne (jne if we don't have CMOV)
23695   // When we can't use the CMOV instruction, it might increase branch
23696   // mispredicts.
23697   // When we can use CMOV, or when there is no mispredict, this improves
23698   // throughput and reduces register pressure.
23699   //
23700   if (CC == X86::COND_NE) {
23701     SDValue Flags;
23702     X86::CondCode CC0, CC1;
23703     bool isAndSetCC;
23704     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23705       if (isAndSetCC) {
23706         std::swap(FalseOp, TrueOp);
23707         CC0 = X86::GetOppositeBranchCondition(CC0);
23708         CC1 = X86::GetOppositeBranchCondition(CC1);
23709       }
23710
23711       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23712         Flags};
23713       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23714       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23715       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23716       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23717       return CMOV;
23718     }
23719   }
23720
23721   return SDValue();
23722 }
23723
23724 /// PerformMulCombine - Optimize a single multiply with constant into two
23725 /// in order to implement it with two cheaper instructions, e.g.
23726 /// LEA + SHL, LEA + LEA.
23727 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23728                                  TargetLowering::DAGCombinerInfo &DCI) {
23729   // An imul is usually smaller than the alternative sequence.
23730   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23731     return SDValue();
23732
23733   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23734     return SDValue();
23735
23736   EVT VT = N->getValueType(0);
23737   if (VT != MVT::i64 && VT != MVT::i32)
23738     return SDValue();
23739
23740   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23741   if (!C)
23742     return SDValue();
23743   uint64_t MulAmt = C->getZExtValue();
23744   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23745     return SDValue();
23746
23747   uint64_t MulAmt1 = 0;
23748   uint64_t MulAmt2 = 0;
23749   if ((MulAmt % 9) == 0) {
23750     MulAmt1 = 9;
23751     MulAmt2 = MulAmt / 9;
23752   } else if ((MulAmt % 5) == 0) {
23753     MulAmt1 = 5;
23754     MulAmt2 = MulAmt / 5;
23755   } else if ((MulAmt % 3) == 0) {
23756     MulAmt1 = 3;
23757     MulAmt2 = MulAmt / 3;
23758   }
23759   if (MulAmt2 &&
23760       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23761     SDLoc DL(N);
23762
23763     if (isPowerOf2_64(MulAmt2) &&
23764         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23765       // If second multiplifer is pow2, issue it first. We want the multiply by
23766       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23767       // is an add.
23768       std::swap(MulAmt1, MulAmt2);
23769
23770     SDValue NewMul;
23771     if (isPowerOf2_64(MulAmt1))
23772       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23773                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23774     else
23775       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23776                            DAG.getConstant(MulAmt1, DL, VT));
23777
23778     if (isPowerOf2_64(MulAmt2))
23779       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23780                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23781     else
23782       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23783                            DAG.getConstant(MulAmt2, DL, VT));
23784
23785     // Do not add new nodes to DAG combiner worklist.
23786     DCI.CombineTo(N, NewMul, false);
23787   }
23788   return SDValue();
23789 }
23790
23791 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23792   SDValue N0 = N->getOperand(0);
23793   SDValue N1 = N->getOperand(1);
23794   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23795   EVT VT = N0.getValueType();
23796
23797   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23798   // since the result of setcc_c is all zero's or all ones.
23799   if (VT.isInteger() && !VT.isVector() &&
23800       N1C && N0.getOpcode() == ISD::AND &&
23801       N0.getOperand(1).getOpcode() == ISD::Constant) {
23802     SDValue N00 = N0.getOperand(0);
23803     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23804     APInt ShAmt = N1C->getAPIntValue();
23805     Mask = Mask.shl(ShAmt);
23806     bool MaskOK = false;
23807     // We can handle cases concerning bit-widening nodes containing setcc_c if
23808     // we carefully interrogate the mask to make sure we are semantics
23809     // preserving.
23810     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23811     // of the underlying setcc_c operation if the setcc_c was zero extended.
23812     // Consider the following example:
23813     //   zext(setcc_c)                 -> i32 0x0000FFFF
23814     //   c1                            -> i32 0x0000FFFF
23815     //   c2                            -> i32 0x00000001
23816     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23817     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23818     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23819       MaskOK = true;
23820     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23821                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23822       MaskOK = true;
23823     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23824                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23825                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23826       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23827     }
23828     if (MaskOK && Mask != 0) {
23829       SDLoc DL(N);
23830       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23831     }
23832   }
23833
23834   // Hardware support for vector shifts is sparse which makes us scalarize the
23835   // vector operations in many cases. Also, on sandybridge ADD is faster than
23836   // shl.
23837   // (shl V, 1) -> add V,V
23838   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23839     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23840       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23841       // We shift all of the values by one. In many cases we do not have
23842       // hardware support for this operation. This is better expressed as an ADD
23843       // of two values.
23844       if (N1SplatC->getAPIntValue() == 1)
23845         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23846     }
23847
23848   return SDValue();
23849 }
23850
23851 /// \brief Returns a vector of 0s if the node in input is a vector logical
23852 /// shift by a constant amount which is known to be bigger than or equal
23853 /// to the vector element size in bits.
23854 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23855                                       const X86Subtarget *Subtarget) {
23856   EVT VT = N->getValueType(0);
23857
23858   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23859       (!Subtarget->hasInt256() ||
23860        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23861     return SDValue();
23862
23863   SDValue Amt = N->getOperand(1);
23864   SDLoc DL(N);
23865   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23866     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23867       APInt ShiftAmt = AmtSplat->getAPIntValue();
23868       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23869
23870       // SSE2/AVX2 logical shifts always return a vector of 0s
23871       // if the shift amount is bigger than or equal to
23872       // the element size. The constant shift amount will be
23873       // encoded as a 8-bit immediate.
23874       if (ShiftAmt.trunc(8).uge(MaxAmount))
23875         return getZeroVector(VT, Subtarget, DAG, DL);
23876     }
23877
23878   return SDValue();
23879 }
23880
23881 /// PerformShiftCombine - Combine shifts.
23882 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23883                                    TargetLowering::DAGCombinerInfo &DCI,
23884                                    const X86Subtarget *Subtarget) {
23885   if (N->getOpcode() == ISD::SHL)
23886     if (SDValue V = PerformSHLCombine(N, DAG))
23887       return V;
23888
23889   // Try to fold this logical shift into a zero vector.
23890   if (N->getOpcode() != ISD::SRA)
23891     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23892       return V;
23893
23894   return SDValue();
23895 }
23896
23897 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23898 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23899 // and friends.  Likewise for OR -> CMPNEQSS.
23900 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23901                             TargetLowering::DAGCombinerInfo &DCI,
23902                             const X86Subtarget *Subtarget) {
23903   unsigned opcode;
23904
23905   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23906   // we're requiring SSE2 for both.
23907   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23908     SDValue N0 = N->getOperand(0);
23909     SDValue N1 = N->getOperand(1);
23910     SDValue CMP0 = N0->getOperand(1);
23911     SDValue CMP1 = N1->getOperand(1);
23912     SDLoc DL(N);
23913
23914     // The SETCCs should both refer to the same CMP.
23915     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23916       return SDValue();
23917
23918     SDValue CMP00 = CMP0->getOperand(0);
23919     SDValue CMP01 = CMP0->getOperand(1);
23920     EVT     VT    = CMP00.getValueType();
23921
23922     if (VT == MVT::f32 || VT == MVT::f64) {
23923       bool ExpectingFlags = false;
23924       // Check for any users that want flags:
23925       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23926            !ExpectingFlags && UI != UE; ++UI)
23927         switch (UI->getOpcode()) {
23928         default:
23929         case ISD::BR_CC:
23930         case ISD::BRCOND:
23931         case ISD::SELECT:
23932           ExpectingFlags = true;
23933           break;
23934         case ISD::CopyToReg:
23935         case ISD::SIGN_EXTEND:
23936         case ISD::ZERO_EXTEND:
23937         case ISD::ANY_EXTEND:
23938           break;
23939         }
23940
23941       if (!ExpectingFlags) {
23942         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23943         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23944
23945         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23946           X86::CondCode tmp = cc0;
23947           cc0 = cc1;
23948           cc1 = tmp;
23949         }
23950
23951         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23952             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23953           // FIXME: need symbolic constants for these magic numbers.
23954           // See X86ATTInstPrinter.cpp:printSSECC().
23955           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23956           if (Subtarget->hasAVX512()) {
23957             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23958                                          CMP01,
23959                                          DAG.getConstant(x86cc, DL, MVT::i8));
23960             if (N->getValueType(0) != MVT::i1)
23961               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23962                                  FSetCC);
23963             return FSetCC;
23964           }
23965           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23966                                               CMP00.getValueType(), CMP00, CMP01,
23967                                               DAG.getConstant(x86cc, DL,
23968                                                               MVT::i8));
23969
23970           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23971           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23972
23973           if (is64BitFP && !Subtarget->is64Bit()) {
23974             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23975             // 64-bit integer, since that's not a legal type. Since
23976             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23977             // bits, but can do this little dance to extract the lowest 32 bits
23978             // and work with those going forward.
23979             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23980                                            OnesOrZeroesF);
23981             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23982             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23983                                         Vector32, DAG.getIntPtrConstant(0, DL));
23984             IntVT = MVT::i32;
23985           }
23986
23987           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23988           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23989                                       DAG.getConstant(1, DL, IntVT));
23990           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23991                                               ANDed);
23992           return OneBitOfTruth;
23993         }
23994       }
23995     }
23996   }
23997   return SDValue();
23998 }
23999
24000 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24001 /// so it can be folded inside ANDNP.
24002 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24003   EVT VT = N->getValueType(0);
24004
24005   // Match direct AllOnes for 128 and 256-bit vectors
24006   if (ISD::isBuildVectorAllOnes(N))
24007     return true;
24008
24009   // Look through a bit convert.
24010   if (N->getOpcode() == ISD::BITCAST)
24011     N = N->getOperand(0).getNode();
24012
24013   // Sometimes the operand may come from a insert_subvector building a 256-bit
24014   // allones vector
24015   if (VT.is256BitVector() &&
24016       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24017     SDValue V1 = N->getOperand(0);
24018     SDValue V2 = N->getOperand(1);
24019
24020     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24021         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24022         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24023         ISD::isBuildVectorAllOnes(V2.getNode()))
24024       return true;
24025   }
24026
24027   return false;
24028 }
24029
24030 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24031 // register. In most cases we actually compare or select YMM-sized registers
24032 // and mixing the two types creates horrible code. This method optimizes
24033 // some of the transition sequences.
24034 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24035                                  TargetLowering::DAGCombinerInfo &DCI,
24036                                  const X86Subtarget *Subtarget) {
24037   EVT VT = N->getValueType(0);
24038   if (!VT.is256BitVector())
24039     return SDValue();
24040
24041   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24042           N->getOpcode() == ISD::ZERO_EXTEND ||
24043           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24044
24045   SDValue Narrow = N->getOperand(0);
24046   EVT NarrowVT = Narrow->getValueType(0);
24047   if (!NarrowVT.is128BitVector())
24048     return SDValue();
24049
24050   if (Narrow->getOpcode() != ISD::XOR &&
24051       Narrow->getOpcode() != ISD::AND &&
24052       Narrow->getOpcode() != ISD::OR)
24053     return SDValue();
24054
24055   SDValue N0  = Narrow->getOperand(0);
24056   SDValue N1  = Narrow->getOperand(1);
24057   SDLoc DL(Narrow);
24058
24059   // The Left side has to be a trunc.
24060   if (N0.getOpcode() != ISD::TRUNCATE)
24061     return SDValue();
24062
24063   // The type of the truncated inputs.
24064   EVT WideVT = N0->getOperand(0)->getValueType(0);
24065   if (WideVT != VT)
24066     return SDValue();
24067
24068   // The right side has to be a 'trunc' or a constant vector.
24069   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24070   ConstantSDNode *RHSConstSplat = nullptr;
24071   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24072     RHSConstSplat = RHSBV->getConstantSplatNode();
24073   if (!RHSTrunc && !RHSConstSplat)
24074     return SDValue();
24075
24076   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24077
24078   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24079     return SDValue();
24080
24081   // Set N0 and N1 to hold the inputs to the new wide operation.
24082   N0 = N0->getOperand(0);
24083   if (RHSConstSplat) {
24084     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24085                      SDValue(RHSConstSplat, 0));
24086     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24087     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24088   } else if (RHSTrunc) {
24089     N1 = N1->getOperand(0);
24090   }
24091
24092   // Generate the wide operation.
24093   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24094   unsigned Opcode = N->getOpcode();
24095   switch (Opcode) {
24096   case ISD::ANY_EXTEND:
24097     return Op;
24098   case ISD::ZERO_EXTEND: {
24099     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24100     APInt Mask = APInt::getAllOnesValue(InBits);
24101     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24102     return DAG.getNode(ISD::AND, DL, VT,
24103                        Op, DAG.getConstant(Mask, DL, VT));
24104   }
24105   case ISD::SIGN_EXTEND:
24106     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24107                        Op, DAG.getValueType(NarrowVT));
24108   default:
24109     llvm_unreachable("Unexpected opcode");
24110   }
24111 }
24112
24113 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24114                                  TargetLowering::DAGCombinerInfo &DCI,
24115                                  const X86Subtarget *Subtarget) {
24116   SDValue N0 = N->getOperand(0);
24117   SDValue N1 = N->getOperand(1);
24118   SDLoc DL(N);
24119
24120   // A vector zext_in_reg may be represented as a shuffle,
24121   // feeding into a bitcast (this represents anyext) feeding into
24122   // an and with a mask.
24123   // We'd like to try to combine that into a shuffle with zero
24124   // plus a bitcast, removing the and.
24125   if (N0.getOpcode() != ISD::BITCAST ||
24126       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24127     return SDValue();
24128
24129   // The other side of the AND should be a splat of 2^C, where C
24130   // is the number of bits in the source type.
24131   if (N1.getOpcode() == ISD::BITCAST)
24132     N1 = N1.getOperand(0);
24133   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24134     return SDValue();
24135   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24136
24137   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24138   EVT SrcType = Shuffle->getValueType(0);
24139
24140   // We expect a single-source shuffle
24141   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24142     return SDValue();
24143
24144   unsigned SrcSize = SrcType.getScalarSizeInBits();
24145
24146   APInt SplatValue, SplatUndef;
24147   unsigned SplatBitSize;
24148   bool HasAnyUndefs;
24149   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24150                                 SplatBitSize, HasAnyUndefs))
24151     return SDValue();
24152
24153   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24154   // Make sure the splat matches the mask we expect
24155   if (SplatBitSize > ResSize ||
24156       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24157     return SDValue();
24158
24159   // Make sure the input and output size make sense
24160   if (SrcSize >= ResSize || ResSize % SrcSize)
24161     return SDValue();
24162
24163   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24164   // The number of u's between each two values depends on the ratio between
24165   // the source and dest type.
24166   unsigned ZextRatio = ResSize / SrcSize;
24167   bool IsZext = true;
24168   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24169     if (i % ZextRatio) {
24170       if (Shuffle->getMaskElt(i) > 0) {
24171         // Expected undef
24172         IsZext = false;
24173         break;
24174       }
24175     } else {
24176       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24177         // Expected element number
24178         IsZext = false;
24179         break;
24180       }
24181     }
24182   }
24183
24184   if (!IsZext)
24185     return SDValue();
24186
24187   // Ok, perform the transformation - replace the shuffle with
24188   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24189   // (instead of undef) where the k elements come from the zero vector.
24190   SmallVector<int, 8> Mask;
24191   unsigned NumElems = SrcType.getVectorNumElements();
24192   for (unsigned i = 0; i < NumElems; ++i)
24193     if (i % ZextRatio)
24194       Mask.push_back(NumElems);
24195     else
24196       Mask.push_back(i / ZextRatio);
24197
24198   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24199     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24200   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24201 }
24202
24203 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24204                                  TargetLowering::DAGCombinerInfo &DCI,
24205                                  const X86Subtarget *Subtarget) {
24206   if (DCI.isBeforeLegalizeOps())
24207     return SDValue();
24208
24209   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24210     return Zext;
24211
24212   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24213     return R;
24214
24215   EVT VT = N->getValueType(0);
24216   SDValue N0 = N->getOperand(0);
24217   SDValue N1 = N->getOperand(1);
24218   SDLoc DL(N);
24219
24220   // Create BEXTR instructions
24221   // BEXTR is ((X >> imm) & (2**size-1))
24222   if (VT == MVT::i32 || VT == MVT::i64) {
24223     // Check for BEXTR.
24224     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24225         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24226       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24227       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24228       if (MaskNode && ShiftNode) {
24229         uint64_t Mask = MaskNode->getZExtValue();
24230         uint64_t Shift = ShiftNode->getZExtValue();
24231         if (isMask_64(Mask)) {
24232           uint64_t MaskSize = countPopulation(Mask);
24233           if (Shift + MaskSize <= VT.getSizeInBits())
24234             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24235                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24236                                                VT));
24237         }
24238       }
24239     } // BEXTR
24240
24241     return SDValue();
24242   }
24243
24244   // Want to form ANDNP nodes:
24245   // 1) In the hopes of then easily combining them with OR and AND nodes
24246   //    to form PBLEND/PSIGN.
24247   // 2) To match ANDN packed intrinsics
24248   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24249     return SDValue();
24250
24251   // Check LHS for vnot
24252   if (N0.getOpcode() == ISD::XOR &&
24253       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24254       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24255     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24256
24257   // Check RHS for vnot
24258   if (N1.getOpcode() == ISD::XOR &&
24259       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24260       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24261     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24262
24263   return SDValue();
24264 }
24265
24266 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24267                                 TargetLowering::DAGCombinerInfo &DCI,
24268                                 const X86Subtarget *Subtarget) {
24269   if (DCI.isBeforeLegalizeOps())
24270     return SDValue();
24271
24272   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24273     return R;
24274
24275   SDValue N0 = N->getOperand(0);
24276   SDValue N1 = N->getOperand(1);
24277   EVT VT = N->getValueType(0);
24278
24279   // look for psign/blend
24280   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24281     if (!Subtarget->hasSSSE3() ||
24282         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24283       return SDValue();
24284
24285     // Canonicalize pandn to RHS
24286     if (N0.getOpcode() == X86ISD::ANDNP)
24287       std::swap(N0, N1);
24288     // or (and (m, y), (pandn m, x))
24289     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24290       SDValue Mask = N1.getOperand(0);
24291       SDValue X    = N1.getOperand(1);
24292       SDValue Y;
24293       if (N0.getOperand(0) == Mask)
24294         Y = N0.getOperand(1);
24295       if (N0.getOperand(1) == Mask)
24296         Y = N0.getOperand(0);
24297
24298       // Check to see if the mask appeared in both the AND and ANDNP and
24299       if (!Y.getNode())
24300         return SDValue();
24301
24302       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24303       // Look through mask bitcast.
24304       if (Mask.getOpcode() == ISD::BITCAST)
24305         Mask = Mask.getOperand(0);
24306       if (X.getOpcode() == ISD::BITCAST)
24307         X = X.getOperand(0);
24308       if (Y.getOpcode() == ISD::BITCAST)
24309         Y = Y.getOperand(0);
24310
24311       EVT MaskVT = Mask.getValueType();
24312
24313       // Validate that the Mask operand is a vector sra node.
24314       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24315       // there is no psrai.b
24316       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24317       unsigned SraAmt = ~0;
24318       if (Mask.getOpcode() == ISD::SRA) {
24319         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24320           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24321             SraAmt = AmtConst->getZExtValue();
24322       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24323         SDValue SraC = Mask.getOperand(1);
24324         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24325       }
24326       if ((SraAmt + 1) != EltBits)
24327         return SDValue();
24328
24329       SDLoc DL(N);
24330
24331       // Now we know we at least have a plendvb with the mask val.  See if
24332       // we can form a psignb/w/d.
24333       // psign = x.type == y.type == mask.type && y = sub(0, x);
24334       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24335           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24336           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24337         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24338                "Unsupported VT for PSIGN");
24339         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24340         return DAG.getBitcast(VT, Mask);
24341       }
24342       // PBLENDVB only available on SSE 4.1
24343       if (!Subtarget->hasSSE41())
24344         return SDValue();
24345
24346       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24347
24348       X = DAG.getBitcast(BlendVT, X);
24349       Y = DAG.getBitcast(BlendVT, Y);
24350       Mask = DAG.getBitcast(BlendVT, Mask);
24351       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24352       return DAG.getBitcast(VT, Mask);
24353     }
24354   }
24355
24356   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24357     return SDValue();
24358
24359   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24360   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24361
24362   // SHLD/SHRD instructions have lower register pressure, but on some
24363   // platforms they have higher latency than the equivalent
24364   // series of shifts/or that would otherwise be generated.
24365   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24366   // have higher latencies and we are not optimizing for size.
24367   if (!OptForSize && Subtarget->isSHLDSlow())
24368     return SDValue();
24369
24370   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24371     std::swap(N0, N1);
24372   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24373     return SDValue();
24374   if (!N0.hasOneUse() || !N1.hasOneUse())
24375     return SDValue();
24376
24377   SDValue ShAmt0 = N0.getOperand(1);
24378   if (ShAmt0.getValueType() != MVT::i8)
24379     return SDValue();
24380   SDValue ShAmt1 = N1.getOperand(1);
24381   if (ShAmt1.getValueType() != MVT::i8)
24382     return SDValue();
24383   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24384     ShAmt0 = ShAmt0.getOperand(0);
24385   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24386     ShAmt1 = ShAmt1.getOperand(0);
24387
24388   SDLoc DL(N);
24389   unsigned Opc = X86ISD::SHLD;
24390   SDValue Op0 = N0.getOperand(0);
24391   SDValue Op1 = N1.getOperand(0);
24392   if (ShAmt0.getOpcode() == ISD::SUB) {
24393     Opc = X86ISD::SHRD;
24394     std::swap(Op0, Op1);
24395     std::swap(ShAmt0, ShAmt1);
24396   }
24397
24398   unsigned Bits = VT.getSizeInBits();
24399   if (ShAmt1.getOpcode() == ISD::SUB) {
24400     SDValue Sum = ShAmt1.getOperand(0);
24401     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24402       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24403       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24404         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24405       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24406         return DAG.getNode(Opc, DL, VT,
24407                            Op0, Op1,
24408                            DAG.getNode(ISD::TRUNCATE, DL,
24409                                        MVT::i8, ShAmt0));
24410     }
24411   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24412     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24413     if (ShAmt0C &&
24414         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24415       return DAG.getNode(Opc, DL, VT,
24416                          N0.getOperand(0), N1.getOperand(0),
24417                          DAG.getNode(ISD::TRUNCATE, DL,
24418                                        MVT::i8, ShAmt0));
24419   }
24420
24421   return SDValue();
24422 }
24423
24424 // Generate NEG and CMOV for integer abs.
24425 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24426   EVT VT = N->getValueType(0);
24427
24428   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24429   // 8-bit integer abs to NEG and CMOV.
24430   if (VT.isInteger() && VT.getSizeInBits() == 8)
24431     return SDValue();
24432
24433   SDValue N0 = N->getOperand(0);
24434   SDValue N1 = N->getOperand(1);
24435   SDLoc DL(N);
24436
24437   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24438   // and change it to SUB and CMOV.
24439   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24440       N0.getOpcode() == ISD::ADD &&
24441       N0.getOperand(1) == N1 &&
24442       N1.getOpcode() == ISD::SRA &&
24443       N1.getOperand(0) == N0.getOperand(0))
24444     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24445       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24446         // Generate SUB & CMOV.
24447         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24448                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24449
24450         SDValue Ops[] = { N0.getOperand(0), Neg,
24451                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24452                           SDValue(Neg.getNode(), 1) };
24453         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24454       }
24455   return SDValue();
24456 }
24457
24458 // Try to turn tests against the signbit in the form of:
24459 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24460 // into:
24461 //   SETGT(X, -1)
24462 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24463   // This is only worth doing if the output type is i8.
24464   if (N->getValueType(0) != MVT::i8)
24465     return SDValue();
24466
24467   SDValue N0 = N->getOperand(0);
24468   SDValue N1 = N->getOperand(1);
24469
24470   // We should be performing an xor against a truncated shift.
24471   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24472     return SDValue();
24473
24474   // Make sure we are performing an xor against one.
24475   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24476     return SDValue();
24477
24478   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24479   SDValue Shift = N0.getOperand(0);
24480   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24481     return SDValue();
24482
24483   // Make sure we are truncating from one of i16, i32 or i64.
24484   EVT ShiftTy = Shift.getValueType();
24485   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24486     return SDValue();
24487
24488   // Make sure the shift amount extracts the sign bit.
24489   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24490       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24491     return SDValue();
24492
24493   // Create a greater-than comparison against -1.
24494   // N.B. Using SETGE against 0 works but we want a canonical looking
24495   // comparison, using SETGT matches up with what TranslateX86CC.
24496   SDLoc DL(N);
24497   SDValue ShiftOp = Shift.getOperand(0);
24498   EVT ShiftOpTy = ShiftOp.getValueType();
24499   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24500                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24501   return Cond;
24502 }
24503
24504 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24505                                  TargetLowering::DAGCombinerInfo &DCI,
24506                                  const X86Subtarget *Subtarget) {
24507   if (DCI.isBeforeLegalizeOps())
24508     return SDValue();
24509
24510   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24511     return RV;
24512
24513   if (Subtarget->hasCMov())
24514     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24515       return RV;
24516
24517   return SDValue();
24518 }
24519
24520 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24521 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24522                                   TargetLowering::DAGCombinerInfo &DCI,
24523                                   const X86Subtarget *Subtarget) {
24524   LoadSDNode *Ld = cast<LoadSDNode>(N);
24525   EVT RegVT = Ld->getValueType(0);
24526   EVT MemVT = Ld->getMemoryVT();
24527   SDLoc dl(Ld);
24528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24529
24530   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24531   // into two 16-byte operations.
24532   ISD::LoadExtType Ext = Ld->getExtensionType();
24533   bool Fast;
24534   unsigned AddressSpace = Ld->getAddressSpace();
24535   unsigned Alignment = Ld->getAlignment();
24536   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24537       Ext == ISD::NON_EXTLOAD &&
24538       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24539                              AddressSpace, Alignment, &Fast) && !Fast) {
24540     unsigned NumElems = RegVT.getVectorNumElements();
24541     if (NumElems < 2)
24542       return SDValue();
24543
24544     SDValue Ptr = Ld->getBasePtr();
24545     SDValue Increment =
24546         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24547
24548     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24549                                   NumElems/2);
24550     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24551                                 Ld->getPointerInfo(), Ld->isVolatile(),
24552                                 Ld->isNonTemporal(), Ld->isInvariant(),
24553                                 Alignment);
24554     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24555     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24556                                 Ld->getPointerInfo(), Ld->isVolatile(),
24557                                 Ld->isNonTemporal(), Ld->isInvariant(),
24558                                 std::min(16U, Alignment));
24559     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24560                              Load1.getValue(1),
24561                              Load2.getValue(1));
24562
24563     SDValue NewVec = DAG.getUNDEF(RegVT);
24564     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24565     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24566     return DCI.CombineTo(N, NewVec, TF, true);
24567   }
24568
24569   return SDValue();
24570 }
24571
24572 /// PerformMLOADCombine - Resolve extending loads
24573 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24574                                    TargetLowering::DAGCombinerInfo &DCI,
24575                                    const X86Subtarget *Subtarget) {
24576   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24577   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24578     return SDValue();
24579
24580   EVT VT = Mld->getValueType(0);
24581   unsigned NumElems = VT.getVectorNumElements();
24582   EVT LdVT = Mld->getMemoryVT();
24583   SDLoc dl(Mld);
24584
24585   assert(LdVT != VT && "Cannot extend to the same type");
24586   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24587   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24588   // From, To sizes and ElemCount must be pow of two
24589   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24590     "Unexpected size for extending masked load");
24591
24592   unsigned SizeRatio  = ToSz / FromSz;
24593   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24594
24595   // Create a type on which we perform the shuffle
24596   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24597           LdVT.getScalarType(), NumElems*SizeRatio);
24598   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24599
24600   // Convert Src0 value
24601   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24602   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24603     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24604     for (unsigned i = 0; i != NumElems; ++i)
24605       ShuffleVec[i] = i * SizeRatio;
24606
24607     // Can't shuffle using an illegal type.
24608     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24609             && "WideVecVT should be legal");
24610     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24611                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24612   }
24613   // Prepare the new mask
24614   SDValue NewMask;
24615   SDValue Mask = Mld->getMask();
24616   if (Mask.getValueType() == VT) {
24617     // Mask and original value have the same type
24618     NewMask = DAG.getBitcast(WideVecVT, Mask);
24619     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24620     for (unsigned i = 0; i != NumElems; ++i)
24621       ShuffleVec[i] = i * SizeRatio;
24622     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24623       ShuffleVec[i] = NumElems*SizeRatio;
24624     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24625                                    DAG.getConstant(0, dl, WideVecVT),
24626                                    &ShuffleVec[0]);
24627   }
24628   else {
24629     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24630     unsigned WidenNumElts = NumElems*SizeRatio;
24631     unsigned MaskNumElts = VT.getVectorNumElements();
24632     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24633                                      WidenNumElts);
24634
24635     unsigned NumConcat = WidenNumElts / MaskNumElts;
24636     SmallVector<SDValue, 16> Ops(NumConcat);
24637     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24638     Ops[0] = Mask;
24639     for (unsigned i = 1; i != NumConcat; ++i)
24640       Ops[i] = ZeroVal;
24641
24642     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24643   }
24644
24645   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24646                                      Mld->getBasePtr(), NewMask, WideSrc0,
24647                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24648                                      ISD::NON_EXTLOAD);
24649   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24650   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24651
24652 }
24653 /// PerformMSTORECombine - Resolve truncating stores
24654 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24655                                     const X86Subtarget *Subtarget) {
24656   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24657   if (!Mst->isTruncatingStore())
24658     return SDValue();
24659
24660   EVT VT = Mst->getValue().getValueType();
24661   unsigned NumElems = VT.getVectorNumElements();
24662   EVT StVT = Mst->getMemoryVT();
24663   SDLoc dl(Mst);
24664
24665   assert(StVT != VT && "Cannot truncate to the same type");
24666   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24667   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24668
24669   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24670
24671   // The truncating store is legal in some cases. For example
24672   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24673   // are designated for truncate store.
24674   // In this case we don't need any further transformations.
24675   if (TLI.isTruncStoreLegal(VT, StVT))
24676     return SDValue();
24677
24678   // From, To sizes and ElemCount must be pow of two
24679   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24680     "Unexpected size for truncating masked store");
24681   // We are going to use the original vector elt for storing.
24682   // Accumulated smaller vector elements must be a multiple of the store size.
24683   assert (((NumElems * FromSz) % ToSz) == 0 &&
24684           "Unexpected ratio for truncating masked store");
24685
24686   unsigned SizeRatio  = FromSz / ToSz;
24687   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24688
24689   // Create a type on which we perform the shuffle
24690   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24691           StVT.getScalarType(), NumElems*SizeRatio);
24692
24693   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24694
24695   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24696   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24697   for (unsigned i = 0; i != NumElems; ++i)
24698     ShuffleVec[i] = i * SizeRatio;
24699
24700   // Can't shuffle using an illegal type.
24701   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24702           && "WideVecVT should be legal");
24703
24704   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24705                                         DAG.getUNDEF(WideVecVT),
24706                                         &ShuffleVec[0]);
24707
24708   SDValue NewMask;
24709   SDValue Mask = Mst->getMask();
24710   if (Mask.getValueType() == VT) {
24711     // Mask and original value have the same type
24712     NewMask = DAG.getBitcast(WideVecVT, Mask);
24713     for (unsigned i = 0; i != NumElems; ++i)
24714       ShuffleVec[i] = i * SizeRatio;
24715     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24716       ShuffleVec[i] = NumElems*SizeRatio;
24717     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24718                                    DAG.getConstant(0, dl, WideVecVT),
24719                                    &ShuffleVec[0]);
24720   }
24721   else {
24722     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24723     unsigned WidenNumElts = NumElems*SizeRatio;
24724     unsigned MaskNumElts = VT.getVectorNumElements();
24725     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24726                                      WidenNumElts);
24727
24728     unsigned NumConcat = WidenNumElts / MaskNumElts;
24729     SmallVector<SDValue, 16> Ops(NumConcat);
24730     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24731     Ops[0] = Mask;
24732     for (unsigned i = 1; i != NumConcat; ++i)
24733       Ops[i] = ZeroVal;
24734
24735     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24736   }
24737
24738   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24739                             NewMask, StVT, Mst->getMemOperand(), false);
24740 }
24741 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24742 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24743                                    const X86Subtarget *Subtarget) {
24744   StoreSDNode *St = cast<StoreSDNode>(N);
24745   EVT VT = St->getValue().getValueType();
24746   EVT StVT = St->getMemoryVT();
24747   SDLoc dl(St);
24748   SDValue StoredVal = St->getOperand(1);
24749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24750
24751   // If we are saving a concatenation of two XMM registers and 32-byte stores
24752   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24753   bool Fast;
24754   unsigned AddressSpace = St->getAddressSpace();
24755   unsigned Alignment = St->getAlignment();
24756   if (VT.is256BitVector() && StVT == VT &&
24757       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24758                              AddressSpace, Alignment, &Fast) && !Fast) {
24759     unsigned NumElems = VT.getVectorNumElements();
24760     if (NumElems < 2)
24761       return SDValue();
24762
24763     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24764     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24765
24766     SDValue Stride =
24767         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24768     SDValue Ptr0 = St->getBasePtr();
24769     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24770
24771     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24772                                 St->getPointerInfo(), St->isVolatile(),
24773                                 St->isNonTemporal(), Alignment);
24774     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24775                                 St->getPointerInfo(), St->isVolatile(),
24776                                 St->isNonTemporal(),
24777                                 std::min(16U, Alignment));
24778     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24779   }
24780
24781   // Optimize trunc store (of multiple scalars) to shuffle and store.
24782   // First, pack all of the elements in one place. Next, store to memory
24783   // in fewer chunks.
24784   if (St->isTruncatingStore() && VT.isVector()) {
24785     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24786     unsigned NumElems = VT.getVectorNumElements();
24787     assert(StVT != VT && "Cannot truncate to the same type");
24788     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24789     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24790
24791     // The truncating store is legal in some cases. For example
24792     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24793     // are designated for truncate store.
24794     // In this case we don't need any further transformations.
24795     if (TLI.isTruncStoreLegal(VT, StVT))
24796       return SDValue();
24797
24798     // From, To sizes and ElemCount must be pow of two
24799     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24800     // We are going to use the original vector elt for storing.
24801     // Accumulated smaller vector elements must be a multiple of the store size.
24802     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24803
24804     unsigned SizeRatio  = FromSz / ToSz;
24805
24806     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24807
24808     // Create a type on which we perform the shuffle
24809     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24810             StVT.getScalarType(), NumElems*SizeRatio);
24811
24812     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24813
24814     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24815     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24816     for (unsigned i = 0; i != NumElems; ++i)
24817       ShuffleVec[i] = i * SizeRatio;
24818
24819     // Can't shuffle using an illegal type.
24820     if (!TLI.isTypeLegal(WideVecVT))
24821       return SDValue();
24822
24823     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24824                                          DAG.getUNDEF(WideVecVT),
24825                                          &ShuffleVec[0]);
24826     // At this point all of the data is stored at the bottom of the
24827     // register. We now need to save it to mem.
24828
24829     // Find the largest store unit
24830     MVT StoreType = MVT::i8;
24831     for (MVT Tp : MVT::integer_valuetypes()) {
24832       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24833         StoreType = Tp;
24834     }
24835
24836     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24837     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24838         (64 <= NumElems * ToSz))
24839       StoreType = MVT::f64;
24840
24841     // Bitcast the original vector into a vector of store-size units
24842     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24843             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24844     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24845     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24846     SmallVector<SDValue, 8> Chains;
24847     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24848                                         TLI.getPointerTy(DAG.getDataLayout()));
24849     SDValue Ptr = St->getBasePtr();
24850
24851     // Perform one or more big stores into memory.
24852     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24853       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24854                                    StoreType, ShuffWide,
24855                                    DAG.getIntPtrConstant(i, dl));
24856       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24857                                 St->getPointerInfo(), St->isVolatile(),
24858                                 St->isNonTemporal(), St->getAlignment());
24859       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24860       Chains.push_back(Ch);
24861     }
24862
24863     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24864   }
24865
24866   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24867   // the FP state in cases where an emms may be missing.
24868   // A preferable solution to the general problem is to figure out the right
24869   // places to insert EMMS.  This qualifies as a quick hack.
24870
24871   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24872   if (VT.getSizeInBits() != 64)
24873     return SDValue();
24874
24875   const Function *F = DAG.getMachineFunction().getFunction();
24876   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24877   bool F64IsLegal =
24878       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24879   if ((VT.isVector() ||
24880        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24881       isa<LoadSDNode>(St->getValue()) &&
24882       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24883       St->getChain().hasOneUse() && !St->isVolatile()) {
24884     SDNode* LdVal = St->getValue().getNode();
24885     LoadSDNode *Ld = nullptr;
24886     int TokenFactorIndex = -1;
24887     SmallVector<SDValue, 8> Ops;
24888     SDNode* ChainVal = St->getChain().getNode();
24889     // Must be a store of a load.  We currently handle two cases:  the load
24890     // is a direct child, and it's under an intervening TokenFactor.  It is
24891     // possible to dig deeper under nested TokenFactors.
24892     if (ChainVal == LdVal)
24893       Ld = cast<LoadSDNode>(St->getChain());
24894     else if (St->getValue().hasOneUse() &&
24895              ChainVal->getOpcode() == ISD::TokenFactor) {
24896       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24897         if (ChainVal->getOperand(i).getNode() == LdVal) {
24898           TokenFactorIndex = i;
24899           Ld = cast<LoadSDNode>(St->getValue());
24900         } else
24901           Ops.push_back(ChainVal->getOperand(i));
24902       }
24903     }
24904
24905     if (!Ld || !ISD::isNormalLoad(Ld))
24906       return SDValue();
24907
24908     // If this is not the MMX case, i.e. we are just turning i64 load/store
24909     // into f64 load/store, avoid the transformation if there are multiple
24910     // uses of the loaded value.
24911     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24912       return SDValue();
24913
24914     SDLoc LdDL(Ld);
24915     SDLoc StDL(N);
24916     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24917     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24918     // pair instead.
24919     if (Subtarget->is64Bit() || F64IsLegal) {
24920       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24921       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24922                                   Ld->getPointerInfo(), Ld->isVolatile(),
24923                                   Ld->isNonTemporal(), Ld->isInvariant(),
24924                                   Ld->getAlignment());
24925       SDValue NewChain = NewLd.getValue(1);
24926       if (TokenFactorIndex != -1) {
24927         Ops.push_back(NewChain);
24928         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24929       }
24930       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24931                           St->getPointerInfo(),
24932                           St->isVolatile(), St->isNonTemporal(),
24933                           St->getAlignment());
24934     }
24935
24936     // Otherwise, lower to two pairs of 32-bit loads / stores.
24937     SDValue LoAddr = Ld->getBasePtr();
24938     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24939                                  DAG.getConstant(4, LdDL, MVT::i32));
24940
24941     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24942                                Ld->getPointerInfo(),
24943                                Ld->isVolatile(), Ld->isNonTemporal(),
24944                                Ld->isInvariant(), Ld->getAlignment());
24945     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24946                                Ld->getPointerInfo().getWithOffset(4),
24947                                Ld->isVolatile(), Ld->isNonTemporal(),
24948                                Ld->isInvariant(),
24949                                MinAlign(Ld->getAlignment(), 4));
24950
24951     SDValue NewChain = LoLd.getValue(1);
24952     if (TokenFactorIndex != -1) {
24953       Ops.push_back(LoLd);
24954       Ops.push_back(HiLd);
24955       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24956     }
24957
24958     LoAddr = St->getBasePtr();
24959     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24960                          DAG.getConstant(4, StDL, MVT::i32));
24961
24962     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24963                                 St->getPointerInfo(),
24964                                 St->isVolatile(), St->isNonTemporal(),
24965                                 St->getAlignment());
24966     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24967                                 St->getPointerInfo().getWithOffset(4),
24968                                 St->isVolatile(),
24969                                 St->isNonTemporal(),
24970                                 MinAlign(St->getAlignment(), 4));
24971     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24972   }
24973
24974   // This is similar to the above case, but here we handle a scalar 64-bit
24975   // integer store that is extracted from a vector on a 32-bit target.
24976   // If we have SSE2, then we can treat it like a floating-point double
24977   // to get past legalization. The execution dependencies fixup pass will
24978   // choose the optimal machine instruction for the store if this really is
24979   // an integer or v2f32 rather than an f64.
24980   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24981       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24982     SDValue OldExtract = St->getOperand(1);
24983     SDValue ExtOp0 = OldExtract.getOperand(0);
24984     unsigned VecSize = ExtOp0.getValueSizeInBits();
24985     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24986     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24987     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24988                                      BitCast, OldExtract.getOperand(1));
24989     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24990                         St->getPointerInfo(), St->isVolatile(),
24991                         St->isNonTemporal(), St->getAlignment());
24992   }
24993
24994   return SDValue();
24995 }
24996
24997 /// Return 'true' if this vector operation is "horizontal"
24998 /// and return the operands for the horizontal operation in LHS and RHS.  A
24999 /// horizontal operation performs the binary operation on successive elements
25000 /// of its first operand, then on successive elements of its second operand,
25001 /// returning the resulting values in a vector.  For example, if
25002 ///   A = < float a0, float a1, float a2, float a3 >
25003 /// and
25004 ///   B = < float b0, float b1, float b2, float b3 >
25005 /// then the result of doing a horizontal operation on A and B is
25006 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25007 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25008 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25009 /// set to A, RHS to B, and the routine returns 'true'.
25010 /// Note that the binary operation should have the property that if one of the
25011 /// operands is UNDEF then the result is UNDEF.
25012 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25013   // Look for the following pattern: if
25014   //   A = < float a0, float a1, float a2, float a3 >
25015   //   B = < float b0, float b1, float b2, float b3 >
25016   // and
25017   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25018   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25019   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25020   // which is A horizontal-op B.
25021
25022   // At least one of the operands should be a vector shuffle.
25023   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25024       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25025     return false;
25026
25027   MVT VT = LHS.getSimpleValueType();
25028
25029   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25030          "Unsupported vector type for horizontal add/sub");
25031
25032   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25033   // operate independently on 128-bit lanes.
25034   unsigned NumElts = VT.getVectorNumElements();
25035   unsigned NumLanes = VT.getSizeInBits()/128;
25036   unsigned NumLaneElts = NumElts / NumLanes;
25037   assert((NumLaneElts % 2 == 0) &&
25038          "Vector type should have an even number of elements in each lane");
25039   unsigned HalfLaneElts = NumLaneElts/2;
25040
25041   // View LHS in the form
25042   //   LHS = VECTOR_SHUFFLE A, B, LMask
25043   // If LHS is not a shuffle then pretend it is the shuffle
25044   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25045   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25046   // type VT.
25047   SDValue A, B;
25048   SmallVector<int, 16> LMask(NumElts);
25049   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25050     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25051       A = LHS.getOperand(0);
25052     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25053       B = LHS.getOperand(1);
25054     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25055     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25056   } else {
25057     if (LHS.getOpcode() != ISD::UNDEF)
25058       A = LHS;
25059     for (unsigned i = 0; i != NumElts; ++i)
25060       LMask[i] = i;
25061   }
25062
25063   // Likewise, view RHS in the form
25064   //   RHS = VECTOR_SHUFFLE C, D, RMask
25065   SDValue C, D;
25066   SmallVector<int, 16> RMask(NumElts);
25067   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25068     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25069       C = RHS.getOperand(0);
25070     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25071       D = RHS.getOperand(1);
25072     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25073     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25074   } else {
25075     if (RHS.getOpcode() != ISD::UNDEF)
25076       C = RHS;
25077     for (unsigned i = 0; i != NumElts; ++i)
25078       RMask[i] = i;
25079   }
25080
25081   // Check that the shuffles are both shuffling the same vectors.
25082   if (!(A == C && B == D) && !(A == D && B == C))
25083     return false;
25084
25085   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25086   if (!A.getNode() && !B.getNode())
25087     return false;
25088
25089   // If A and B occur in reverse order in RHS, then "swap" them (which means
25090   // rewriting the mask).
25091   if (A != C)
25092     ShuffleVectorSDNode::commuteMask(RMask);
25093
25094   // At this point LHS and RHS are equivalent to
25095   //   LHS = VECTOR_SHUFFLE A, B, LMask
25096   //   RHS = VECTOR_SHUFFLE A, B, RMask
25097   // Check that the masks correspond to performing a horizontal operation.
25098   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25099     for (unsigned i = 0; i != NumLaneElts; ++i) {
25100       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25101
25102       // Ignore any UNDEF components.
25103       if (LIdx < 0 || RIdx < 0 ||
25104           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25105           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25106         continue;
25107
25108       // Check that successive elements are being operated on.  If not, this is
25109       // not a horizontal operation.
25110       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25111       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25112       if (!(LIdx == Index && RIdx == Index + 1) &&
25113           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25114         return false;
25115     }
25116   }
25117
25118   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25119   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25120   return true;
25121 }
25122
25123 /// Do target-specific dag combines on floating point adds.
25124 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25125                                   const X86Subtarget *Subtarget) {
25126   EVT VT = N->getValueType(0);
25127   SDValue LHS = N->getOperand(0);
25128   SDValue RHS = N->getOperand(1);
25129
25130   // Try to synthesize horizontal adds from adds of shuffles.
25131   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25132        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25133       isHorizontalBinOp(LHS, RHS, true))
25134     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25135   return SDValue();
25136 }
25137
25138 /// Do target-specific dag combines on floating point subs.
25139 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25140                                   const X86Subtarget *Subtarget) {
25141   EVT VT = N->getValueType(0);
25142   SDValue LHS = N->getOperand(0);
25143   SDValue RHS = N->getOperand(1);
25144
25145   // Try to synthesize horizontal subs from subs of shuffles.
25146   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25147        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25148       isHorizontalBinOp(LHS, RHS, false))
25149     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25150   return SDValue();
25151 }
25152
25153 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25154 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
25155   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25156
25157   // F[X]OR(0.0, x) -> x
25158   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25159     if (C->getValueAPF().isPosZero())
25160       return N->getOperand(1);
25161
25162   // F[X]OR(x, 0.0) -> x
25163   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25164     if (C->getValueAPF().isPosZero())
25165       return N->getOperand(0);
25166   return SDValue();
25167 }
25168
25169 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25170 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25171   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25172
25173   // Only perform optimizations if UnsafeMath is used.
25174   if (!DAG.getTarget().Options.UnsafeFPMath)
25175     return SDValue();
25176
25177   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25178   // into FMINC and FMAXC, which are Commutative operations.
25179   unsigned NewOp = 0;
25180   switch (N->getOpcode()) {
25181     default: llvm_unreachable("unknown opcode");
25182     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25183     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25184   }
25185
25186   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25187                      N->getOperand(0), N->getOperand(1));
25188 }
25189
25190 /// Do target-specific dag combines on X86ISD::FAND nodes.
25191 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25192   // FAND(0.0, x) -> 0.0
25193   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25194     if (C->getValueAPF().isPosZero())
25195       return N->getOperand(0);
25196
25197   // FAND(x, 0.0) -> 0.0
25198   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25199     if (C->getValueAPF().isPosZero())
25200       return N->getOperand(1);
25201
25202   return SDValue();
25203 }
25204
25205 /// Do target-specific dag combines on X86ISD::FANDN nodes
25206 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25207   // FANDN(0.0, x) -> x
25208   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25209     if (C->getValueAPF().isPosZero())
25210       return N->getOperand(1);
25211
25212   // FANDN(x, 0.0) -> 0.0
25213   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25214     if (C->getValueAPF().isPosZero())
25215       return N->getOperand(1);
25216
25217   return SDValue();
25218 }
25219
25220 static SDValue PerformBTCombine(SDNode *N,
25221                                 SelectionDAG &DAG,
25222                                 TargetLowering::DAGCombinerInfo &DCI) {
25223   // BT ignores high bits in the bit index operand.
25224   SDValue Op1 = N->getOperand(1);
25225   if (Op1.hasOneUse()) {
25226     unsigned BitWidth = Op1.getValueSizeInBits();
25227     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25228     APInt KnownZero, KnownOne;
25229     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25230                                           !DCI.isBeforeLegalizeOps());
25231     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25232     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25233         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25234       DCI.CommitTargetLoweringOpt(TLO);
25235   }
25236   return SDValue();
25237 }
25238
25239 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25240   SDValue Op = N->getOperand(0);
25241   if (Op.getOpcode() == ISD::BITCAST)
25242     Op = Op.getOperand(0);
25243   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25244   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25245       VT.getVectorElementType().getSizeInBits() ==
25246       OpVT.getVectorElementType().getSizeInBits()) {
25247     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25248   }
25249   return SDValue();
25250 }
25251
25252 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25253                                                const X86Subtarget *Subtarget) {
25254   EVT VT = N->getValueType(0);
25255   if (!VT.isVector())
25256     return SDValue();
25257
25258   SDValue N0 = N->getOperand(0);
25259   SDValue N1 = N->getOperand(1);
25260   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25261   SDLoc dl(N);
25262
25263   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25264   // both SSE and AVX2 since there is no sign-extended shift right
25265   // operation on a vector with 64-bit elements.
25266   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25267   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25268   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25269       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25270     SDValue N00 = N0.getOperand(0);
25271
25272     // EXTLOAD has a better solution on AVX2,
25273     // it may be replaced with X86ISD::VSEXT node.
25274     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25275       if (!ISD::isNormalLoad(N00.getNode()))
25276         return SDValue();
25277
25278     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25279         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25280                                   N00, N1);
25281       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25282     }
25283   }
25284   return SDValue();
25285 }
25286
25287 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25288                                   TargetLowering::DAGCombinerInfo &DCI,
25289                                   const X86Subtarget *Subtarget) {
25290   SDValue N0 = N->getOperand(0);
25291   EVT VT = N->getValueType(0);
25292   EVT SVT = VT.getScalarType();
25293   EVT InVT = N0.getValueType();
25294   EVT InSVT = InVT.getScalarType();
25295   SDLoc DL(N);
25296
25297   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25298   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25299   // This exposes the sext to the sdivrem lowering, so that it directly extends
25300   // from AH (which we otherwise need to do contortions to access).
25301   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25302       InVT == MVT::i8 && VT == MVT::i32) {
25303     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25304     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25305                             N0.getOperand(0), N0.getOperand(1));
25306     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25307     return R.getValue(1);
25308   }
25309
25310   if (!DCI.isBeforeLegalizeOps()) {
25311     if (InVT == MVT::i1) {
25312       SDValue Zero = DAG.getConstant(0, DL, VT);
25313       SDValue AllOnes =
25314         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25315       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25316     }
25317     return SDValue();
25318   }
25319
25320   if (VT.isVector() && Subtarget->hasSSE2()) {
25321     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25322       EVT InVT = N.getValueType();
25323       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25324                                    Size / InVT.getScalarSizeInBits());
25325       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25326                                     DAG.getUNDEF(InVT));
25327       Opnds[0] = N;
25328       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25329     };
25330
25331     // If target-size is less than 128-bits, extend to a type that would extend
25332     // to 128 bits, extend that and extract the original target vector.
25333     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25334         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25335         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25336       unsigned Scale = 128 / VT.getSizeInBits();
25337       EVT ExVT =
25338           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25339       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25340       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25341       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25342                          DAG.getIntPtrConstant(0, DL));
25343     }
25344
25345     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25346     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25347     if (VT.getSizeInBits() == 128 &&
25348         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25349         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25350       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25351       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25352     }
25353
25354     // On pre-AVX2 targets, split into 128-bit nodes of
25355     // ISD::SIGN_EXTEND_VECTOR_INREG.
25356     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25357         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25358         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25359       unsigned NumVecs = VT.getSizeInBits() / 128;
25360       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25361       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25362       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25363
25364       SmallVector<SDValue, 8> Opnds;
25365       for (unsigned i = 0, Offset = 0; i != NumVecs;
25366            ++i, Offset += NumSubElts) {
25367         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25368                                      DAG.getIntPtrConstant(Offset, DL));
25369         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25370         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25371         Opnds.push_back(SrcVec);
25372       }
25373       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25374     }
25375   }
25376
25377   if (!Subtarget->hasFp256())
25378     return SDValue();
25379
25380   if (VT.isVector() && VT.getSizeInBits() == 256)
25381     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25382       return R;
25383
25384   return SDValue();
25385 }
25386
25387 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25388                                  const X86Subtarget* Subtarget) {
25389   SDLoc dl(N);
25390   EVT VT = N->getValueType(0);
25391
25392   // Let legalize expand this if it isn't a legal type yet.
25393   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25394     return SDValue();
25395
25396   EVT ScalarVT = VT.getScalarType();
25397   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25398       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25399        !Subtarget->hasAVX512()))
25400     return SDValue();
25401
25402   SDValue A = N->getOperand(0);
25403   SDValue B = N->getOperand(1);
25404   SDValue C = N->getOperand(2);
25405
25406   bool NegA = (A.getOpcode() == ISD::FNEG);
25407   bool NegB = (B.getOpcode() == ISD::FNEG);
25408   bool NegC = (C.getOpcode() == ISD::FNEG);
25409
25410   // Negative multiplication when NegA xor NegB
25411   bool NegMul = (NegA != NegB);
25412   if (NegA)
25413     A = A.getOperand(0);
25414   if (NegB)
25415     B = B.getOperand(0);
25416   if (NegC)
25417     C = C.getOperand(0);
25418
25419   unsigned Opcode;
25420   if (!NegMul)
25421     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25422   else
25423     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25424
25425   return DAG.getNode(Opcode, dl, VT, A, B, C);
25426 }
25427
25428 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25429                                   TargetLowering::DAGCombinerInfo &DCI,
25430                                   const X86Subtarget *Subtarget) {
25431   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25432   //           (and (i32 x86isd::setcc_carry), 1)
25433   // This eliminates the zext. This transformation is necessary because
25434   // ISD::SETCC is always legalized to i8.
25435   SDLoc dl(N);
25436   SDValue N0 = N->getOperand(0);
25437   EVT VT = N->getValueType(0);
25438
25439   if (N0.getOpcode() == ISD::AND &&
25440       N0.hasOneUse() &&
25441       N0.getOperand(0).hasOneUse()) {
25442     SDValue N00 = N0.getOperand(0);
25443     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25444       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25445       if (!C || C->getZExtValue() != 1)
25446         return SDValue();
25447       return DAG.getNode(ISD::AND, dl, VT,
25448                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25449                                      N00.getOperand(0), N00.getOperand(1)),
25450                          DAG.getConstant(1, dl, VT));
25451     }
25452   }
25453
25454   if (N0.getOpcode() == ISD::TRUNCATE &&
25455       N0.hasOneUse() &&
25456       N0.getOperand(0).hasOneUse()) {
25457     SDValue N00 = N0.getOperand(0);
25458     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25459       return DAG.getNode(ISD::AND, dl, VT,
25460                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25461                                      N00.getOperand(0), N00.getOperand(1)),
25462                          DAG.getConstant(1, dl, VT));
25463     }
25464   }
25465
25466   if (VT.is256BitVector())
25467     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25468       return R;
25469
25470   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25471   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25472   // This exposes the zext to the udivrem lowering, so that it directly extends
25473   // from AH (which we otherwise need to do contortions to access).
25474   if (N0.getOpcode() == ISD::UDIVREM &&
25475       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25476       (VT == MVT::i32 || VT == MVT::i64)) {
25477     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25478     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25479                             N0.getOperand(0), N0.getOperand(1));
25480     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25481     return R.getValue(1);
25482   }
25483
25484   return SDValue();
25485 }
25486
25487 // Optimize x == -y --> x+y == 0
25488 //          x != -y --> x+y != 0
25489 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25490                                       const X86Subtarget* Subtarget) {
25491   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25492   SDValue LHS = N->getOperand(0);
25493   SDValue RHS = N->getOperand(1);
25494   EVT VT = N->getValueType(0);
25495   SDLoc DL(N);
25496
25497   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25498     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25499       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25500         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25501                                    LHS.getOperand(1));
25502         return DAG.getSetCC(DL, N->getValueType(0), addV,
25503                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25504       }
25505   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25506     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25507       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25508         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25509                                    RHS.getOperand(1));
25510         return DAG.getSetCC(DL, N->getValueType(0), addV,
25511                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25512       }
25513
25514   if (VT.getScalarType() == MVT::i1 &&
25515       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25516     bool IsSEXT0 =
25517         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25518         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25519     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25520
25521     if (!IsSEXT0 || !IsVZero1) {
25522       // Swap the operands and update the condition code.
25523       std::swap(LHS, RHS);
25524       CC = ISD::getSetCCSwappedOperands(CC);
25525
25526       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25527                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25528       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25529     }
25530
25531     if (IsSEXT0 && IsVZero1) {
25532       assert(VT == LHS.getOperand(0).getValueType() &&
25533              "Uexpected operand type");
25534       if (CC == ISD::SETGT)
25535         return DAG.getConstant(0, DL, VT);
25536       if (CC == ISD::SETLE)
25537         return DAG.getConstant(1, DL, VT);
25538       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25539         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25540
25541       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25542              "Unexpected condition code!");
25543       return LHS.getOperand(0);
25544     }
25545   }
25546
25547   return SDValue();
25548 }
25549
25550 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25551                                          SelectionDAG &DAG) {
25552   SDLoc dl(Load);
25553   MVT VT = Load->getSimpleValueType(0);
25554   MVT EVT = VT.getVectorElementType();
25555   SDValue Addr = Load->getOperand(1);
25556   SDValue NewAddr = DAG.getNode(
25557       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25558       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25559                       Addr.getSimpleValueType()));
25560
25561   SDValue NewLoad =
25562       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25563                   DAG.getMachineFunction().getMachineMemOperand(
25564                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25565   return NewLoad;
25566 }
25567
25568 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25569                                       const X86Subtarget *Subtarget) {
25570   SDLoc dl(N);
25571   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25572   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25573          "X86insertps is only defined for v4x32");
25574
25575   SDValue Ld = N->getOperand(1);
25576   if (MayFoldLoad(Ld)) {
25577     // Extract the countS bits from the immediate so we can get the proper
25578     // address when narrowing the vector load to a specific element.
25579     // When the second source op is a memory address, insertps doesn't use
25580     // countS and just gets an f32 from that address.
25581     unsigned DestIndex =
25582         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25583
25584     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25585
25586     // Create this as a scalar to vector to match the instruction pattern.
25587     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25588     // countS bits are ignored when loading from memory on insertps, which
25589     // means we don't need to explicitly set them to 0.
25590     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25591                        LoadScalarToVector, N->getOperand(2));
25592   }
25593   return SDValue();
25594 }
25595
25596 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25597   SDValue V0 = N->getOperand(0);
25598   SDValue V1 = N->getOperand(1);
25599   SDLoc DL(N);
25600   EVT VT = N->getValueType(0);
25601
25602   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25603   // operands and changing the mask to 1. This saves us a bunch of
25604   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25605   // x86InstrInfo knows how to commute this back after instruction selection
25606   // if it would help register allocation.
25607
25608   // TODO: If optimizing for size or a processor that doesn't suffer from
25609   // partial register update stalls, this should be transformed into a MOVSD
25610   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25611
25612   if (VT == MVT::v2f64)
25613     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25614       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25615         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25616         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25617       }
25618
25619   return SDValue();
25620 }
25621
25622 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25623 // as "sbb reg,reg", since it can be extended without zext and produces
25624 // an all-ones bit which is more useful than 0/1 in some cases.
25625 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25626                                MVT VT) {
25627   if (VT == MVT::i8)
25628     return DAG.getNode(ISD::AND, DL, VT,
25629                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25630                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25631                                    EFLAGS),
25632                        DAG.getConstant(1, DL, VT));
25633   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25634   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25635                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25636                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25637                                  EFLAGS));
25638 }
25639
25640 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25641 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25642                                    TargetLowering::DAGCombinerInfo &DCI,
25643                                    const X86Subtarget *Subtarget) {
25644   SDLoc DL(N);
25645   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25646   SDValue EFLAGS = N->getOperand(1);
25647
25648   if (CC == X86::COND_A) {
25649     // Try to convert COND_A into COND_B in an attempt to facilitate
25650     // materializing "setb reg".
25651     //
25652     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25653     // cannot take an immediate as its first operand.
25654     //
25655     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25656         EFLAGS.getValueType().isInteger() &&
25657         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25658       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25659                                    EFLAGS.getNode()->getVTList(),
25660                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25661       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25662       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25663     }
25664   }
25665
25666   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25667   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25668   // cases.
25669   if (CC == X86::COND_B)
25670     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25671
25672   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25673     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25674     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25675   }
25676
25677   return SDValue();
25678 }
25679
25680 // Optimize branch condition evaluation.
25681 //
25682 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25683                                     TargetLowering::DAGCombinerInfo &DCI,
25684                                     const X86Subtarget *Subtarget) {
25685   SDLoc DL(N);
25686   SDValue Chain = N->getOperand(0);
25687   SDValue Dest = N->getOperand(1);
25688   SDValue EFLAGS = N->getOperand(3);
25689   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25690
25691   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25692     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25693     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25694                        Flags);
25695   }
25696
25697   return SDValue();
25698 }
25699
25700 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25701                                                          SelectionDAG &DAG) {
25702   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25703   // optimize away operation when it's from a constant.
25704   //
25705   // The general transformation is:
25706   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25707   //       AND(VECTOR_CMP(x,y), constant2)
25708   //    constant2 = UNARYOP(constant)
25709
25710   // Early exit if this isn't a vector operation, the operand of the
25711   // unary operation isn't a bitwise AND, or if the sizes of the operations
25712   // aren't the same.
25713   EVT VT = N->getValueType(0);
25714   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25715       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25716       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25717     return SDValue();
25718
25719   // Now check that the other operand of the AND is a constant. We could
25720   // make the transformation for non-constant splats as well, but it's unclear
25721   // that would be a benefit as it would not eliminate any operations, just
25722   // perform one more step in scalar code before moving to the vector unit.
25723   if (BuildVectorSDNode *BV =
25724           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25725     // Bail out if the vector isn't a constant.
25726     if (!BV->isConstant())
25727       return SDValue();
25728
25729     // Everything checks out. Build up the new and improved node.
25730     SDLoc DL(N);
25731     EVT IntVT = BV->getValueType(0);
25732     // Create a new constant of the appropriate type for the transformed
25733     // DAG.
25734     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25735     // The AND node needs bitcasts to/from an integer vector type around it.
25736     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25737     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25738                                  N->getOperand(0)->getOperand(0), MaskConst);
25739     SDValue Res = DAG.getBitcast(VT, NewAnd);
25740     return Res;
25741   }
25742
25743   return SDValue();
25744 }
25745
25746 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25747                                         const X86Subtarget *Subtarget) {
25748   SDValue Op0 = N->getOperand(0);
25749   EVT VT = N->getValueType(0);
25750   EVT InVT = Op0.getValueType();
25751   EVT InSVT = InVT.getScalarType();
25752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25753
25754   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25755   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25756   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25757     SDLoc dl(N);
25758     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25759                                  InVT.getVectorNumElements());
25760     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25761
25762     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25763       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25764
25765     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25766   }
25767
25768   return SDValue();
25769 }
25770
25771 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25772                                         const X86Subtarget *Subtarget) {
25773   // First try to optimize away the conversion entirely when it's
25774   // conditionally from a constant. Vectors only.
25775   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25776     return Res;
25777
25778   // Now move on to more general possibilities.
25779   SDValue Op0 = N->getOperand(0);
25780   EVT VT = N->getValueType(0);
25781   EVT InVT = Op0.getValueType();
25782   EVT InSVT = InVT.getScalarType();
25783
25784   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25785   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25786   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25787     SDLoc dl(N);
25788     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25789                                  InVT.getVectorNumElements());
25790     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25791     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25792   }
25793
25794   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25795   // a 32-bit target where SSE doesn't support i64->FP operations.
25796   if (Op0.getOpcode() == ISD::LOAD) {
25797     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25798     EVT LdVT = Ld->getValueType(0);
25799
25800     // This transformation is not supported if the result type is f16
25801     if (VT == MVT::f16)
25802       return SDValue();
25803
25804     if (!Ld->isVolatile() && !VT.isVector() &&
25805         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25806         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25807       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25808           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25809       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25810       return FILDChain;
25811     }
25812   }
25813   return SDValue();
25814 }
25815
25816 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25817 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25818                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25819   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25820   // the result is either zero or one (depending on the input carry bit).
25821   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25822   if (X86::isZeroNode(N->getOperand(0)) &&
25823       X86::isZeroNode(N->getOperand(1)) &&
25824       // We don't have a good way to replace an EFLAGS use, so only do this when
25825       // dead right now.
25826       SDValue(N, 1).use_empty()) {
25827     SDLoc DL(N);
25828     EVT VT = N->getValueType(0);
25829     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25830     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25831                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25832                                            DAG.getConstant(X86::COND_B, DL,
25833                                                            MVT::i8),
25834                                            N->getOperand(2)),
25835                                DAG.getConstant(1, DL, VT));
25836     return DCI.CombineTo(N, Res1, CarryOut);
25837   }
25838
25839   return SDValue();
25840 }
25841
25842 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25843 //      (add Y, (setne X, 0)) -> sbb -1, Y
25844 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25845 //      (sub (setne X, 0), Y) -> adc -1, Y
25846 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25847   SDLoc DL(N);
25848
25849   // Look through ZExts.
25850   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25851   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25852     return SDValue();
25853
25854   SDValue SetCC = Ext.getOperand(0);
25855   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25856     return SDValue();
25857
25858   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25859   if (CC != X86::COND_E && CC != X86::COND_NE)
25860     return SDValue();
25861
25862   SDValue Cmp = SetCC.getOperand(1);
25863   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25864       !X86::isZeroNode(Cmp.getOperand(1)) ||
25865       !Cmp.getOperand(0).getValueType().isInteger())
25866     return SDValue();
25867
25868   SDValue CmpOp0 = Cmp.getOperand(0);
25869   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25870                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25871
25872   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25873   if (CC == X86::COND_NE)
25874     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25875                        DL, OtherVal.getValueType(), OtherVal,
25876                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25877                        NewCmp);
25878   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25879                      DL, OtherVal.getValueType(), OtherVal,
25880                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25881 }
25882
25883 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25884 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25885                                  const X86Subtarget *Subtarget) {
25886   EVT VT = N->getValueType(0);
25887   SDValue Op0 = N->getOperand(0);
25888   SDValue Op1 = N->getOperand(1);
25889
25890   // Try to synthesize horizontal adds from adds of shuffles.
25891   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25892        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25893       isHorizontalBinOp(Op0, Op1, true))
25894     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25895
25896   return OptimizeConditionalInDecrement(N, DAG);
25897 }
25898
25899 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25900                                  const X86Subtarget *Subtarget) {
25901   SDValue Op0 = N->getOperand(0);
25902   SDValue Op1 = N->getOperand(1);
25903
25904   // X86 can't encode an immediate LHS of a sub. See if we can push the
25905   // negation into a preceding instruction.
25906   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25907     // If the RHS of the sub is a XOR with one use and a constant, invert the
25908     // immediate. Then add one to the LHS of the sub so we can turn
25909     // X-Y -> X+~Y+1, saving one register.
25910     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25911         isa<ConstantSDNode>(Op1.getOperand(1))) {
25912       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25913       EVT VT = Op0.getValueType();
25914       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25915                                    Op1.getOperand(0),
25916                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25917       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25918                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25919     }
25920   }
25921
25922   // Try to synthesize horizontal adds from adds of shuffles.
25923   EVT VT = N->getValueType(0);
25924   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25925        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25926       isHorizontalBinOp(Op0, Op1, true))
25927     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25928
25929   return OptimizeConditionalInDecrement(N, DAG);
25930 }
25931
25932 /// performVZEXTCombine - Performs build vector combines
25933 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25934                                    TargetLowering::DAGCombinerInfo &DCI,
25935                                    const X86Subtarget *Subtarget) {
25936   SDLoc DL(N);
25937   MVT VT = N->getSimpleValueType(0);
25938   SDValue Op = N->getOperand(0);
25939   MVT OpVT = Op.getSimpleValueType();
25940   MVT OpEltVT = OpVT.getVectorElementType();
25941   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25942
25943   // (vzext (bitcast (vzext (x)) -> (vzext x)
25944   SDValue V = Op;
25945   while (V.getOpcode() == ISD::BITCAST)
25946     V = V.getOperand(0);
25947
25948   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25949     MVT InnerVT = V.getSimpleValueType();
25950     MVT InnerEltVT = InnerVT.getVectorElementType();
25951
25952     // If the element sizes match exactly, we can just do one larger vzext. This
25953     // is always an exact type match as vzext operates on integer types.
25954     if (OpEltVT == InnerEltVT) {
25955       assert(OpVT == InnerVT && "Types must match for vzext!");
25956       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25957     }
25958
25959     // The only other way we can combine them is if only a single element of the
25960     // inner vzext is used in the input to the outer vzext.
25961     if (InnerEltVT.getSizeInBits() < InputBits)
25962       return SDValue();
25963
25964     // In this case, the inner vzext is completely dead because we're going to
25965     // only look at bits inside of the low element. Just do the outer vzext on
25966     // a bitcast of the input to the inner.
25967     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25968   }
25969
25970   // Check if we can bypass extracting and re-inserting an element of an input
25971   // vector. Essentially:
25972   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25973   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25974       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25975       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25976     SDValue ExtractedV = V.getOperand(0);
25977     SDValue OrigV = ExtractedV.getOperand(0);
25978     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25979       if (ExtractIdx->getZExtValue() == 0) {
25980         MVT OrigVT = OrigV.getSimpleValueType();
25981         // Extract a subvector if necessary...
25982         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25983           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25984           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25985                                     OrigVT.getVectorNumElements() / Ratio);
25986           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25987                               DAG.getIntPtrConstant(0, DL));
25988         }
25989         Op = DAG.getBitcast(OpVT, OrigV);
25990         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25991       }
25992   }
25993
25994   return SDValue();
25995 }
25996
25997 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25998                                              DAGCombinerInfo &DCI) const {
25999   SelectionDAG &DAG = DCI.DAG;
26000   switch (N->getOpcode()) {
26001   default: break;
26002   case ISD::EXTRACT_VECTOR_ELT:
26003     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26004   case ISD::VSELECT:
26005   case ISD::SELECT:
26006   case X86ISD::SHRUNKBLEND:
26007     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26008   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26009   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26010   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26011   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26012   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26013   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26014   case ISD::SHL:
26015   case ISD::SRA:
26016   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26017   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26018   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26019   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26020   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26021   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26022   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26023   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26024   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26025   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26026   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26027   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26028   case X86ISD::FXOR:
26029   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
26030   case X86ISD::FMIN:
26031   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26032   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26033   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26034   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26035   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26036   case ISD::ANY_EXTEND:
26037   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26038   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26039   case ISD::SIGN_EXTEND_INREG:
26040     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26041   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26042   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26043   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26044   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26045   case X86ISD::SHUFP:       // Handle all target specific shuffles
26046   case X86ISD::PALIGNR:
26047   case X86ISD::UNPCKH:
26048   case X86ISD::UNPCKL:
26049   case X86ISD::MOVHLPS:
26050   case X86ISD::MOVLHPS:
26051   case X86ISD::PSHUFB:
26052   case X86ISD::PSHUFD:
26053   case X86ISD::PSHUFHW:
26054   case X86ISD::PSHUFLW:
26055   case X86ISD::MOVSS:
26056   case X86ISD::MOVSD:
26057   case X86ISD::VPERMILPI:
26058   case X86ISD::VPERM2X128:
26059   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26060   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26061   case X86ISD::INSERTPS: {
26062     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26063       return PerformINSERTPSCombine(N, DAG, Subtarget);
26064     break;
26065   }
26066   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26067   }
26068
26069   return SDValue();
26070 }
26071
26072 /// isTypeDesirableForOp - Return true if the target has native support for
26073 /// the specified value type and it is 'desirable' to use the type for the
26074 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26075 /// instruction encodings are longer and some i16 instructions are slow.
26076 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26077   if (!isTypeLegal(VT))
26078     return false;
26079   if (VT != MVT::i16)
26080     return true;
26081
26082   switch (Opc) {
26083   default:
26084     return true;
26085   case ISD::LOAD:
26086   case ISD::SIGN_EXTEND:
26087   case ISD::ZERO_EXTEND:
26088   case ISD::ANY_EXTEND:
26089   case ISD::SHL:
26090   case ISD::SRL:
26091   case ISD::SUB:
26092   case ISD::ADD:
26093   case ISD::MUL:
26094   case ISD::AND:
26095   case ISD::OR:
26096   case ISD::XOR:
26097     return false;
26098   }
26099 }
26100
26101 /// IsDesirableToPromoteOp - This method query the target whether it is
26102 /// beneficial for dag combiner to promote the specified node. If true, it
26103 /// should return the desired promotion type by reference.
26104 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26105   EVT VT = Op.getValueType();
26106   if (VT != MVT::i16)
26107     return false;
26108
26109   bool Promote = false;
26110   bool Commute = false;
26111   switch (Op.getOpcode()) {
26112   default: break;
26113   case ISD::LOAD: {
26114     LoadSDNode *LD = cast<LoadSDNode>(Op);
26115     // If the non-extending load has a single use and it's not live out, then it
26116     // might be folded.
26117     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26118                                                      Op.hasOneUse()*/) {
26119       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26120              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26121         // The only case where we'd want to promote LOAD (rather then it being
26122         // promoted as an operand is when it's only use is liveout.
26123         if (UI->getOpcode() != ISD::CopyToReg)
26124           return false;
26125       }
26126     }
26127     Promote = true;
26128     break;
26129   }
26130   case ISD::SIGN_EXTEND:
26131   case ISD::ZERO_EXTEND:
26132   case ISD::ANY_EXTEND:
26133     Promote = true;
26134     break;
26135   case ISD::SHL:
26136   case ISD::SRL: {
26137     SDValue N0 = Op.getOperand(0);
26138     // Look out for (store (shl (load), x)).
26139     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26140       return false;
26141     Promote = true;
26142     break;
26143   }
26144   case ISD::ADD:
26145   case ISD::MUL:
26146   case ISD::AND:
26147   case ISD::OR:
26148   case ISD::XOR:
26149     Commute = true;
26150     // fallthrough
26151   case ISD::SUB: {
26152     SDValue N0 = Op.getOperand(0);
26153     SDValue N1 = Op.getOperand(1);
26154     if (!Commute && MayFoldLoad(N1))
26155       return false;
26156     // Avoid disabling potential load folding opportunities.
26157     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26158       return false;
26159     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26160       return false;
26161     Promote = true;
26162   }
26163   }
26164
26165   PVT = MVT::i32;
26166   return Promote;
26167 }
26168
26169 //===----------------------------------------------------------------------===//
26170 //                           X86 Inline Assembly Support
26171 //===----------------------------------------------------------------------===//
26172
26173 // Helper to match a string separated by whitespace.
26174 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26175   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26176
26177   for (StringRef Piece : Pieces) {
26178     if (!S.startswith(Piece)) // Check if the piece matches.
26179       return false;
26180
26181     S = S.substr(Piece.size());
26182     StringRef::size_type Pos = S.find_first_not_of(" \t");
26183     if (Pos == 0) // We matched a prefix.
26184       return false;
26185
26186     S = S.substr(Pos);
26187   }
26188
26189   return S.empty();
26190 }
26191
26192 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26193
26194   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26195     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26196         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26197         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26198
26199       if (AsmPieces.size() == 3)
26200         return true;
26201       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26202         return true;
26203     }
26204   }
26205   return false;
26206 }
26207
26208 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26209   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26210
26211   std::string AsmStr = IA->getAsmString();
26212
26213   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26214   if (!Ty || Ty->getBitWidth() % 16 != 0)
26215     return false;
26216
26217   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26218   SmallVector<StringRef, 4> AsmPieces;
26219   SplitString(AsmStr, AsmPieces, ";\n");
26220
26221   switch (AsmPieces.size()) {
26222   default: return false;
26223   case 1:
26224     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26225     // we will turn this bswap into something that will be lowered to logical
26226     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26227     // lower so don't worry about this.
26228     // bswap $0
26229     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26230         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26231         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26232         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26233         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26234         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26235       // No need to check constraints, nothing other than the equivalent of
26236       // "=r,0" would be valid here.
26237       return IntrinsicLowering::LowerToByteSwap(CI);
26238     }
26239
26240     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26241     if (CI->getType()->isIntegerTy(16) &&
26242         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26243         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26244          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26245       AsmPieces.clear();
26246       StringRef ConstraintsStr = IA->getConstraintString();
26247       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26248       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26249       if (clobbersFlagRegisters(AsmPieces))
26250         return IntrinsicLowering::LowerToByteSwap(CI);
26251     }
26252     break;
26253   case 3:
26254     if (CI->getType()->isIntegerTy(32) &&
26255         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26256         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26257         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26258         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26259       AsmPieces.clear();
26260       StringRef ConstraintsStr = IA->getConstraintString();
26261       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26262       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26263       if (clobbersFlagRegisters(AsmPieces))
26264         return IntrinsicLowering::LowerToByteSwap(CI);
26265     }
26266
26267     if (CI->getType()->isIntegerTy(64)) {
26268       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26269       if (Constraints.size() >= 2 &&
26270           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26271           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26272         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26273         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26274             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26275             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26276           return IntrinsicLowering::LowerToByteSwap(CI);
26277       }
26278     }
26279     break;
26280   }
26281   return false;
26282 }
26283
26284 /// getConstraintType - Given a constraint letter, return the type of
26285 /// constraint it is for this target.
26286 X86TargetLowering::ConstraintType
26287 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26288   if (Constraint.size() == 1) {
26289     switch (Constraint[0]) {
26290     case 'R':
26291     case 'q':
26292     case 'Q':
26293     case 'f':
26294     case 't':
26295     case 'u':
26296     case 'y':
26297     case 'x':
26298     case 'Y':
26299     case 'l':
26300       return C_RegisterClass;
26301     case 'a':
26302     case 'b':
26303     case 'c':
26304     case 'd':
26305     case 'S':
26306     case 'D':
26307     case 'A':
26308       return C_Register;
26309     case 'I':
26310     case 'J':
26311     case 'K':
26312     case 'L':
26313     case 'M':
26314     case 'N':
26315     case 'G':
26316     case 'C':
26317     case 'e':
26318     case 'Z':
26319       return C_Other;
26320     default:
26321       break;
26322     }
26323   }
26324   return TargetLowering::getConstraintType(Constraint);
26325 }
26326
26327 /// Examine constraint type and operand type and determine a weight value.
26328 /// This object must already have been set up with the operand type
26329 /// and the current alternative constraint selected.
26330 TargetLowering::ConstraintWeight
26331   X86TargetLowering::getSingleConstraintMatchWeight(
26332     AsmOperandInfo &info, const char *constraint) const {
26333   ConstraintWeight weight = CW_Invalid;
26334   Value *CallOperandVal = info.CallOperandVal;
26335     // If we don't have a value, we can't do a match,
26336     // but allow it at the lowest weight.
26337   if (!CallOperandVal)
26338     return CW_Default;
26339   Type *type = CallOperandVal->getType();
26340   // Look at the constraint type.
26341   switch (*constraint) {
26342   default:
26343     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26344   case 'R':
26345   case 'q':
26346   case 'Q':
26347   case 'a':
26348   case 'b':
26349   case 'c':
26350   case 'd':
26351   case 'S':
26352   case 'D':
26353   case 'A':
26354     if (CallOperandVal->getType()->isIntegerTy())
26355       weight = CW_SpecificReg;
26356     break;
26357   case 'f':
26358   case 't':
26359   case 'u':
26360     if (type->isFloatingPointTy())
26361       weight = CW_SpecificReg;
26362     break;
26363   case 'y':
26364     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26365       weight = CW_SpecificReg;
26366     break;
26367   case 'x':
26368   case 'Y':
26369     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26370         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26371       weight = CW_Register;
26372     break;
26373   case 'I':
26374     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26375       if (C->getZExtValue() <= 31)
26376         weight = CW_Constant;
26377     }
26378     break;
26379   case 'J':
26380     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26381       if (C->getZExtValue() <= 63)
26382         weight = CW_Constant;
26383     }
26384     break;
26385   case 'K':
26386     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26387       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26388         weight = CW_Constant;
26389     }
26390     break;
26391   case 'L':
26392     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26393       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26394         weight = CW_Constant;
26395     }
26396     break;
26397   case 'M':
26398     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26399       if (C->getZExtValue() <= 3)
26400         weight = CW_Constant;
26401     }
26402     break;
26403   case 'N':
26404     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26405       if (C->getZExtValue() <= 0xff)
26406         weight = CW_Constant;
26407     }
26408     break;
26409   case 'G':
26410   case 'C':
26411     if (isa<ConstantFP>(CallOperandVal)) {
26412       weight = CW_Constant;
26413     }
26414     break;
26415   case 'e':
26416     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26417       if ((C->getSExtValue() >= -0x80000000LL) &&
26418           (C->getSExtValue() <= 0x7fffffffLL))
26419         weight = CW_Constant;
26420     }
26421     break;
26422   case 'Z':
26423     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26424       if (C->getZExtValue() <= 0xffffffff)
26425         weight = CW_Constant;
26426     }
26427     break;
26428   }
26429   return weight;
26430 }
26431
26432 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26433 /// with another that has more specific requirements based on the type of the
26434 /// corresponding operand.
26435 const char *X86TargetLowering::
26436 LowerXConstraint(EVT ConstraintVT) const {
26437   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26438   // 'f' like normal targets.
26439   if (ConstraintVT.isFloatingPoint()) {
26440     if (Subtarget->hasSSE2())
26441       return "Y";
26442     if (Subtarget->hasSSE1())
26443       return "x";
26444   }
26445
26446   return TargetLowering::LowerXConstraint(ConstraintVT);
26447 }
26448
26449 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26450 /// vector.  If it is invalid, don't add anything to Ops.
26451 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26452                                                      std::string &Constraint,
26453                                                      std::vector<SDValue>&Ops,
26454                                                      SelectionDAG &DAG) const {
26455   SDValue Result;
26456
26457   // Only support length 1 constraints for now.
26458   if (Constraint.length() > 1) return;
26459
26460   char ConstraintLetter = Constraint[0];
26461   switch (ConstraintLetter) {
26462   default: break;
26463   case 'I':
26464     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26465       if (C->getZExtValue() <= 31) {
26466         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26467                                        Op.getValueType());
26468         break;
26469       }
26470     }
26471     return;
26472   case 'J':
26473     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26474       if (C->getZExtValue() <= 63) {
26475         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26476                                        Op.getValueType());
26477         break;
26478       }
26479     }
26480     return;
26481   case 'K':
26482     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26483       if (isInt<8>(C->getSExtValue())) {
26484         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26485                                        Op.getValueType());
26486         break;
26487       }
26488     }
26489     return;
26490   case 'L':
26491     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26492       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26493           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26494         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26495                                        Op.getValueType());
26496         break;
26497       }
26498     }
26499     return;
26500   case 'M':
26501     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26502       if (C->getZExtValue() <= 3) {
26503         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26504                                        Op.getValueType());
26505         break;
26506       }
26507     }
26508     return;
26509   case 'N':
26510     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26511       if (C->getZExtValue() <= 255) {
26512         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26513                                        Op.getValueType());
26514         break;
26515       }
26516     }
26517     return;
26518   case 'O':
26519     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26520       if (C->getZExtValue() <= 127) {
26521         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26522                                        Op.getValueType());
26523         break;
26524       }
26525     }
26526     return;
26527   case 'e': {
26528     // 32-bit signed value
26529     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26530       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26531                                            C->getSExtValue())) {
26532         // Widen to 64 bits here to get it sign extended.
26533         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26534         break;
26535       }
26536     // FIXME gcc accepts some relocatable values here too, but only in certain
26537     // memory models; it's complicated.
26538     }
26539     return;
26540   }
26541   case 'Z': {
26542     // 32-bit unsigned value
26543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26544       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26545                                            C->getZExtValue())) {
26546         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26547                                        Op.getValueType());
26548         break;
26549       }
26550     }
26551     // FIXME gcc accepts some relocatable values here too, but only in certain
26552     // memory models; it's complicated.
26553     return;
26554   }
26555   case 'i': {
26556     // Literal immediates are always ok.
26557     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26558       // Widen to 64 bits here to get it sign extended.
26559       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26560       break;
26561     }
26562
26563     // In any sort of PIC mode addresses need to be computed at runtime by
26564     // adding in a register or some sort of table lookup.  These can't
26565     // be used as immediates.
26566     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26567       return;
26568
26569     // If we are in non-pic codegen mode, we allow the address of a global (with
26570     // an optional displacement) to be used with 'i'.
26571     GlobalAddressSDNode *GA = nullptr;
26572     int64_t Offset = 0;
26573
26574     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26575     while (1) {
26576       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26577         Offset += GA->getOffset();
26578         break;
26579       } else if (Op.getOpcode() == ISD::ADD) {
26580         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26581           Offset += C->getZExtValue();
26582           Op = Op.getOperand(0);
26583           continue;
26584         }
26585       } else if (Op.getOpcode() == ISD::SUB) {
26586         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26587           Offset += -C->getZExtValue();
26588           Op = Op.getOperand(0);
26589           continue;
26590         }
26591       }
26592
26593       // Otherwise, this isn't something we can handle, reject it.
26594       return;
26595     }
26596
26597     const GlobalValue *GV = GA->getGlobal();
26598     // If we require an extra load to get this address, as in PIC mode, we
26599     // can't accept it.
26600     if (isGlobalStubReference(
26601             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26602       return;
26603
26604     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26605                                         GA->getValueType(0), Offset);
26606     break;
26607   }
26608   }
26609
26610   if (Result.getNode()) {
26611     Ops.push_back(Result);
26612     return;
26613   }
26614   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26615 }
26616
26617 std::pair<unsigned, const TargetRegisterClass *>
26618 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26619                                                 StringRef Constraint,
26620                                                 MVT VT) const {
26621   // First, see if this is a constraint that directly corresponds to an LLVM
26622   // register class.
26623   if (Constraint.size() == 1) {
26624     // GCC Constraint Letters
26625     switch (Constraint[0]) {
26626     default: break;
26627       // TODO: Slight differences here in allocation order and leaving
26628       // RIP in the class. Do they matter any more here than they do
26629       // in the normal allocation?
26630     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26631       if (Subtarget->is64Bit()) {
26632         if (VT == MVT::i32 || VT == MVT::f32)
26633           return std::make_pair(0U, &X86::GR32RegClass);
26634         if (VT == MVT::i16)
26635           return std::make_pair(0U, &X86::GR16RegClass);
26636         if (VT == MVT::i8 || VT == MVT::i1)
26637           return std::make_pair(0U, &X86::GR8RegClass);
26638         if (VT == MVT::i64 || VT == MVT::f64)
26639           return std::make_pair(0U, &X86::GR64RegClass);
26640         break;
26641       }
26642       // 32-bit fallthrough
26643     case 'Q':   // Q_REGS
26644       if (VT == MVT::i32 || VT == MVT::f32)
26645         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26646       if (VT == MVT::i16)
26647         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26648       if (VT == MVT::i8 || VT == MVT::i1)
26649         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26650       if (VT == MVT::i64)
26651         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26652       break;
26653     case 'r':   // GENERAL_REGS
26654     case 'l':   // INDEX_REGS
26655       if (VT == MVT::i8 || VT == MVT::i1)
26656         return std::make_pair(0U, &X86::GR8RegClass);
26657       if (VT == MVT::i16)
26658         return std::make_pair(0U, &X86::GR16RegClass);
26659       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26660         return std::make_pair(0U, &X86::GR32RegClass);
26661       return std::make_pair(0U, &X86::GR64RegClass);
26662     case 'R':   // LEGACY_REGS
26663       if (VT == MVT::i8 || VT == MVT::i1)
26664         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26665       if (VT == MVT::i16)
26666         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26667       if (VT == MVT::i32 || !Subtarget->is64Bit())
26668         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26669       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26670     case 'f':  // FP Stack registers.
26671       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26672       // value to the correct fpstack register class.
26673       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26674         return std::make_pair(0U, &X86::RFP32RegClass);
26675       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26676         return std::make_pair(0U, &X86::RFP64RegClass);
26677       return std::make_pair(0U, &X86::RFP80RegClass);
26678     case 'y':   // MMX_REGS if MMX allowed.
26679       if (!Subtarget->hasMMX()) break;
26680       return std::make_pair(0U, &X86::VR64RegClass);
26681     case 'Y':   // SSE_REGS if SSE2 allowed
26682       if (!Subtarget->hasSSE2()) break;
26683       // FALL THROUGH.
26684     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26685       if (!Subtarget->hasSSE1()) break;
26686
26687       switch (VT.SimpleTy) {
26688       default: break;
26689       // Scalar SSE types.
26690       case MVT::f32:
26691       case MVT::i32:
26692         return std::make_pair(0U, &X86::FR32RegClass);
26693       case MVT::f64:
26694       case MVT::i64:
26695         return std::make_pair(0U, &X86::FR64RegClass);
26696       // Vector types.
26697       case MVT::v16i8:
26698       case MVT::v8i16:
26699       case MVT::v4i32:
26700       case MVT::v2i64:
26701       case MVT::v4f32:
26702       case MVT::v2f64:
26703         return std::make_pair(0U, &X86::VR128RegClass);
26704       // AVX types.
26705       case MVT::v32i8:
26706       case MVT::v16i16:
26707       case MVT::v8i32:
26708       case MVT::v4i64:
26709       case MVT::v8f32:
26710       case MVT::v4f64:
26711         return std::make_pair(0U, &X86::VR256RegClass);
26712       case MVT::v8f64:
26713       case MVT::v16f32:
26714       case MVT::v16i32:
26715       case MVT::v8i64:
26716         return std::make_pair(0U, &X86::VR512RegClass);
26717       }
26718       break;
26719     }
26720   }
26721
26722   // Use the default implementation in TargetLowering to convert the register
26723   // constraint into a member of a register class.
26724   std::pair<unsigned, const TargetRegisterClass*> Res;
26725   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26726
26727   // Not found as a standard register?
26728   if (!Res.second) {
26729     // Map st(0) -> st(7) -> ST0
26730     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26731         tolower(Constraint[1]) == 's' &&
26732         tolower(Constraint[2]) == 't' &&
26733         Constraint[3] == '(' &&
26734         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26735         Constraint[5] == ')' &&
26736         Constraint[6] == '}') {
26737
26738       Res.first = X86::FP0+Constraint[4]-'0';
26739       Res.second = &X86::RFP80RegClass;
26740       return Res;
26741     }
26742
26743     // GCC allows "st(0)" to be called just plain "st".
26744     if (StringRef("{st}").equals_lower(Constraint)) {
26745       Res.first = X86::FP0;
26746       Res.second = &X86::RFP80RegClass;
26747       return Res;
26748     }
26749
26750     // flags -> EFLAGS
26751     if (StringRef("{flags}").equals_lower(Constraint)) {
26752       Res.first = X86::EFLAGS;
26753       Res.second = &X86::CCRRegClass;
26754       return Res;
26755     }
26756
26757     // 'A' means EAX + EDX.
26758     if (Constraint == "A") {
26759       Res.first = X86::EAX;
26760       Res.second = &X86::GR32_ADRegClass;
26761       return Res;
26762     }
26763     return Res;
26764   }
26765
26766   // Otherwise, check to see if this is a register class of the wrong value
26767   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26768   // turn into {ax},{dx}.
26769   // MVT::Other is used to specify clobber names.
26770   if (Res.second->hasType(VT) || VT == MVT::Other)
26771     return Res;   // Correct type already, nothing to do.
26772
26773   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26774   // return "eax". This should even work for things like getting 64bit integer
26775   // registers when given an f64 type.
26776   const TargetRegisterClass *Class = Res.second;
26777   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26778       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26779     unsigned Size = VT.getSizeInBits();
26780     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26781                                   : Size == 16 ? MVT::i16
26782                                   : Size == 32 ? MVT::i32
26783                                   : Size == 64 ? MVT::i64
26784                                   : MVT::Other;
26785     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26786     if (DestReg > 0) {
26787       Res.first = DestReg;
26788       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26789                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26790                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26791                  : &X86::GR64RegClass;
26792       assert(Res.second->contains(Res.first) && "Register in register class");
26793     } else {
26794       // No register found/type mismatch.
26795       Res.first = 0;
26796       Res.second = nullptr;
26797     }
26798   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26799              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26800              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26801              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26802              Class == &X86::VR512RegClass) {
26803     // Handle references to XMM physical registers that got mapped into the
26804     // wrong class.  This can happen with constraints like {xmm0} where the
26805     // target independent register mapper will just pick the first match it can
26806     // find, ignoring the required type.
26807
26808     if (VT == MVT::f32 || VT == MVT::i32)
26809       Res.second = &X86::FR32RegClass;
26810     else if (VT == MVT::f64 || VT == MVT::i64)
26811       Res.second = &X86::FR64RegClass;
26812     else if (X86::VR128RegClass.hasType(VT))
26813       Res.second = &X86::VR128RegClass;
26814     else if (X86::VR256RegClass.hasType(VT))
26815       Res.second = &X86::VR256RegClass;
26816     else if (X86::VR512RegClass.hasType(VT))
26817       Res.second = &X86::VR512RegClass;
26818     else {
26819       // Type mismatch and not a clobber: Return an error;
26820       Res.first = 0;
26821       Res.second = nullptr;
26822     }
26823   }
26824
26825   return Res;
26826 }
26827
26828 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26829                                             const AddrMode &AM, Type *Ty,
26830                                             unsigned AS) const {
26831   // Scaling factors are not free at all.
26832   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26833   // will take 2 allocations in the out of order engine instead of 1
26834   // for plain addressing mode, i.e. inst (reg1).
26835   // E.g.,
26836   // vaddps (%rsi,%drx), %ymm0, %ymm1
26837   // Requires two allocations (one for the load, one for the computation)
26838   // whereas:
26839   // vaddps (%rsi), %ymm0, %ymm1
26840   // Requires just 1 allocation, i.e., freeing allocations for other operations
26841   // and having less micro operations to execute.
26842   //
26843   // For some X86 architectures, this is even worse because for instance for
26844   // stores, the complex addressing mode forces the instruction to use the
26845   // "load" ports instead of the dedicated "store" port.
26846   // E.g., on Haswell:
26847   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26848   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26849   if (isLegalAddressingMode(DL, AM, Ty, AS))
26850     // Scale represents reg2 * scale, thus account for 1
26851     // as soon as we use a second register.
26852     return AM.Scale != 0;
26853   return -1;
26854 }
26855
26856 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26857   // Integer division on x86 is expensive. However, when aggressively optimizing
26858   // for code size, we prefer to use a div instruction, as it is usually smaller
26859   // than the alternative sequence.
26860   // The exception to this is vector division. Since x86 doesn't have vector
26861   // integer division, leaving the division as-is is a loss even in terms of
26862   // size, because it will have to be scalarized, while the alternative code
26863   // sequence can be performed in vector form.
26864   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26865                                    Attribute::MinSize);
26866   return OptSize && !VT.isVector();
26867 }