Added promotion to EXTRACT_SUBVECTOR operand.
[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 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71     "x86-recip-refinement-steps", cl::init(1),
72     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73              "result of the hardware reciprocal estimate instruction."),
74     cl::NotHidden);
75
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
78                        SDValue V2);
79
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81                                      const X86Subtarget &STI)
82     : TargetLowering(TM), Subtarget(&STI) {
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   TD = getDataLayout();
86
87   // Set up the TargetLowering object.
88   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
89
90   // X86 is weird. It always uses i8 for shift amounts and setcc results.
91   setBooleanContents(ZeroOrOneBooleanContent);
92   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
94
95   // For 64-bit, since we have so many registers, use the ILP scheduler.
96   // For 32-bit, use the register pressure specific scheduling.
97   // For Atom, always use ILP scheduling.
98   if (Subtarget->isAtom())
99     setSchedulingPreference(Sched::ILP);
100   else if (Subtarget->is64Bit())
101     setSchedulingPreference(Sched::ILP);
102   else
103     setSchedulingPreference(Sched::RegPressure);
104   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
106
107   // Bypass expensive divides on Atom when compiling with O2.
108   if (TM.getOptLevel() >= CodeGenOpt::Default) {
109     if (Subtarget->hasSlowDivide32())
110       addBypassSlowDiv(32, 8);
111     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112       addBypassSlowDiv(64, 16);
113   }
114
115   if (Subtarget->isTargetKnownWindowsMSVC()) {
116     // Setup Windows compiler runtime calls.
117     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119     setLibcallName(RTLIB::SREM_I64, "_allrem");
120     setLibcallName(RTLIB::UREM_I64, "_aullrem");
121     setLibcallName(RTLIB::MUL_I64, "_allmul");
122     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
127
128     // The _ftol2 runtime function has an unusual calling conv, which
129     // is modeled by a special pseudo-instruction.
130     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
134   }
135
136   if (Subtarget->isTargetDarwin()) {
137     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138     setUseUnderscoreSetJmp(false);
139     setUseUnderscoreLongJmp(false);
140   } else if (Subtarget->isTargetWindowsGNU()) {
141     // MS runtime is weird: it exports _setjmp, but longjmp!
142     setUseUnderscoreSetJmp(true);
143     setUseUnderscoreLongJmp(false);
144   } else {
145     setUseUnderscoreSetJmp(true);
146     setUseUnderscoreLongJmp(true);
147   }
148
149   // Set up the register classes.
150   addRegisterClass(MVT::i8, &X86::GR8RegClass);
151   addRegisterClass(MVT::i16, &X86::GR16RegClass);
152   addRegisterClass(MVT::i32, &X86::GR32RegClass);
153   if (Subtarget->is64Bit())
154     addRegisterClass(MVT::i64, &X86::GR64RegClass);
155
156   for (MVT VT : MVT::integer_valuetypes())
157     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
158
159   // We don't accept any truncstore of integer registers.
160   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
166
167   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
168
169   // SETOEQ and SETUNE require checking two conditions.
170   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
176
177   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
178   // operation.
179   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
180   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
181   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
182
183   if (Subtarget->is64Bit()) {
184     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
185     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
186   } else if (!Subtarget->useSoftFloat()) {
187     // We have an algorithm for SSE2->double, and we turn this into a
188     // 64-bit FILD followed by conditional FADD for other targets.
189     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
190     // We have an algorithm for SSE2, and we turn this into a 64-bit
191     // FILD for other targets.
192     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
193   }
194
195   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
196   // this operation.
197   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
198   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
199
200   if (!Subtarget->useSoftFloat()) {
201     // SSE has no i16 to fp conversion, only i32
202     if (X86ScalarSSEf32) {
203       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
204       // f32 and f64 cases are Legal, f80 case is not
205       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
206     } else {
207       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
208       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
209     }
210   } else {
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
213   }
214
215   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
216   // are Legal, f80 is custom lowered.
217   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
218   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
219
220   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
221   // this operation.
222   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
224
225   if (X86ScalarSSEf32) {
226     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
227     // f32 and f64 cases are Legal, f80 case is not
228     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
229   } else {
230     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
231     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
232   }
233
234   // Handle FP_TO_UINT by promoting the destination to a larger signed
235   // conversion.
236   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
237   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
238   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
239
240   if (Subtarget->is64Bit()) {
241     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
242     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
243   } else if (!Subtarget->useSoftFloat()) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254   }
255
256   if (isTargetFTOL()) {
257     // Use the _ftol2 runtime function, which has a pseudo-instruction
258     // to handle its weird calling convention.
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
260   }
261
262   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263   if (!X86ScalarSSEf64) {
264     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
265     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
266     if (Subtarget->is64Bit()) {
267       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
268       // Without SSE, i64->f64 goes through memory.
269       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
270     }
271   }
272
273   // Scalar integer divide and remainder are lowered to use operations that
274   // produce two results, to match the available instructions. This exposes
275   // the two-result form to trivial CSE, which is able to combine x/y and x%y
276   // into a single instruction.
277   //
278   // Scalar integer multiply-high is also lowered to use two-result
279   // operations, to match the available instructions. However, plain multiply
280   // (low) operations are left as Legal, as there are single-result
281   // instructions for this in x86. Using the two-result multiply instructions
282   // when both high and low results are needed must be arranged by dagcombine.
283   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
284     MVT VT = IntVTs[i];
285     setOperationAction(ISD::MULHS, VT, Expand);
286     setOperationAction(ISD::MULHU, VT, Expand);
287     setOperationAction(ISD::SDIV, VT, Expand);
288     setOperationAction(ISD::UDIV, VT, Expand);
289     setOperationAction(ISD::SREM, VT, Expand);
290     setOperationAction(ISD::UREM, VT, Expand);
291
292     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293     setOperationAction(ISD::ADDC, VT, Custom);
294     setOperationAction(ISD::ADDE, VT, Custom);
295     setOperationAction(ISD::SUBC, VT, Custom);
296     setOperationAction(ISD::SUBE, VT, Custom);
297   }
298
299   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
300   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
301   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
306   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
307   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
314   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
315   if (Subtarget->is64Bit())
316     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
319   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
320   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->is64Bit()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502     // TargetInfo::X86_64ABIBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!Subtarget->useSoftFloat()) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!Subtarget->useSoftFloat()) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753
754       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755       // split/scalarized right now.
756       if (VT.getVectorElementType() == MVT::f16)
757         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
758     }
759   }
760
761   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762   // with -msoft-float, disable use of MMX as well.
763   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765     // No operations on x86mmx supported, everything uses intrinsics.
766   }
767
768   // MMX-sized vectors (other than x86mmx) are expected to be expanded
769   // into smaller operations.
770   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
772     setOperationAction(ISD::AND,                MMXTy,      Expand);
773     setOperationAction(ISD::OR,                 MMXTy,      Expand);
774     setOperationAction(ISD::XOR,                MMXTy,      Expand);
775     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
776     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
777     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
778   }
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780
781   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783
784     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
788     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
789     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
790     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
791     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
793     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
794     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
797     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
798   }
799
800   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802
803     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804     // registers cannot be used even for integer operations.
805     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809
810     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
811     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
812     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
813     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
815     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
819     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
820     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
833
834     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
838
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
844
845     // Only provide customized ctpop vector bit twiddling for vector types we
846     // know to perform better than using the popcnt instructions on each vector
847     // element. If popcnt isn't supported, always provide the custom version.
848     if (!Subtarget->hasPOPCNT()) {
849       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
850       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
851     }
852
853     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
854     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
855       MVT VT = (MVT::SimpleValueType)i;
856       // Do not attempt to custom lower non-power-of-2 vectors
857       if (!isPowerOf2_32(VT.getVectorNumElements()))
858         continue;
859       // Do not attempt to custom lower non-128-bit vectors
860       if (!VT.is128BitVector())
861         continue;
862       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
863       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
864       setOperationAction(ISD::VSELECT,            VT, Custom);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866     }
867
868     // We support custom legalizing of sext and anyext loads for specific
869     // memory vector types which we can load as a scalar (or sequence of
870     // scalars) and extend in-register to a legal 128-bit vector type. For sext
871     // loads these must work with a single scalar load.
872     for (MVT VT : MVT::integer_vector_valuetypes()) {
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882     }
883
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
889     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900       MVT VT = (MVT::SimpleValueType)i;
901
902       // Do not attempt to promote non-128-bit vectors
903       if (!VT.is128BitVector())
904         continue;
905
906       setOperationAction(ISD::AND,    VT, Promote);
907       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
908       setOperationAction(ISD::OR,     VT, Promote);
909       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
910       setOperationAction(ISD::XOR,    VT, Promote);
911       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
912       setOperationAction(ISD::LOAD,   VT, Promote);
913       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
914       setOperationAction(ISD::SELECT, VT, Promote);
915       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916     }
917
918     // Custom lower v2i64 and v2f64 selects.
919     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
920     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
921     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
923
924     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     // FIXME: Do we need to handle scalar-to-vector here?
955     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
956
957     // We directly match byte blends in the backend as they match the VSELECT
958     // condition form.
959     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
960
961     // SSE41 brings specific instructions for doing vector sign extend even in
962     // cases where we don't have SRA.
963     for (MVT VT : MVT::integer_vector_valuetypes()) {
964       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
965       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
966       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
967     }
968
969     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
971     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
972     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
976
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     // i8 and i16 vectors are custom because the source register and source
985     // source memory operand types are not the same width.  f32 vectors are
986     // custom since the immediate controlling the insert encodes additional
987     // information.
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
992
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
997
998     // FIXME: these should be Legal, but that's only for the case where
999     // the index is constant.  For now custom expand to deal with that.
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE2()) {
1007     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1008     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1009     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1010
1011     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1012     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1013
1014     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1015     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1016
1017     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1018     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1019
1020     // In the customized shift lowering, the legal cases in AVX2 will be
1021     // recognized.
1022     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1023     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1024
1025     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1026     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1027
1028     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1029   }
1030
1031   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1032     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1035     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1036     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1038
1039     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1042
1043     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1051     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1053     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1054     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1055
1056     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1057     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1059     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1060     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1062     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1063     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1064     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1066     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1067     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1068
1069     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1070     // even though v8i16 is a legal type.
1071     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1073     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1074
1075     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1076     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1077     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1078
1079     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1080     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1081
1082     for (MVT VT : MVT::fp_vector_valuetypes())
1083       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1084
1085     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1086     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1087
1088     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1089     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1090
1091     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1092     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1093
1094     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1095     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1096     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1097     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1098
1099     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1100     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1101     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1102
1103     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1104     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1105     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1106     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1107     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1108     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1109     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1110     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1111     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1112     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1113     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1114     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1115
1116     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1117       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1118       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1119       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1120       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1121       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1122       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1123     }
1124
1125     if (Subtarget->hasInt256()) {
1126       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1127       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1128       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1129       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1130
1131       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1132       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1133       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1134       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1135
1136       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1137       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1138       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1139       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1140
1141       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1142       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1143       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1144       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1145
1146       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1147       // when we have a 256bit-wide blend with immediate.
1148       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1149
1150       // Only provide customized ctpop vector bit twiddling for vector types we
1151       // know to perform better than using the popcnt instructions on each
1152       // vector element. If popcnt isn't supported, always provide the custom
1153       // version.
1154       if (!Subtarget->hasPOPCNT())
1155         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1156
1157       // Custom CTPOP always performs better on natively supported v8i32
1158       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1159
1160       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1161       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1162       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1163       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1164       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1165       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1166       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1167
1168       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1169       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1170       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1171       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1172       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1173       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1174     } else {
1175       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1176       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1177       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1178       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1179
1180       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1181       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1182       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1183       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1184
1185       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1186       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1187       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1188       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1189     }
1190
1191     // In the customized shift lowering, the legal cases in AVX2 will be
1192     // recognized.
1193     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1194     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1195
1196     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1197     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1198
1199     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1200
1201     // Custom lower several nodes for 256-bit types.
1202     for (MVT VT : MVT::vector_valuetypes()) {
1203       if (VT.getScalarSizeInBits() >= 32) {
1204         setOperationAction(ISD::MLOAD,  VT, Legal);
1205         setOperationAction(ISD::MSTORE, VT, Legal);
1206       }
1207       // Extract subvector is special because the value type
1208       // (result) is 128-bit but the source is 256-bit wide.
1209       if (VT.is128BitVector()) {
1210         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1211       }
1212       // Do not attempt to custom lower other non-256-bit vectors
1213       if (!VT.is256BitVector())
1214         continue;
1215
1216       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1217       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1218       setOperationAction(ISD::VSELECT,            VT, Custom);
1219       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1220       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1221       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1222       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1223       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1224     }
1225
1226     if (Subtarget->hasInt256())
1227       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1228
1229
1230     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1231     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1232       MVT VT = (MVT::SimpleValueType)i;
1233
1234       // Do not attempt to promote non-256-bit vectors
1235       if (!VT.is256BitVector())
1236         continue;
1237
1238       setOperationAction(ISD::AND,    VT, Promote);
1239       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1240       setOperationAction(ISD::OR,     VT, Promote);
1241       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1242       setOperationAction(ISD::XOR,    VT, Promote);
1243       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1244       setOperationAction(ISD::LOAD,   VT, Promote);
1245       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1246       setOperationAction(ISD::SELECT, VT, Promote);
1247       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1248     }
1249   }
1250
1251   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1252     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1253     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1254     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1255     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1256
1257     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1258     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1259     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1260
1261     for (MVT VT : MVT::fp_vector_valuetypes())
1262       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1263
1264     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1265     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1266     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1267     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1268     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1269     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1270     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1271     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1272     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1273     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1274
1275     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1276     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1277     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1278     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1279     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1280     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1281
1282     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1283     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1284     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1285     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1286     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1287     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1288     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1289     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1290
1291     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1292     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1293     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1294     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1295     if (Subtarget->is64Bit()) {
1296       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1297       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1298       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1299       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1300     }
1301     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1302     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1303     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1304     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1305     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1306     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1307     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1308     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1309     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1310     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1311     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1312     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1313     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1314     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1315     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1316     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1317
1318     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1319     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1320     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1321     if (Subtarget->hasDQI()) {
1322       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1323       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1324     }
1325     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1326     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1327     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1328     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1329     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1330     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1331     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1332     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1333     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1334     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1335     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1336     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1337     if (Subtarget->hasDQI()) {
1338       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1339       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1340     }
1341     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1342     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1343     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1344     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1346     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1347     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1348     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1349     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1350     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1351
1352     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1353     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1354     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1355     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1356     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1357
1358     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1359     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1360
1361     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1362
1363     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1364     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1365     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1366     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1367     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1368     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1370     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1371     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1372     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1373     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1374
1375     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1376     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1377
1378     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1379     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1380
1381     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1382
1383     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1384     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1385
1386     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1387     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1388
1389     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1390     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1391
1392     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1393     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1394     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1395     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1396     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1397     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1398
1399     if (Subtarget->hasCDI()) {
1400       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1401       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1402     }
1403     if (Subtarget->hasDQI()) {
1404       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1405       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1406       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1407     }
1408     // Custom lower several nodes.
1409     for (MVT VT : MVT::vector_valuetypes()) {
1410       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1411       if (EltSize == 1) {
1412         setOperationAction(ISD::AND, VT, Legal);
1413         setOperationAction(ISD::OR,  VT, Legal);
1414         setOperationAction(ISD::XOR,  VT, Legal);
1415       }
1416       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1417         setOperationAction(ISD::MGATHER,  VT, Custom);
1418         setOperationAction(ISD::MSCATTER, VT, Custom);
1419       }
1420       // Extract subvector is special because the value type
1421       // (result) is 256/128-bit but the source is 512-bit wide.
1422       if (VT.is128BitVector() || VT.is256BitVector()) {
1423         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1424       }
1425       if (VT.getVectorElementType() == MVT::i1)
1426         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1427
1428       // Do not attempt to custom lower other non-512-bit vectors
1429       if (!VT.is512BitVector())
1430         continue;
1431
1432       if (EltSize >= 32) {
1433         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1434         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1435         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1436         setOperationAction(ISD::VSELECT,             VT, Legal);
1437         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1438         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1439         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1440         setOperationAction(ISD::MLOAD,               VT, Legal);
1441         setOperationAction(ISD::MSTORE,              VT, Legal);
1442       }
1443     }
1444     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1445       MVT VT = (MVT::SimpleValueType)i;
1446
1447       // Do not attempt to promote non-512-bit vectors.
1448       if (!VT.is512BitVector())
1449         continue;
1450
1451       setOperationAction(ISD::SELECT, VT, Promote);
1452       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1453     }
1454   }// has  AVX-512
1455
1456   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1457     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1458     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1459
1460     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1461     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1462
1463     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1464     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1465     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1466     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1467     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1468     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1469     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1470     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1471     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1474     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1475     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1476     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1477     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1478     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1479     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1480     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1481     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1482     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1483     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1484     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1485     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1486
1487     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1488       const MVT VT = (MVT::SimpleValueType)i;
1489
1490       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1491
1492       // Do not attempt to promote non-512-bit vectors.
1493       if (!VT.is512BitVector())
1494         continue;
1495
1496       if (EltSize < 32) {
1497         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1498         setOperationAction(ISD::VSELECT,             VT, Legal);
1499       }
1500     }
1501   }
1502
1503   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1504     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1505     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1506
1507     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1508     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1509     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1510     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1511     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1512     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1513     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1514     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1515     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1516     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1517
1518     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1519     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1520     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1521     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1522     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1523     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1524     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1525     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1526   }
1527
1528   // We want to custom lower some of our intrinsics.
1529   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1530   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1531   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1532   if (!Subtarget->is64Bit())
1533     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1534
1535   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1536   // handle type legalization for these operations here.
1537   //
1538   // FIXME: We really should do custom legalization for addition and
1539   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1540   // than generic legalization for 64-bit multiplication-with-overflow, though.
1541   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1542     // Add/Sub/Mul with overflow operations are custom lowered.
1543     MVT VT = IntVTs[i];
1544     setOperationAction(ISD::SADDO, VT, Custom);
1545     setOperationAction(ISD::UADDO, VT, Custom);
1546     setOperationAction(ISD::SSUBO, VT, Custom);
1547     setOperationAction(ISD::USUBO, VT, Custom);
1548     setOperationAction(ISD::SMULO, VT, Custom);
1549     setOperationAction(ISD::UMULO, VT, Custom);
1550   }
1551
1552
1553   if (!Subtarget->is64Bit()) {
1554     // These libcalls are not available in 32-bit.
1555     setLibcallName(RTLIB::SHL_I128, nullptr);
1556     setLibcallName(RTLIB::SRL_I128, nullptr);
1557     setLibcallName(RTLIB::SRA_I128, nullptr);
1558   }
1559
1560   // Combine sin / cos into one node or libcall if possible.
1561   if (Subtarget->hasSinCos()) {
1562     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1563     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1564     if (Subtarget->isTargetDarwin()) {
1565       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1566       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1567       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1568       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1569     }
1570   }
1571
1572   if (Subtarget->isTargetWin64()) {
1573     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1574     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1575     setOperationAction(ISD::SREM, MVT::i128, Custom);
1576     setOperationAction(ISD::UREM, MVT::i128, Custom);
1577     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1578     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1579   }
1580
1581   // We have target-specific dag combine patterns for the following nodes:
1582   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1583   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1584   setTargetDAGCombine(ISD::BITCAST);
1585   setTargetDAGCombine(ISD::VSELECT);
1586   setTargetDAGCombine(ISD::SELECT);
1587   setTargetDAGCombine(ISD::SHL);
1588   setTargetDAGCombine(ISD::SRA);
1589   setTargetDAGCombine(ISD::SRL);
1590   setTargetDAGCombine(ISD::OR);
1591   setTargetDAGCombine(ISD::AND);
1592   setTargetDAGCombine(ISD::ADD);
1593   setTargetDAGCombine(ISD::FADD);
1594   setTargetDAGCombine(ISD::FSUB);
1595   setTargetDAGCombine(ISD::FMA);
1596   setTargetDAGCombine(ISD::SUB);
1597   setTargetDAGCombine(ISD::LOAD);
1598   setTargetDAGCombine(ISD::MLOAD);
1599   setTargetDAGCombine(ISD::STORE);
1600   setTargetDAGCombine(ISD::MSTORE);
1601   setTargetDAGCombine(ISD::ZERO_EXTEND);
1602   setTargetDAGCombine(ISD::ANY_EXTEND);
1603   setTargetDAGCombine(ISD::SIGN_EXTEND);
1604   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1605   setTargetDAGCombine(ISD::SINT_TO_FP);
1606   setTargetDAGCombine(ISD::SETCC);
1607   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1608   setTargetDAGCombine(ISD::BUILD_VECTOR);
1609   setTargetDAGCombine(ISD::MUL);
1610   setTargetDAGCombine(ISD::XOR);
1611
1612   computeRegisterProperties(Subtarget->getRegisterInfo());
1613
1614   // On Darwin, -Os means optimize for size without hurting performance,
1615   // do not reduce the limit.
1616   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1617   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1618   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1619   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1620   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1621   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1622   setPrefLoopAlignment(4); // 2^4 bytes.
1623
1624   // Predictable cmov don't hurt on atom because it's in-order.
1625   PredictableSelectIsExpensive = !Subtarget->isAtom();
1626   EnableExtLdPromotion = true;
1627   setPrefFunctionAlignment(4); // 2^4 bytes.
1628
1629   verifyIntrinsicTables();
1630 }
1631
1632 // This has so far only been implemented for 64-bit MachO.
1633 bool X86TargetLowering::useLoadStackGuardNode() const {
1634   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1635 }
1636
1637 TargetLoweringBase::LegalizeTypeAction
1638 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1639   if (ExperimentalVectorWideningLegalization &&
1640       VT.getVectorNumElements() != 1 &&
1641       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1642     return TypeWidenVector;
1643
1644   return TargetLoweringBase::getPreferredVectorAction(VT);
1645 }
1646
1647 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1648   if (!VT.isVector())
1649     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1650
1651   const unsigned NumElts = VT.getVectorNumElements();
1652   const EVT EltVT = VT.getVectorElementType();
1653   if (VT.is512BitVector()) {
1654     if (Subtarget->hasAVX512())
1655       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1656           EltVT == MVT::f32 || EltVT == MVT::f64)
1657         switch(NumElts) {
1658         case  8: return MVT::v8i1;
1659         case 16: return MVT::v16i1;
1660       }
1661     if (Subtarget->hasBWI())
1662       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1663         switch(NumElts) {
1664         case 32: return MVT::v32i1;
1665         case 64: return MVT::v64i1;
1666       }
1667   }
1668
1669   if (VT.is256BitVector() || VT.is128BitVector()) {
1670     if (Subtarget->hasVLX())
1671       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1672           EltVT == MVT::f32 || EltVT == MVT::f64)
1673         switch(NumElts) {
1674         case 2: return MVT::v2i1;
1675         case 4: return MVT::v4i1;
1676         case 8: return MVT::v8i1;
1677       }
1678     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1679       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1680         switch(NumElts) {
1681         case  8: return MVT::v8i1;
1682         case 16: return MVT::v16i1;
1683         case 32: return MVT::v32i1;
1684       }
1685   }
1686
1687   return VT.changeVectorElementTypeToInteger();
1688 }
1689
1690 /// Helper for getByValTypeAlignment to determine
1691 /// the desired ByVal argument alignment.
1692 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1693   if (MaxAlign == 16)
1694     return;
1695   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1696     if (VTy->getBitWidth() == 128)
1697       MaxAlign = 16;
1698   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1699     unsigned EltAlign = 0;
1700     getMaxByValAlign(ATy->getElementType(), EltAlign);
1701     if (EltAlign > MaxAlign)
1702       MaxAlign = EltAlign;
1703   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1704     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1705       unsigned EltAlign = 0;
1706       getMaxByValAlign(STy->getElementType(i), EltAlign);
1707       if (EltAlign > MaxAlign)
1708         MaxAlign = EltAlign;
1709       if (MaxAlign == 16)
1710         break;
1711     }
1712   }
1713 }
1714
1715 /// Return the desired alignment for ByVal aggregate
1716 /// function arguments in the caller parameter area. For X86, aggregates
1717 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1718 /// are at 4-byte boundaries.
1719 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1720   if (Subtarget->is64Bit()) {
1721     // Max of 8 and alignment of type.
1722     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1723     if (TyAlign > 8)
1724       return TyAlign;
1725     return 8;
1726   }
1727
1728   unsigned Align = 4;
1729   if (Subtarget->hasSSE1())
1730     getMaxByValAlign(Ty, Align);
1731   return Align;
1732 }
1733
1734 /// Returns the target specific optimal type for load
1735 /// and store operations as a result of memset, memcpy, and memmove
1736 /// lowering. If DstAlign is zero that means it's safe to destination
1737 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1738 /// means there isn't a need to check it against alignment requirement,
1739 /// probably because the source does not need to be loaded. If 'IsMemset' is
1740 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1741 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1742 /// source is constant so it does not need to be loaded.
1743 /// It returns EVT::Other if the type should be determined using generic
1744 /// target-independent logic.
1745 EVT
1746 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1747                                        unsigned DstAlign, unsigned SrcAlign,
1748                                        bool IsMemset, bool ZeroMemset,
1749                                        bool MemcpyStrSrc,
1750                                        MachineFunction &MF) const {
1751   const Function *F = MF.getFunction();
1752   if ((!IsMemset || ZeroMemset) &&
1753       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1754     if (Size >= 16 &&
1755         (Subtarget->isUnalignedMemAccessFast() ||
1756          ((DstAlign == 0 || DstAlign >= 16) &&
1757           (SrcAlign == 0 || SrcAlign >= 16)))) {
1758       if (Size >= 32) {
1759         if (Subtarget->hasInt256())
1760           return MVT::v8i32;
1761         if (Subtarget->hasFp256())
1762           return MVT::v8f32;
1763       }
1764       if (Subtarget->hasSSE2())
1765         return MVT::v4i32;
1766       if (Subtarget->hasSSE1())
1767         return MVT::v4f32;
1768     } else if (!MemcpyStrSrc && Size >= 8 &&
1769                !Subtarget->is64Bit() &&
1770                Subtarget->hasSSE2()) {
1771       // Do not use f64 to lower memcpy if source is string constant. It's
1772       // better to use i32 to avoid the loads.
1773       return MVT::f64;
1774     }
1775   }
1776   if (Subtarget->is64Bit() && Size >= 8)
1777     return MVT::i64;
1778   return MVT::i32;
1779 }
1780
1781 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1782   if (VT == MVT::f32)
1783     return X86ScalarSSEf32;
1784   else if (VT == MVT::f64)
1785     return X86ScalarSSEf64;
1786   return true;
1787 }
1788
1789 bool
1790 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1791                                                   unsigned,
1792                                                   unsigned,
1793                                                   bool *Fast) const {
1794   if (Fast)
1795     *Fast = Subtarget->isUnalignedMemAccessFast();
1796   return true;
1797 }
1798
1799 /// Return the entry encoding for a jump table in the
1800 /// current function.  The returned value is a member of the
1801 /// MachineJumpTableInfo::JTEntryKind enum.
1802 unsigned X86TargetLowering::getJumpTableEncoding() const {
1803   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1804   // symbol.
1805   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1806       Subtarget->isPICStyleGOT())
1807     return MachineJumpTableInfo::EK_Custom32;
1808
1809   // Otherwise, use the normal jump table encoding heuristics.
1810   return TargetLowering::getJumpTableEncoding();
1811 }
1812
1813 bool X86TargetLowering::useSoftFloat() const {
1814   return Subtarget->useSoftFloat();
1815 }
1816
1817 const MCExpr *
1818 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1819                                              const MachineBasicBlock *MBB,
1820                                              unsigned uid,MCContext &Ctx) const{
1821   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1822          Subtarget->isPICStyleGOT());
1823   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1824   // entries.
1825   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1826                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1827 }
1828
1829 /// Returns relocation base for the given PIC jumptable.
1830 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1831                                                     SelectionDAG &DAG) const {
1832   if (!Subtarget->is64Bit())
1833     // This doesn't have SDLoc associated with it, but is not really the
1834     // same as a Register.
1835     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1836   return Table;
1837 }
1838
1839 /// This returns the relocation base for the given PIC jumptable,
1840 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1841 const MCExpr *X86TargetLowering::
1842 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1843                              MCContext &Ctx) const {
1844   // X86-64 uses RIP relative addressing based on the jump table label.
1845   if (Subtarget->isPICStyleRIPRel())
1846     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1847
1848   // Otherwise, the reference is relative to the PIC base.
1849   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1850 }
1851
1852 std::pair<const TargetRegisterClass *, uint8_t>
1853 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1854                                            MVT VT) const {
1855   const TargetRegisterClass *RRC = nullptr;
1856   uint8_t Cost = 1;
1857   switch (VT.SimpleTy) {
1858   default:
1859     return TargetLowering::findRepresentativeClass(TRI, VT);
1860   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1861     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1862     break;
1863   case MVT::x86mmx:
1864     RRC = &X86::VR64RegClass;
1865     break;
1866   case MVT::f32: case MVT::f64:
1867   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1868   case MVT::v4f32: case MVT::v2f64:
1869   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1870   case MVT::v4f64:
1871     RRC = &X86::VR128RegClass;
1872     break;
1873   }
1874   return std::make_pair(RRC, Cost);
1875 }
1876
1877 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1878                                                unsigned &Offset) const {
1879   if (!Subtarget->isTargetLinux())
1880     return false;
1881
1882   if (Subtarget->is64Bit()) {
1883     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1884     Offset = 0x28;
1885     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1886       AddressSpace = 256;
1887     else
1888       AddressSpace = 257;
1889   } else {
1890     // %gs:0x14 on i386
1891     Offset = 0x14;
1892     AddressSpace = 256;
1893   }
1894   return true;
1895 }
1896
1897 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1898                                             unsigned DestAS) const {
1899   assert(SrcAS != DestAS && "Expected different address spaces!");
1900
1901   return SrcAS < 256 && DestAS < 256;
1902 }
1903
1904 //===----------------------------------------------------------------------===//
1905 //               Return Value Calling Convention Implementation
1906 //===----------------------------------------------------------------------===//
1907
1908 #include "X86GenCallingConv.inc"
1909
1910 bool
1911 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1912                                   MachineFunction &MF, bool isVarArg,
1913                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1914                         LLVMContext &Context) const {
1915   SmallVector<CCValAssign, 16> RVLocs;
1916   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1917   return CCInfo.CheckReturn(Outs, RetCC_X86);
1918 }
1919
1920 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1921   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1922   return ScratchRegs;
1923 }
1924
1925 SDValue
1926 X86TargetLowering::LowerReturn(SDValue Chain,
1927                                CallingConv::ID CallConv, bool isVarArg,
1928                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1929                                const SmallVectorImpl<SDValue> &OutVals,
1930                                SDLoc dl, SelectionDAG &DAG) const {
1931   MachineFunction &MF = DAG.getMachineFunction();
1932   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1933
1934   SmallVector<CCValAssign, 16> RVLocs;
1935   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1936   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1937
1938   SDValue Flag;
1939   SmallVector<SDValue, 6> RetOps;
1940   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1941   // Operand #1 = Bytes To Pop
1942   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1943                    MVT::i16));
1944
1945   // Copy the result values into the output registers.
1946   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1947     CCValAssign &VA = RVLocs[i];
1948     assert(VA.isRegLoc() && "Can only return in registers!");
1949     SDValue ValToCopy = OutVals[i];
1950     EVT ValVT = ValToCopy.getValueType();
1951
1952     // Promote values to the appropriate types.
1953     if (VA.getLocInfo() == CCValAssign::SExt)
1954       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1955     else if (VA.getLocInfo() == CCValAssign::ZExt)
1956       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1957     else if (VA.getLocInfo() == CCValAssign::AExt) {
1958       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1959         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1960       else
1961         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1962     }
1963     else if (VA.getLocInfo() == CCValAssign::BCvt)
1964       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1965
1966     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1967            "Unexpected FP-extend for return value.");
1968
1969     // If this is x86-64, and we disabled SSE, we can't return FP values,
1970     // or SSE or MMX vectors.
1971     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1972          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1973           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1974       report_fatal_error("SSE register return with SSE disabled");
1975     }
1976     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1977     // llvm-gcc has never done it right and no one has noticed, so this
1978     // should be OK for now.
1979     if (ValVT == MVT::f64 &&
1980         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1981       report_fatal_error("SSE2 register return with SSE2 disabled");
1982
1983     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1984     // the RET instruction and handled by the FP Stackifier.
1985     if (VA.getLocReg() == X86::FP0 ||
1986         VA.getLocReg() == X86::FP1) {
1987       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1988       // change the value to the FP stack register class.
1989       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1990         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1991       RetOps.push_back(ValToCopy);
1992       // Don't emit a copytoreg.
1993       continue;
1994     }
1995
1996     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1997     // which is returned in RAX / RDX.
1998     if (Subtarget->is64Bit()) {
1999       if (ValVT == MVT::x86mmx) {
2000         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2001           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2002           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2003                                   ValToCopy);
2004           // If we don't have SSE2 available, convert to v4f32 so the generated
2005           // register is legal.
2006           if (!Subtarget->hasSSE2())
2007             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2008         }
2009       }
2010     }
2011
2012     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2013     Flag = Chain.getValue(1);
2014     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2015   }
2016
2017   // All x86 ABIs require that for returning structs by value we copy
2018   // the sret argument into %rax/%eax (depending on ABI) for the return.
2019   // We saved the argument into a virtual register in the entry block,
2020   // so now we copy the value out and into %rax/%eax.
2021   //
2022   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2023   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2024   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2025   // either case FuncInfo->setSRetReturnReg() will have been called.
2026   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2027     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2028
2029     unsigned RetValReg
2030         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2031           X86::RAX : X86::EAX;
2032     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2033     Flag = Chain.getValue(1);
2034
2035     // RAX/EAX now acts like a return value.
2036     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2037   }
2038
2039   RetOps[0] = Chain;  // Update chain.
2040
2041   // Add the flag if we have it.
2042   if (Flag.getNode())
2043     RetOps.push_back(Flag);
2044
2045   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2046 }
2047
2048 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2049   if (N->getNumValues() != 1)
2050     return false;
2051   if (!N->hasNUsesOfValue(1, 0))
2052     return false;
2053
2054   SDValue TCChain = Chain;
2055   SDNode *Copy = *N->use_begin();
2056   if (Copy->getOpcode() == ISD::CopyToReg) {
2057     // If the copy has a glue operand, we conservatively assume it isn't safe to
2058     // perform a tail call.
2059     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2060       return false;
2061     TCChain = Copy->getOperand(0);
2062   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2063     return false;
2064
2065   bool HasRet = false;
2066   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2067        UI != UE; ++UI) {
2068     if (UI->getOpcode() != X86ISD::RET_FLAG)
2069       return false;
2070     // If we are returning more than one value, we can definitely
2071     // not make a tail call see PR19530
2072     if (UI->getNumOperands() > 4)
2073       return false;
2074     if (UI->getNumOperands() == 4 &&
2075         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2076       return false;
2077     HasRet = true;
2078   }
2079
2080   if (!HasRet)
2081     return false;
2082
2083   Chain = TCChain;
2084   return true;
2085 }
2086
2087 EVT
2088 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2089                                             ISD::NodeType ExtendKind) const {
2090   MVT ReturnMVT;
2091   // TODO: Is this also valid on 32-bit?
2092   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2093     ReturnMVT = MVT::i8;
2094   else
2095     ReturnMVT = MVT::i32;
2096
2097   EVT MinVT = getRegisterType(Context, ReturnMVT);
2098   return VT.bitsLT(MinVT) ? MinVT : VT;
2099 }
2100
2101 /// Lower the result values of a call into the
2102 /// appropriate copies out of appropriate physical registers.
2103 ///
2104 SDValue
2105 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2106                                    CallingConv::ID CallConv, bool isVarArg,
2107                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2108                                    SDLoc dl, SelectionDAG &DAG,
2109                                    SmallVectorImpl<SDValue> &InVals) const {
2110
2111   // Assign locations to each value returned by this call.
2112   SmallVector<CCValAssign, 16> RVLocs;
2113   bool Is64Bit = Subtarget->is64Bit();
2114   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2115                  *DAG.getContext());
2116   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2117
2118   // Copy all of the result registers out of their specified physreg.
2119   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2120     CCValAssign &VA = RVLocs[i];
2121     EVT CopyVT = VA.getLocVT();
2122
2123     // If this is x86-64, and we disabled SSE, we can't return FP values
2124     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2125         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2126       report_fatal_error("SSE register return with SSE disabled");
2127     }
2128
2129     // If we prefer to use the value in xmm registers, copy it out as f80 and
2130     // use a truncate to move it from fp stack reg to xmm reg.
2131     bool RoundAfterCopy = false;
2132     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2133         isScalarFPTypeInSSEReg(VA.getValVT())) {
2134       CopyVT = MVT::f80;
2135       RoundAfterCopy = (CopyVT != VA.getLocVT());
2136     }
2137
2138     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2139                                CopyVT, InFlag).getValue(1);
2140     SDValue Val = Chain.getValue(0);
2141
2142     if (RoundAfterCopy)
2143       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2144                         // This truncation won't change the value.
2145                         DAG.getIntPtrConstant(1, dl));
2146
2147     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2148       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2149
2150     InFlag = Chain.getValue(2);
2151     InVals.push_back(Val);
2152   }
2153
2154   return Chain;
2155 }
2156
2157 //===----------------------------------------------------------------------===//
2158 //                C & StdCall & Fast Calling Convention implementation
2159 //===----------------------------------------------------------------------===//
2160 //  StdCall calling convention seems to be standard for many Windows' API
2161 //  routines and around. It differs from C calling convention just a little:
2162 //  callee should clean up the stack, not caller. Symbols should be also
2163 //  decorated in some fancy way :) It doesn't support any vector arguments.
2164 //  For info on fast calling convention see Fast Calling Convention (tail call)
2165 //  implementation LowerX86_32FastCCCallTo.
2166
2167 /// CallIsStructReturn - Determines whether a call uses struct return
2168 /// semantics.
2169 enum StructReturnType {
2170   NotStructReturn,
2171   RegStructReturn,
2172   StackStructReturn
2173 };
2174 static StructReturnType
2175 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2176   if (Outs.empty())
2177     return NotStructReturn;
2178
2179   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2180   if (!Flags.isSRet())
2181     return NotStructReturn;
2182   if (Flags.isInReg())
2183     return RegStructReturn;
2184   return StackStructReturn;
2185 }
2186
2187 /// Determines whether a function uses struct return semantics.
2188 static StructReturnType
2189 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2190   if (Ins.empty())
2191     return NotStructReturn;
2192
2193   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2194   if (!Flags.isSRet())
2195     return NotStructReturn;
2196   if (Flags.isInReg())
2197     return RegStructReturn;
2198   return StackStructReturn;
2199 }
2200
2201 /// Make a copy of an aggregate at address specified by "Src" to address
2202 /// "Dst" with size and alignment information specified by the specific
2203 /// parameter attribute. The copy will be passed as a byval function parameter.
2204 static SDValue
2205 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2206                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2207                           SDLoc dl) {
2208   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2209
2210   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2211                        /*isVolatile*/false, /*AlwaysInline=*/true,
2212                        /*isTailCall*/false,
2213                        MachinePointerInfo(), MachinePointerInfo());
2214 }
2215
2216 /// Return true if the calling convention is one that
2217 /// supports tail call optimization.
2218 static bool IsTailCallConvention(CallingConv::ID CC) {
2219   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2220           CC == CallingConv::HiPE);
2221 }
2222
2223 /// \brief Return true if the calling convention is a C calling convention.
2224 static bool IsCCallConvention(CallingConv::ID CC) {
2225   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2226           CC == CallingConv::X86_64_SysV);
2227 }
2228
2229 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2230   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2231     return false;
2232
2233   CallSite CS(CI);
2234   CallingConv::ID CalleeCC = CS.getCallingConv();
2235   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2236     return false;
2237
2238   return true;
2239 }
2240
2241 /// Return true if the function is being made into
2242 /// a tailcall target by changing its ABI.
2243 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2244                                    bool GuaranteedTailCallOpt) {
2245   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2246 }
2247
2248 SDValue
2249 X86TargetLowering::LowerMemArgument(SDValue Chain,
2250                                     CallingConv::ID CallConv,
2251                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2252                                     SDLoc dl, SelectionDAG &DAG,
2253                                     const CCValAssign &VA,
2254                                     MachineFrameInfo *MFI,
2255                                     unsigned i) const {
2256   // Create the nodes corresponding to a load from this parameter slot.
2257   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2258   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2259       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2260   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2261   EVT ValVT;
2262
2263   // If value is passed by pointer we have address passed instead of the value
2264   // itself.
2265   bool ExtendedInMem = VA.isExtInLoc() &&
2266     VA.getValVT().getScalarType() == MVT::i1;
2267
2268   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2269     ValVT = VA.getLocVT();
2270   else
2271     ValVT = VA.getValVT();
2272
2273   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2274   // changed with more analysis.
2275   // In case of tail call optimization mark all arguments mutable. Since they
2276   // could be overwritten by lowering of arguments in case of a tail call.
2277   if (Flags.isByVal()) {
2278     unsigned Bytes = Flags.getByValSize();
2279     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2280     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2281     return DAG.getFrameIndex(FI, getPointerTy());
2282   } else {
2283     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2284                                     VA.getLocMemOffset(), isImmutable);
2285     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2286     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2287                                MachinePointerInfo::getFixedStack(FI),
2288                                false, false, false, 0);
2289     return ExtendedInMem ?
2290       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2291   }
2292 }
2293
2294 // FIXME: Get this from tablegen.
2295 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2296                                                 const X86Subtarget *Subtarget) {
2297   assert(Subtarget->is64Bit());
2298
2299   if (Subtarget->isCallingConvWin64(CallConv)) {
2300     static const MCPhysReg GPR64ArgRegsWin64[] = {
2301       X86::RCX, X86::RDX, X86::R8,  X86::R9
2302     };
2303     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2304   }
2305
2306   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2307     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2308   };
2309   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2310 }
2311
2312 // FIXME: Get this from tablegen.
2313 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2314                                                 CallingConv::ID CallConv,
2315                                                 const X86Subtarget *Subtarget) {
2316   assert(Subtarget->is64Bit());
2317   if (Subtarget->isCallingConvWin64(CallConv)) {
2318     // The XMM registers which might contain var arg parameters are shadowed
2319     // in their paired GPR.  So we only need to save the GPR to their home
2320     // slots.
2321     // TODO: __vectorcall will change this.
2322     return None;
2323   }
2324
2325   const Function *Fn = MF.getFunction();
2326   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2327   bool isSoftFloat = Subtarget->useSoftFloat();
2328   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2329          "SSE register cannot be used when SSE is disabled!");
2330   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2331     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2332     // registers.
2333     return None;
2334
2335   static const MCPhysReg XMMArgRegs64Bit[] = {
2336     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2337     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2338   };
2339   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2340 }
2341
2342 SDValue
2343 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2344                                         CallingConv::ID CallConv,
2345                                         bool isVarArg,
2346                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2347                                         SDLoc dl,
2348                                         SelectionDAG &DAG,
2349                                         SmallVectorImpl<SDValue> &InVals)
2350                                           const {
2351   MachineFunction &MF = DAG.getMachineFunction();
2352   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2353   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2354
2355   const Function* Fn = MF.getFunction();
2356   if (Fn->hasExternalLinkage() &&
2357       Subtarget->isTargetCygMing() &&
2358       Fn->getName() == "main")
2359     FuncInfo->setForceFramePointer(true);
2360
2361   MachineFrameInfo *MFI = MF.getFrameInfo();
2362   bool Is64Bit = Subtarget->is64Bit();
2363   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2364
2365   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2366          "Var args not supported with calling convention fastcc, ghc or hipe");
2367
2368   // Assign locations to all of the incoming arguments.
2369   SmallVector<CCValAssign, 16> ArgLocs;
2370   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2371
2372   // Allocate shadow area for Win64
2373   if (IsWin64)
2374     CCInfo.AllocateStack(32, 8);
2375
2376   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2377
2378   unsigned LastVal = ~0U;
2379   SDValue ArgValue;
2380   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381     CCValAssign &VA = ArgLocs[i];
2382     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2383     // places.
2384     assert(VA.getValNo() != LastVal &&
2385            "Don't support value assigned to multiple locs yet");
2386     (void)LastVal;
2387     LastVal = VA.getValNo();
2388
2389     if (VA.isRegLoc()) {
2390       EVT RegVT = VA.getLocVT();
2391       const TargetRegisterClass *RC;
2392       if (RegVT == MVT::i32)
2393         RC = &X86::GR32RegClass;
2394       else if (Is64Bit && RegVT == MVT::i64)
2395         RC = &X86::GR64RegClass;
2396       else if (RegVT == MVT::f32)
2397         RC = &X86::FR32RegClass;
2398       else if (RegVT == MVT::f64)
2399         RC = &X86::FR64RegClass;
2400       else if (RegVT.is512BitVector())
2401         RC = &X86::VR512RegClass;
2402       else if (RegVT.is256BitVector())
2403         RC = &X86::VR256RegClass;
2404       else if (RegVT.is128BitVector())
2405         RC = &X86::VR128RegClass;
2406       else if (RegVT == MVT::x86mmx)
2407         RC = &X86::VR64RegClass;
2408       else if (RegVT == MVT::i1)
2409         RC = &X86::VK1RegClass;
2410       else if (RegVT == MVT::v8i1)
2411         RC = &X86::VK8RegClass;
2412       else if (RegVT == MVT::v16i1)
2413         RC = &X86::VK16RegClass;
2414       else if (RegVT == MVT::v32i1)
2415         RC = &X86::VK32RegClass;
2416       else if (RegVT == MVT::v64i1)
2417         RC = &X86::VK64RegClass;
2418       else
2419         llvm_unreachable("Unknown argument type!");
2420
2421       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2422       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2423
2424       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2425       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2426       // right size.
2427       if (VA.getLocInfo() == CCValAssign::SExt)
2428         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2429                                DAG.getValueType(VA.getValVT()));
2430       else if (VA.getLocInfo() == CCValAssign::ZExt)
2431         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2432                                DAG.getValueType(VA.getValVT()));
2433       else if (VA.getLocInfo() == CCValAssign::BCvt)
2434         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2435
2436       if (VA.isExtInLoc()) {
2437         // Handle MMX values passed in XMM regs.
2438         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2439           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2440         else
2441           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2442       }
2443     } else {
2444       assert(VA.isMemLoc());
2445       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2446     }
2447
2448     // If value is passed via pointer - do a load.
2449     if (VA.getLocInfo() == CCValAssign::Indirect)
2450       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2451                              MachinePointerInfo(), false, false, false, 0);
2452
2453     InVals.push_back(ArgValue);
2454   }
2455
2456   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2457     // All x86 ABIs require that for returning structs by value we copy the
2458     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2459     // the argument into a virtual register so that we can access it from the
2460     // return points.
2461     if (Ins[i].Flags.isSRet()) {
2462       unsigned Reg = FuncInfo->getSRetReturnReg();
2463       if (!Reg) {
2464         MVT PtrTy = getPointerTy();
2465         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2466         FuncInfo->setSRetReturnReg(Reg);
2467       }
2468       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2469       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2470       break;
2471     }
2472   }
2473
2474   unsigned StackSize = CCInfo.getNextStackOffset();
2475   // Align stack specially for tail calls.
2476   if (FuncIsMadeTailCallSafe(CallConv,
2477                              MF.getTarget().Options.GuaranteedTailCallOpt))
2478     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2479
2480   // If the function takes variable number of arguments, make a frame index for
2481   // the start of the first vararg value... for expansion of llvm.va_start. We
2482   // can skip this if there are no va_start calls.
2483   if (MFI->hasVAStart() &&
2484       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2485                    CallConv != CallingConv::X86_ThisCall))) {
2486     FuncInfo->setVarArgsFrameIndex(
2487         MFI->CreateFixedObject(1, StackSize, true));
2488   }
2489
2490   MachineModuleInfo &MMI = MF.getMMI();
2491   const Function *WinEHParent = nullptr;
2492   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2493     WinEHParent = MMI.getWinEHParent(Fn);
2494   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2495   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2496
2497   // Figure out if XMM registers are in use.
2498   assert(!(Subtarget->useSoftFloat() &&
2499            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2500          "SSE register cannot be used when SSE is disabled!");
2501
2502   // 64-bit calling conventions support varargs and register parameters, so we
2503   // have to do extra work to spill them in the prologue.
2504   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2505     // Find the first unallocated argument registers.
2506     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2507     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2508     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2509     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2510     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2511            "SSE register cannot be used when SSE is disabled!");
2512
2513     // Gather all the live in physical registers.
2514     SmallVector<SDValue, 6> LiveGPRs;
2515     SmallVector<SDValue, 8> LiveXMMRegs;
2516     SDValue ALVal;
2517     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2518       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2519       LiveGPRs.push_back(
2520           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2521     }
2522     if (!ArgXMMs.empty()) {
2523       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2524       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2525       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2526         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2527         LiveXMMRegs.push_back(
2528             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2529       }
2530     }
2531
2532     if (IsWin64) {
2533       // Get to the caller-allocated home save location.  Add 8 to account
2534       // for the return address.
2535       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2536       FuncInfo->setRegSaveFrameIndex(
2537           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2538       // Fixup to set vararg frame on shadow area (4 x i64).
2539       if (NumIntRegs < 4)
2540         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2541     } else {
2542       // For X86-64, if there are vararg parameters that are passed via
2543       // registers, then we must store them to their spots on the stack so
2544       // they may be loaded by deferencing the result of va_next.
2545       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2546       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2547       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2548           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2549     }
2550
2551     // Store the integer parameter registers.
2552     SmallVector<SDValue, 8> MemOps;
2553     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2554                                       getPointerTy());
2555     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2556     for (SDValue Val : LiveGPRs) {
2557       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2558                                 DAG.getIntPtrConstant(Offset, dl));
2559       SDValue Store =
2560         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2561                      MachinePointerInfo::getFixedStack(
2562                        FuncInfo->getRegSaveFrameIndex(), Offset),
2563                      false, false, 0);
2564       MemOps.push_back(Store);
2565       Offset += 8;
2566     }
2567
2568     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2569       // Now store the XMM (fp + vector) parameter registers.
2570       SmallVector<SDValue, 12> SaveXMMOps;
2571       SaveXMMOps.push_back(Chain);
2572       SaveXMMOps.push_back(ALVal);
2573       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2574                              FuncInfo->getRegSaveFrameIndex(), dl));
2575       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2576                              FuncInfo->getVarArgsFPOffset(), dl));
2577       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2578                         LiveXMMRegs.end());
2579       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2580                                    MVT::Other, SaveXMMOps));
2581     }
2582
2583     if (!MemOps.empty())
2584       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2585   } else if (IsWinEHOutlined) {
2586     // Get to the caller-allocated home save location.  Add 8 to account
2587     // for the return address.
2588     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2589     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2590         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2591
2592     MMI.getWinEHFuncInfo(Fn)
2593         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2594         FuncInfo->getRegSaveFrameIndex();
2595
2596     // Store the second integer parameter (rdx) into rsp+16 relative to the
2597     // stack pointer at the entry of the function.
2598     SDValue RSFIN =
2599         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2600     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2601     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2602     Chain = DAG.getStore(
2603         Val.getValue(1), dl, Val, RSFIN,
2604         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2605         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2606   }
2607
2608   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2609     // Find the largest legal vector type.
2610     MVT VecVT = MVT::Other;
2611     // FIXME: Only some x86_32 calling conventions support AVX512.
2612     if (Subtarget->hasAVX512() &&
2613         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2614                      CallConv == CallingConv::Intel_OCL_BI)))
2615       VecVT = MVT::v16f32;
2616     else if (Subtarget->hasAVX())
2617       VecVT = MVT::v8f32;
2618     else if (Subtarget->hasSSE2())
2619       VecVT = MVT::v4f32;
2620
2621     // We forward some GPRs and some vector types.
2622     SmallVector<MVT, 2> RegParmTypes;
2623     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2624     RegParmTypes.push_back(IntVT);
2625     if (VecVT != MVT::Other)
2626       RegParmTypes.push_back(VecVT);
2627
2628     // Compute the set of forwarded registers. The rest are scratch.
2629     SmallVectorImpl<ForwardedRegister> &Forwards =
2630         FuncInfo->getForwardedMustTailRegParms();
2631     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2632
2633     // Conservatively forward AL on x86_64, since it might be used for varargs.
2634     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2635       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2636       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2637     }
2638
2639     // Copy all forwards from physical to virtual registers.
2640     for (ForwardedRegister &F : Forwards) {
2641       // FIXME: Can we use a less constrained schedule?
2642       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2643       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2644       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2645     }
2646   }
2647
2648   // Some CCs need callee pop.
2649   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2650                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2651     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2652   } else {
2653     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2654     // If this is an sret function, the return should pop the hidden pointer.
2655     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2656         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2657         argsAreStructReturn(Ins) == StackStructReturn)
2658       FuncInfo->setBytesToPopOnReturn(4);
2659   }
2660
2661   if (!Is64Bit) {
2662     // RegSaveFrameIndex is X86-64 only.
2663     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2664     if (CallConv == CallingConv::X86_FastCall ||
2665         CallConv == CallingConv::X86_ThisCall)
2666       // fastcc functions can't have varargs.
2667       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2668   }
2669
2670   FuncInfo->setArgumentStackSize(StackSize);
2671
2672   if (IsWinEHParent) {
2673     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2674     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2675     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2676     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2677     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2678                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2679                          /*isVolatile=*/true,
2680                          /*isNonTemporal=*/false, /*Alignment=*/0);
2681   }
2682
2683   return Chain;
2684 }
2685
2686 SDValue
2687 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2688                                     SDValue StackPtr, SDValue Arg,
2689                                     SDLoc dl, SelectionDAG &DAG,
2690                                     const CCValAssign &VA,
2691                                     ISD::ArgFlagsTy Flags) const {
2692   unsigned LocMemOffset = VA.getLocMemOffset();
2693   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2694   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2695   if (Flags.isByVal())
2696     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2697
2698   return DAG.getStore(Chain, dl, Arg, PtrOff,
2699                       MachinePointerInfo::getStack(LocMemOffset),
2700                       false, false, 0);
2701 }
2702
2703 /// Emit a load of return address if tail call
2704 /// optimization is performed and it is required.
2705 SDValue
2706 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2707                                            SDValue &OutRetAddr, SDValue Chain,
2708                                            bool IsTailCall, bool Is64Bit,
2709                                            int FPDiff, SDLoc dl) const {
2710   // Adjust the Return address stack slot.
2711   EVT VT = getPointerTy();
2712   OutRetAddr = getReturnAddressFrameIndex(DAG);
2713
2714   // Load the "old" Return address.
2715   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2716                            false, false, false, 0);
2717   return SDValue(OutRetAddr.getNode(), 1);
2718 }
2719
2720 /// Emit a store of the return address if tail call
2721 /// optimization is performed and it is required (FPDiff!=0).
2722 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2723                                         SDValue Chain, SDValue RetAddrFrIdx,
2724                                         EVT PtrVT, unsigned SlotSize,
2725                                         int FPDiff, SDLoc dl) {
2726   // Store the return address to the appropriate stack slot.
2727   if (!FPDiff) return Chain;
2728   // Calculate the new stack slot for the return address.
2729   int NewReturnAddrFI =
2730     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2731                                          false);
2732   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2733   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2734                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2735                        false, false, 0);
2736   return Chain;
2737 }
2738
2739 SDValue
2740 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2741                              SmallVectorImpl<SDValue> &InVals) const {
2742   SelectionDAG &DAG                     = CLI.DAG;
2743   SDLoc &dl                             = CLI.DL;
2744   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2745   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2746   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2747   SDValue Chain                         = CLI.Chain;
2748   SDValue Callee                        = CLI.Callee;
2749   CallingConv::ID CallConv              = CLI.CallConv;
2750   bool &isTailCall                      = CLI.IsTailCall;
2751   bool isVarArg                         = CLI.IsVarArg;
2752
2753   MachineFunction &MF = DAG.getMachineFunction();
2754   bool Is64Bit        = Subtarget->is64Bit();
2755   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2756   StructReturnType SR = callIsStructReturn(Outs);
2757   bool IsSibcall      = false;
2758   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2759
2760   if (MF.getTarget().Options.DisableTailCalls)
2761     isTailCall = false;
2762
2763   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2764   if (IsMustTail) {
2765     // Force this to be a tail call.  The verifier rules are enough to ensure
2766     // that we can lower this successfully without moving the return address
2767     // around.
2768     isTailCall = true;
2769   } else if (isTailCall) {
2770     // Check if it's really possible to do a tail call.
2771     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2772                     isVarArg, SR != NotStructReturn,
2773                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2774                     Outs, OutVals, Ins, DAG);
2775
2776     // Sibcalls are automatically detected tailcalls which do not require
2777     // ABI changes.
2778     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2779       IsSibcall = true;
2780
2781     if (isTailCall)
2782       ++NumTailCalls;
2783   }
2784
2785   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2786          "Var args not supported with calling convention fastcc, ghc or hipe");
2787
2788   // Analyze operands of the call, assigning locations to each operand.
2789   SmallVector<CCValAssign, 16> ArgLocs;
2790   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2791
2792   // Allocate shadow area for Win64
2793   if (IsWin64)
2794     CCInfo.AllocateStack(32, 8);
2795
2796   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2797
2798   // Get a count of how many bytes are to be pushed on the stack.
2799   unsigned NumBytes = CCInfo.getNextStackOffset();
2800   if (IsSibcall)
2801     // This is a sibcall. The memory operands are available in caller's
2802     // own caller's stack.
2803     NumBytes = 0;
2804   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2805            IsTailCallConvention(CallConv))
2806     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2807
2808   int FPDiff = 0;
2809   if (isTailCall && !IsSibcall && !IsMustTail) {
2810     // Lower arguments at fp - stackoffset + fpdiff.
2811     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2812
2813     FPDiff = NumBytesCallerPushed - NumBytes;
2814
2815     // Set the delta of movement of the returnaddr stackslot.
2816     // But only set if delta is greater than previous delta.
2817     if (FPDiff < X86Info->getTCReturnAddrDelta())
2818       X86Info->setTCReturnAddrDelta(FPDiff);
2819   }
2820
2821   unsigned NumBytesToPush = NumBytes;
2822   unsigned NumBytesToPop = NumBytes;
2823
2824   // If we have an inalloca argument, all stack space has already been allocated
2825   // for us and be right at the top of the stack.  We don't support multiple
2826   // arguments passed in memory when using inalloca.
2827   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2828     NumBytesToPush = 0;
2829     if (!ArgLocs.back().isMemLoc())
2830       report_fatal_error("cannot use inalloca attribute on a register "
2831                          "parameter");
2832     if (ArgLocs.back().getLocMemOffset() != 0)
2833       report_fatal_error("any parameter with the inalloca attribute must be "
2834                          "the only memory argument");
2835   }
2836
2837   if (!IsSibcall)
2838     Chain = DAG.getCALLSEQ_START(
2839         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2840
2841   SDValue RetAddrFrIdx;
2842   // Load return address for tail calls.
2843   if (isTailCall && FPDiff)
2844     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2845                                     Is64Bit, FPDiff, dl);
2846
2847   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2848   SmallVector<SDValue, 8> MemOpChains;
2849   SDValue StackPtr;
2850
2851   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2852   // of tail call optimization arguments are handle later.
2853   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2854   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2855     // Skip inalloca arguments, they have already been written.
2856     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2857     if (Flags.isInAlloca())
2858       continue;
2859
2860     CCValAssign &VA = ArgLocs[i];
2861     EVT RegVT = VA.getLocVT();
2862     SDValue Arg = OutVals[i];
2863     bool isByVal = Flags.isByVal();
2864
2865     // Promote the value if needed.
2866     switch (VA.getLocInfo()) {
2867     default: llvm_unreachable("Unknown loc info!");
2868     case CCValAssign::Full: break;
2869     case CCValAssign::SExt:
2870       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2871       break;
2872     case CCValAssign::ZExt:
2873       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2874       break;
2875     case CCValAssign::AExt:
2876       if (Arg.getValueType().isVector() &&
2877           Arg.getValueType().getScalarType() == MVT::i1)
2878         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2879       else if (RegVT.is128BitVector()) {
2880         // Special case: passing MMX values in XMM registers.
2881         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2882         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2883         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2884       } else
2885         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2886       break;
2887     case CCValAssign::BCvt:
2888       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2889       break;
2890     case CCValAssign::Indirect: {
2891       // Store the argument.
2892       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2893       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2894       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2895                            MachinePointerInfo::getFixedStack(FI),
2896                            false, false, 0);
2897       Arg = SpillSlot;
2898       break;
2899     }
2900     }
2901
2902     if (VA.isRegLoc()) {
2903       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2904       if (isVarArg && IsWin64) {
2905         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2906         // shadow reg if callee is a varargs function.
2907         unsigned ShadowReg = 0;
2908         switch (VA.getLocReg()) {
2909         case X86::XMM0: ShadowReg = X86::RCX; break;
2910         case X86::XMM1: ShadowReg = X86::RDX; break;
2911         case X86::XMM2: ShadowReg = X86::R8; break;
2912         case X86::XMM3: ShadowReg = X86::R9; break;
2913         }
2914         if (ShadowReg)
2915           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2916       }
2917     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2918       assert(VA.isMemLoc());
2919       if (!StackPtr.getNode())
2920         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2921                                       getPointerTy());
2922       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2923                                              dl, DAG, VA, Flags));
2924     }
2925   }
2926
2927   if (!MemOpChains.empty())
2928     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2929
2930   if (Subtarget->isPICStyleGOT()) {
2931     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2932     // GOT pointer.
2933     if (!isTailCall) {
2934       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2935                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2936     } else {
2937       // If we are tail calling and generating PIC/GOT style code load the
2938       // address of the callee into ECX. The value in ecx is used as target of
2939       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2940       // for tail calls on PIC/GOT architectures. Normally we would just put the
2941       // address of GOT into ebx and then call target@PLT. But for tail calls
2942       // ebx would be restored (since ebx is callee saved) before jumping to the
2943       // target@PLT.
2944
2945       // Note: The actual moving to ECX is done further down.
2946       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2947       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2948           !G->getGlobal()->hasProtectedVisibility())
2949         Callee = LowerGlobalAddress(Callee, DAG);
2950       else if (isa<ExternalSymbolSDNode>(Callee))
2951         Callee = LowerExternalSymbol(Callee, DAG);
2952     }
2953   }
2954
2955   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2956     // From AMD64 ABI document:
2957     // For calls that may call functions that use varargs or stdargs
2958     // (prototype-less calls or calls to functions containing ellipsis (...) in
2959     // the declaration) %al is used as hidden argument to specify the number
2960     // of SSE registers used. The contents of %al do not need to match exactly
2961     // the number of registers, but must be an ubound on the number of SSE
2962     // registers used and is in the range 0 - 8 inclusive.
2963
2964     // Count the number of XMM registers allocated.
2965     static const MCPhysReg XMMArgRegs[] = {
2966       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2967       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2968     };
2969     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2970     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2971            && "SSE registers cannot be used when SSE is disabled");
2972
2973     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2974                                         DAG.getConstant(NumXMMRegs, dl,
2975                                                         MVT::i8)));
2976   }
2977
2978   if (isVarArg && IsMustTail) {
2979     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2980     for (const auto &F : Forwards) {
2981       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2982       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2983     }
2984   }
2985
2986   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2987   // don't need this because the eligibility check rejects calls that require
2988   // shuffling arguments passed in memory.
2989   if (!IsSibcall && isTailCall) {
2990     // Force all the incoming stack arguments to be loaded from the stack
2991     // before any new outgoing arguments are stored to the stack, because the
2992     // outgoing stack slots may alias the incoming argument stack slots, and
2993     // the alias isn't otherwise explicit. This is slightly more conservative
2994     // than necessary, because it means that each store effectively depends
2995     // on every argument instead of just those arguments it would clobber.
2996     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2997
2998     SmallVector<SDValue, 8> MemOpChains2;
2999     SDValue FIN;
3000     int FI = 0;
3001     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3002       CCValAssign &VA = ArgLocs[i];
3003       if (VA.isRegLoc())
3004         continue;
3005       assert(VA.isMemLoc());
3006       SDValue Arg = OutVals[i];
3007       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3008       // Skip inalloca arguments.  They don't require any work.
3009       if (Flags.isInAlloca())
3010         continue;
3011       // Create frame index.
3012       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3013       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3014       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3015       FIN = DAG.getFrameIndex(FI, getPointerTy());
3016
3017       if (Flags.isByVal()) {
3018         // Copy relative to framepointer.
3019         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3020         if (!StackPtr.getNode())
3021           StackPtr = DAG.getCopyFromReg(Chain, dl,
3022                                         RegInfo->getStackRegister(),
3023                                         getPointerTy());
3024         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3025
3026         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3027                                                          ArgChain,
3028                                                          Flags, DAG, dl));
3029       } else {
3030         // Store relative to framepointer.
3031         MemOpChains2.push_back(
3032           DAG.getStore(ArgChain, dl, Arg, FIN,
3033                        MachinePointerInfo::getFixedStack(FI),
3034                        false, false, 0));
3035       }
3036     }
3037
3038     if (!MemOpChains2.empty())
3039       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3040
3041     // Store the return address to the appropriate stack slot.
3042     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3043                                      getPointerTy(), RegInfo->getSlotSize(),
3044                                      FPDiff, dl);
3045   }
3046
3047   // Build a sequence of copy-to-reg nodes chained together with token chain
3048   // and flag operands which copy the outgoing args into registers.
3049   SDValue InFlag;
3050   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3051     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3052                              RegsToPass[i].second, InFlag);
3053     InFlag = Chain.getValue(1);
3054   }
3055
3056   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3057     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3058     // In the 64-bit large code model, we have to make all calls
3059     // through a register, since the call instruction's 32-bit
3060     // pc-relative offset may not be large enough to hold the whole
3061     // address.
3062   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3063     // If the callee is a GlobalAddress node (quite common, every direct call
3064     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3065     // it.
3066     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3067
3068     // We should use extra load for direct calls to dllimported functions in
3069     // non-JIT mode.
3070     const GlobalValue *GV = G->getGlobal();
3071     if (!GV->hasDLLImportStorageClass()) {
3072       unsigned char OpFlags = 0;
3073       bool ExtraLoad = false;
3074       unsigned WrapperKind = ISD::DELETED_NODE;
3075
3076       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3077       // external symbols most go through the PLT in PIC mode.  If the symbol
3078       // has hidden or protected visibility, or if it is static or local, then
3079       // we don't need to use the PLT - we can directly call it.
3080       if (Subtarget->isTargetELF() &&
3081           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3082           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3083         OpFlags = X86II::MO_PLT;
3084       } else if (Subtarget->isPICStyleStubAny() &&
3085                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3086                  (!Subtarget->getTargetTriple().isMacOSX() ||
3087                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3088         // PC-relative references to external symbols should go through $stub,
3089         // unless we're building with the leopard linker or later, which
3090         // automatically synthesizes these stubs.
3091         OpFlags = X86II::MO_DARWIN_STUB;
3092       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3093                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3094         // If the function is marked as non-lazy, generate an indirect call
3095         // which loads from the GOT directly. This avoids runtime overhead
3096         // at the cost of eager binding (and one extra byte of encoding).
3097         OpFlags = X86II::MO_GOTPCREL;
3098         WrapperKind = X86ISD::WrapperRIP;
3099         ExtraLoad = true;
3100       }
3101
3102       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3103                                           G->getOffset(), OpFlags);
3104
3105       // Add a wrapper if needed.
3106       if (WrapperKind != ISD::DELETED_NODE)
3107         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3108       // Add extra indirection if needed.
3109       if (ExtraLoad)
3110         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3111                              MachinePointerInfo::getGOT(),
3112                              false, false, false, 0);
3113     }
3114   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3115     unsigned char OpFlags = 0;
3116
3117     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3118     // external symbols should go through the PLT.
3119     if (Subtarget->isTargetELF() &&
3120         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3121       OpFlags = X86II::MO_PLT;
3122     } else if (Subtarget->isPICStyleStubAny() &&
3123                (!Subtarget->getTargetTriple().isMacOSX() ||
3124                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3125       // PC-relative references to external symbols should go through $stub,
3126       // unless we're building with the leopard linker or later, which
3127       // automatically synthesizes these stubs.
3128       OpFlags = X86II::MO_DARWIN_STUB;
3129     }
3130
3131     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3132                                          OpFlags);
3133   } else if (Subtarget->isTarget64BitILP32() &&
3134              Callee->getValueType(0) == MVT::i32) {
3135     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3136     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3137   }
3138
3139   // Returns a chain & a flag for retval copy to use.
3140   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3141   SmallVector<SDValue, 8> Ops;
3142
3143   if (!IsSibcall && isTailCall) {
3144     Chain = DAG.getCALLSEQ_END(Chain,
3145                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3146                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3147     InFlag = Chain.getValue(1);
3148   }
3149
3150   Ops.push_back(Chain);
3151   Ops.push_back(Callee);
3152
3153   if (isTailCall)
3154     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3155
3156   // Add argument registers to the end of the list so that they are known live
3157   // into the call.
3158   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3159     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3160                                   RegsToPass[i].second.getValueType()));
3161
3162   // Add a register mask operand representing the call-preserved registers.
3163   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3164   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3165   assert(Mask && "Missing call preserved mask for calling convention");
3166   Ops.push_back(DAG.getRegisterMask(Mask));
3167
3168   if (InFlag.getNode())
3169     Ops.push_back(InFlag);
3170
3171   if (isTailCall) {
3172     // We used to do:
3173     //// If this is the first return lowered for this function, add the regs
3174     //// to the liveout set for the function.
3175     // This isn't right, although it's probably harmless on x86; liveouts
3176     // should be computed from returns not tail calls.  Consider a void
3177     // function making a tail call to a function returning int.
3178     MF.getFrameInfo()->setHasTailCall();
3179     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3180   }
3181
3182   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3183   InFlag = Chain.getValue(1);
3184
3185   // Create the CALLSEQ_END node.
3186   unsigned NumBytesForCalleeToPop;
3187   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3188                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3189     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3190   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3191            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3192            SR == StackStructReturn)
3193     // If this is a call to a struct-return function, the callee
3194     // pops the hidden struct pointer, so we have to push it back.
3195     // This is common for Darwin/X86, Linux & Mingw32 targets.
3196     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3197     NumBytesForCalleeToPop = 4;
3198   else
3199     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3200
3201   // Returns a flag for retval copy to use.
3202   if (!IsSibcall) {
3203     Chain = DAG.getCALLSEQ_END(Chain,
3204                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3205                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3206                                                      true),
3207                                InFlag, dl);
3208     InFlag = Chain.getValue(1);
3209   }
3210
3211   // Handle result values, copying them out of physregs into vregs that we
3212   // return.
3213   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3214                          Ins, dl, DAG, InVals);
3215 }
3216
3217 //===----------------------------------------------------------------------===//
3218 //                Fast Calling Convention (tail call) implementation
3219 //===----------------------------------------------------------------------===//
3220
3221 //  Like std call, callee cleans arguments, convention except that ECX is
3222 //  reserved for storing the tail called function address. Only 2 registers are
3223 //  free for argument passing (inreg). Tail call optimization is performed
3224 //  provided:
3225 //                * tailcallopt is enabled
3226 //                * caller/callee are fastcc
3227 //  On X86_64 architecture with GOT-style position independent code only local
3228 //  (within module) calls are supported at the moment.
3229 //  To keep the stack aligned according to platform abi the function
3230 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3231 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3232 //  If a tail called function callee has more arguments than the caller the
3233 //  caller needs to make sure that there is room to move the RETADDR to. This is
3234 //  achieved by reserving an area the size of the argument delta right after the
3235 //  original RETADDR, but before the saved framepointer or the spilled registers
3236 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3237 //  stack layout:
3238 //    arg1
3239 //    arg2
3240 //    RETADDR
3241 //    [ new RETADDR
3242 //      move area ]
3243 //    (possible EBP)
3244 //    ESI
3245 //    EDI
3246 //    local1 ..
3247
3248 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3249 /// for a 16 byte align requirement.
3250 unsigned
3251 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3252                                                SelectionDAG& DAG) const {
3253   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3254   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3255   unsigned StackAlignment = TFI.getStackAlignment();
3256   uint64_t AlignMask = StackAlignment - 1;
3257   int64_t Offset = StackSize;
3258   unsigned SlotSize = RegInfo->getSlotSize();
3259   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3260     // Number smaller than 12 so just add the difference.
3261     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3262   } else {
3263     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3264     Offset = ((~AlignMask) & Offset) + StackAlignment +
3265       (StackAlignment-SlotSize);
3266   }
3267   return Offset;
3268 }
3269
3270 /// MatchingStackOffset - Return true if the given stack call argument is
3271 /// already available in the same position (relatively) of the caller's
3272 /// incoming argument stack.
3273 static
3274 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3275                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3276                          const X86InstrInfo *TII) {
3277   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3278   int FI = INT_MAX;
3279   if (Arg.getOpcode() == ISD::CopyFromReg) {
3280     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3281     if (!TargetRegisterInfo::isVirtualRegister(VR))
3282       return false;
3283     MachineInstr *Def = MRI->getVRegDef(VR);
3284     if (!Def)
3285       return false;
3286     if (!Flags.isByVal()) {
3287       if (!TII->isLoadFromStackSlot(Def, FI))
3288         return false;
3289     } else {
3290       unsigned Opcode = Def->getOpcode();
3291       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3292            Opcode == X86::LEA64_32r) &&
3293           Def->getOperand(1).isFI()) {
3294         FI = Def->getOperand(1).getIndex();
3295         Bytes = Flags.getByValSize();
3296       } else
3297         return false;
3298     }
3299   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3300     if (Flags.isByVal())
3301       // ByVal argument is passed in as a pointer but it's now being
3302       // dereferenced. e.g.
3303       // define @foo(%struct.X* %A) {
3304       //   tail call @bar(%struct.X* byval %A)
3305       // }
3306       return false;
3307     SDValue Ptr = Ld->getBasePtr();
3308     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3309     if (!FINode)
3310       return false;
3311     FI = FINode->getIndex();
3312   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3313     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3314     FI = FINode->getIndex();
3315     Bytes = Flags.getByValSize();
3316   } else
3317     return false;
3318
3319   assert(FI != INT_MAX);
3320   if (!MFI->isFixedObjectIndex(FI))
3321     return false;
3322   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3323 }
3324
3325 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3326 /// for tail call optimization. Targets which want to do tail call
3327 /// optimization should implement this function.
3328 bool
3329 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3330                                                      CallingConv::ID CalleeCC,
3331                                                      bool isVarArg,
3332                                                      bool isCalleeStructRet,
3333                                                      bool isCallerStructRet,
3334                                                      Type *RetTy,
3335                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3336                                     const SmallVectorImpl<SDValue> &OutVals,
3337                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3338                                                      SelectionDAG &DAG) const {
3339   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3340     return false;
3341
3342   // If -tailcallopt is specified, make fastcc functions tail-callable.
3343   const MachineFunction &MF = DAG.getMachineFunction();
3344   const Function *CallerF = MF.getFunction();
3345
3346   // If the function return type is x86_fp80 and the callee return type is not,
3347   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3348   // perform a tailcall optimization here.
3349   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3350     return false;
3351
3352   CallingConv::ID CallerCC = CallerF->getCallingConv();
3353   bool CCMatch = CallerCC == CalleeCC;
3354   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3355   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3356
3357   // Win64 functions have extra shadow space for argument homing. Don't do the
3358   // sibcall if the caller and callee have mismatched expectations for this
3359   // space.
3360   if (IsCalleeWin64 != IsCallerWin64)
3361     return false;
3362
3363   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3364     if (IsTailCallConvention(CalleeCC) && CCMatch)
3365       return true;
3366     return false;
3367   }
3368
3369   // Look for obvious safe cases to perform tail call optimization that do not
3370   // require ABI changes. This is what gcc calls sibcall.
3371
3372   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3373   // emit a special epilogue.
3374   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3375   if (RegInfo->needsStackRealignment(MF))
3376     return false;
3377
3378   // Also avoid sibcall optimization if either caller or callee uses struct
3379   // return semantics.
3380   if (isCalleeStructRet || isCallerStructRet)
3381     return false;
3382
3383   // An stdcall/thiscall caller is expected to clean up its arguments; the
3384   // callee isn't going to do that.
3385   // FIXME: this is more restrictive than needed. We could produce a tailcall
3386   // when the stack adjustment matches. For example, with a thiscall that takes
3387   // only one argument.
3388   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3389                    CallerCC == CallingConv::X86_ThisCall))
3390     return false;
3391
3392   // Do not sibcall optimize vararg calls unless all arguments are passed via
3393   // registers.
3394   if (isVarArg && !Outs.empty()) {
3395
3396     // Optimizing for varargs on Win64 is unlikely to be safe without
3397     // additional testing.
3398     if (IsCalleeWin64 || IsCallerWin64)
3399       return false;
3400
3401     SmallVector<CCValAssign, 16> ArgLocs;
3402     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3403                    *DAG.getContext());
3404
3405     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3406     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3407       if (!ArgLocs[i].isRegLoc())
3408         return false;
3409   }
3410
3411   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3412   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3413   // this into a sibcall.
3414   bool Unused = false;
3415   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3416     if (!Ins[i].Used) {
3417       Unused = true;
3418       break;
3419     }
3420   }
3421   if (Unused) {
3422     SmallVector<CCValAssign, 16> RVLocs;
3423     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3424                    *DAG.getContext());
3425     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3426     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3427       CCValAssign &VA = RVLocs[i];
3428       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3429         return false;
3430     }
3431   }
3432
3433   // If the calling conventions do not match, then we'd better make sure the
3434   // results are returned in the same way as what the caller expects.
3435   if (!CCMatch) {
3436     SmallVector<CCValAssign, 16> RVLocs1;
3437     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3438                     *DAG.getContext());
3439     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3440
3441     SmallVector<CCValAssign, 16> RVLocs2;
3442     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3443                     *DAG.getContext());
3444     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3445
3446     if (RVLocs1.size() != RVLocs2.size())
3447       return false;
3448     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3449       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3450         return false;
3451       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3452         return false;
3453       if (RVLocs1[i].isRegLoc()) {
3454         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3455           return false;
3456       } else {
3457         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3458           return false;
3459       }
3460     }
3461   }
3462
3463   // If the callee takes no arguments then go on to check the results of the
3464   // call.
3465   if (!Outs.empty()) {
3466     // Check if stack adjustment is needed. For now, do not do this if any
3467     // argument is passed on the stack.
3468     SmallVector<CCValAssign, 16> ArgLocs;
3469     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3470                    *DAG.getContext());
3471
3472     // Allocate shadow area for Win64
3473     if (IsCalleeWin64)
3474       CCInfo.AllocateStack(32, 8);
3475
3476     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3477     if (CCInfo.getNextStackOffset()) {
3478       MachineFunction &MF = DAG.getMachineFunction();
3479       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3480         return false;
3481
3482       // Check if the arguments are already laid out in the right way as
3483       // the caller's fixed stack objects.
3484       MachineFrameInfo *MFI = MF.getFrameInfo();
3485       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3486       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3487       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3488         CCValAssign &VA = ArgLocs[i];
3489         SDValue Arg = OutVals[i];
3490         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3491         if (VA.getLocInfo() == CCValAssign::Indirect)
3492           return false;
3493         if (!VA.isRegLoc()) {
3494           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3495                                    MFI, MRI, TII))
3496             return false;
3497         }
3498       }
3499     }
3500
3501     // If the tailcall address may be in a register, then make sure it's
3502     // possible to register allocate for it. In 32-bit, the call address can
3503     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3504     // callee-saved registers are restored. These happen to be the same
3505     // registers used to pass 'inreg' arguments so watch out for those.
3506     if (!Subtarget->is64Bit() &&
3507         ((!isa<GlobalAddressSDNode>(Callee) &&
3508           !isa<ExternalSymbolSDNode>(Callee)) ||
3509          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3510       unsigned NumInRegs = 0;
3511       // In PIC we need an extra register to formulate the address computation
3512       // for the callee.
3513       unsigned MaxInRegs =
3514         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3515
3516       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3517         CCValAssign &VA = ArgLocs[i];
3518         if (!VA.isRegLoc())
3519           continue;
3520         unsigned Reg = VA.getLocReg();
3521         switch (Reg) {
3522         default: break;
3523         case X86::EAX: case X86::EDX: case X86::ECX:
3524           if (++NumInRegs == MaxInRegs)
3525             return false;
3526           break;
3527         }
3528       }
3529     }
3530   }
3531
3532   return true;
3533 }
3534
3535 FastISel *
3536 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3537                                   const TargetLibraryInfo *libInfo) const {
3538   return X86::createFastISel(funcInfo, libInfo);
3539 }
3540
3541 //===----------------------------------------------------------------------===//
3542 //                           Other Lowering Hooks
3543 //===----------------------------------------------------------------------===//
3544
3545 static bool MayFoldLoad(SDValue Op) {
3546   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3547 }
3548
3549 static bool MayFoldIntoStore(SDValue Op) {
3550   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3551 }
3552
3553 static bool isTargetShuffle(unsigned Opcode) {
3554   switch(Opcode) {
3555   default: return false;
3556   case X86ISD::BLENDI:
3557   case X86ISD::PSHUFB:
3558   case X86ISD::PSHUFD:
3559   case X86ISD::PSHUFHW:
3560   case X86ISD::PSHUFLW:
3561   case X86ISD::SHUFP:
3562   case X86ISD::PALIGNR:
3563   case X86ISD::MOVLHPS:
3564   case X86ISD::MOVLHPD:
3565   case X86ISD::MOVHLPS:
3566   case X86ISD::MOVLPS:
3567   case X86ISD::MOVLPD:
3568   case X86ISD::MOVSHDUP:
3569   case X86ISD::MOVSLDUP:
3570   case X86ISD::MOVDDUP:
3571   case X86ISD::MOVSS:
3572   case X86ISD::MOVSD:
3573   case X86ISD::UNPCKL:
3574   case X86ISD::UNPCKH:
3575   case X86ISD::VPERMILPI:
3576   case X86ISD::VPERM2X128:
3577   case X86ISD::VPERMI:
3578     return true;
3579   }
3580 }
3581
3582 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3583                                     SDValue V1, unsigned TargetMask,
3584                                     SelectionDAG &DAG) {
3585   switch(Opc) {
3586   default: llvm_unreachable("Unknown x86 shuffle node");
3587   case X86ISD::PSHUFD:
3588   case X86ISD::PSHUFHW:
3589   case X86ISD::PSHUFLW:
3590   case X86ISD::VPERMILPI:
3591   case X86ISD::VPERMI:
3592     return DAG.getNode(Opc, dl, VT, V1,
3593                        DAG.getConstant(TargetMask, dl, MVT::i8));
3594   }
3595 }
3596
3597 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3598                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3599   switch(Opc) {
3600   default: llvm_unreachable("Unknown x86 shuffle node");
3601   case X86ISD::MOVLHPS:
3602   case X86ISD::MOVLHPD:
3603   case X86ISD::MOVHLPS:
3604   case X86ISD::MOVLPS:
3605   case X86ISD::MOVLPD:
3606   case X86ISD::MOVSS:
3607   case X86ISD::MOVSD:
3608   case X86ISD::UNPCKL:
3609   case X86ISD::UNPCKH:
3610     return DAG.getNode(Opc, dl, VT, V1, V2);
3611   }
3612 }
3613
3614 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3615   MachineFunction &MF = DAG.getMachineFunction();
3616   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3617   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3618   int ReturnAddrIndex = FuncInfo->getRAIndex();
3619
3620   if (ReturnAddrIndex == 0) {
3621     // Set up a frame object for the return address.
3622     unsigned SlotSize = RegInfo->getSlotSize();
3623     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3624                                                            -(int64_t)SlotSize,
3625                                                            false);
3626     FuncInfo->setRAIndex(ReturnAddrIndex);
3627   }
3628
3629   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3630 }
3631
3632 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3633                                        bool hasSymbolicDisplacement) {
3634   // Offset should fit into 32 bit immediate field.
3635   if (!isInt<32>(Offset))
3636     return false;
3637
3638   // If we don't have a symbolic displacement - we don't have any extra
3639   // restrictions.
3640   if (!hasSymbolicDisplacement)
3641     return true;
3642
3643   // FIXME: Some tweaks might be needed for medium code model.
3644   if (M != CodeModel::Small && M != CodeModel::Kernel)
3645     return false;
3646
3647   // For small code model we assume that latest object is 16MB before end of 31
3648   // bits boundary. We may also accept pretty large negative constants knowing
3649   // that all objects are in the positive half of address space.
3650   if (M == CodeModel::Small && Offset < 16*1024*1024)
3651     return true;
3652
3653   // For kernel code model we know that all object resist in the negative half
3654   // of 32bits address space. We may not accept negative offsets, since they may
3655   // be just off and we may accept pretty large positive ones.
3656   if (M == CodeModel::Kernel && Offset >= 0)
3657     return true;
3658
3659   return false;
3660 }
3661
3662 /// isCalleePop - Determines whether the callee is required to pop its
3663 /// own arguments. Callee pop is necessary to support tail calls.
3664 bool X86::isCalleePop(CallingConv::ID CallingConv,
3665                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3666   switch (CallingConv) {
3667   default:
3668     return false;
3669   case CallingConv::X86_StdCall:
3670   case CallingConv::X86_FastCall:
3671   case CallingConv::X86_ThisCall:
3672     return !is64Bit;
3673   case CallingConv::Fast:
3674   case CallingConv::GHC:
3675   case CallingConv::HiPE:
3676     if (IsVarArg)
3677       return false;
3678     return TailCallOpt;
3679   }
3680 }
3681
3682 /// \brief Return true if the condition is an unsigned comparison operation.
3683 static bool isX86CCUnsigned(unsigned X86CC) {
3684   switch (X86CC) {
3685   default: llvm_unreachable("Invalid integer condition!");
3686   case X86::COND_E:     return true;
3687   case X86::COND_G:     return false;
3688   case X86::COND_GE:    return false;
3689   case X86::COND_L:     return false;
3690   case X86::COND_LE:    return false;
3691   case X86::COND_NE:    return true;
3692   case X86::COND_B:     return true;
3693   case X86::COND_A:     return true;
3694   case X86::COND_BE:    return true;
3695   case X86::COND_AE:    return true;
3696   }
3697   llvm_unreachable("covered switch fell through?!");
3698 }
3699
3700 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3701 /// specific condition code, returning the condition code and the LHS/RHS of the
3702 /// comparison to make.
3703 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3704                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3705   if (!isFP) {
3706     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3707       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3708         // X > -1   -> X == 0, jump !sign.
3709         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3710         return X86::COND_NS;
3711       }
3712       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3713         // X < 0   -> X == 0, jump on sign.
3714         return X86::COND_S;
3715       }
3716       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3717         // X < 1   -> X <= 0
3718         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3719         return X86::COND_LE;
3720       }
3721     }
3722
3723     switch (SetCCOpcode) {
3724     default: llvm_unreachable("Invalid integer condition!");
3725     case ISD::SETEQ:  return X86::COND_E;
3726     case ISD::SETGT:  return X86::COND_G;
3727     case ISD::SETGE:  return X86::COND_GE;
3728     case ISD::SETLT:  return X86::COND_L;
3729     case ISD::SETLE:  return X86::COND_LE;
3730     case ISD::SETNE:  return X86::COND_NE;
3731     case ISD::SETULT: return X86::COND_B;
3732     case ISD::SETUGT: return X86::COND_A;
3733     case ISD::SETULE: return X86::COND_BE;
3734     case ISD::SETUGE: return X86::COND_AE;
3735     }
3736   }
3737
3738   // First determine if it is required or is profitable to flip the operands.
3739
3740   // If LHS is a foldable load, but RHS is not, flip the condition.
3741   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3742       !ISD::isNON_EXTLoad(RHS.getNode())) {
3743     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3744     std::swap(LHS, RHS);
3745   }
3746
3747   switch (SetCCOpcode) {
3748   default: break;
3749   case ISD::SETOLT:
3750   case ISD::SETOLE:
3751   case ISD::SETUGT:
3752   case ISD::SETUGE:
3753     std::swap(LHS, RHS);
3754     break;
3755   }
3756
3757   // On a floating point condition, the flags are set as follows:
3758   // ZF  PF  CF   op
3759   //  0 | 0 | 0 | X > Y
3760   //  0 | 0 | 1 | X < Y
3761   //  1 | 0 | 0 | X == Y
3762   //  1 | 1 | 1 | unordered
3763   switch (SetCCOpcode) {
3764   default: llvm_unreachable("Condcode should be pre-legalized away");
3765   case ISD::SETUEQ:
3766   case ISD::SETEQ:   return X86::COND_E;
3767   case ISD::SETOLT:              // flipped
3768   case ISD::SETOGT:
3769   case ISD::SETGT:   return X86::COND_A;
3770   case ISD::SETOLE:              // flipped
3771   case ISD::SETOGE:
3772   case ISD::SETGE:   return X86::COND_AE;
3773   case ISD::SETUGT:              // flipped
3774   case ISD::SETULT:
3775   case ISD::SETLT:   return X86::COND_B;
3776   case ISD::SETUGE:              // flipped
3777   case ISD::SETULE:
3778   case ISD::SETLE:   return X86::COND_BE;
3779   case ISD::SETONE:
3780   case ISD::SETNE:   return X86::COND_NE;
3781   case ISD::SETUO:   return X86::COND_P;
3782   case ISD::SETO:    return X86::COND_NP;
3783   case ISD::SETOEQ:
3784   case ISD::SETUNE:  return X86::COND_INVALID;
3785   }
3786 }
3787
3788 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3789 /// code. Current x86 isa includes the following FP cmov instructions:
3790 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3791 static bool hasFPCMov(unsigned X86CC) {
3792   switch (X86CC) {
3793   default:
3794     return false;
3795   case X86::COND_B:
3796   case X86::COND_BE:
3797   case X86::COND_E:
3798   case X86::COND_P:
3799   case X86::COND_A:
3800   case X86::COND_AE:
3801   case X86::COND_NE:
3802   case X86::COND_NP:
3803     return true;
3804   }
3805 }
3806
3807 /// isFPImmLegal - Returns true if the target can instruction select the
3808 /// specified FP immediate natively. If false, the legalizer will
3809 /// materialize the FP immediate as a load from a constant pool.
3810 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3811   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3812     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3813       return true;
3814   }
3815   return false;
3816 }
3817
3818 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3819                                               ISD::LoadExtType ExtTy,
3820                                               EVT NewVT) const {
3821   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3822   // relocation target a movq or addq instruction: don't let the load shrink.
3823   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3824   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3825     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3826       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3827   return true;
3828 }
3829
3830 /// \brief Returns true if it is beneficial to convert a load of a constant
3831 /// to just the constant itself.
3832 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3833                                                           Type *Ty) const {
3834   assert(Ty->isIntegerTy());
3835
3836   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3837   if (BitSize == 0 || BitSize > 64)
3838     return false;
3839   return true;
3840 }
3841
3842 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3843                                                 unsigned Index) const {
3844   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3845     return false;
3846
3847   return (Index == 0 || Index == ResVT.getVectorNumElements());
3848 }
3849
3850 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3851   // Speculate cttz only if we can directly use TZCNT.
3852   return Subtarget->hasBMI();
3853 }
3854
3855 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3856   // Speculate ctlz only if we can directly use LZCNT.
3857   return Subtarget->hasLZCNT();
3858 }
3859
3860 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3861 /// the specified range (L, H].
3862 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3863   return (Val < 0) || (Val >= Low && Val < Hi);
3864 }
3865
3866 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3867 /// specified value.
3868 static bool isUndefOrEqual(int Val, int CmpVal) {
3869   return (Val < 0 || Val == CmpVal);
3870 }
3871
3872 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3873 /// from position Pos and ending in Pos+Size, falls within the specified
3874 /// sequential range (Low, Low+Size]. or is undef.
3875 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3876                                        unsigned Pos, unsigned Size, int Low) {
3877   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3878     if (!isUndefOrEqual(Mask[i], Low))
3879       return false;
3880   return true;
3881 }
3882
3883 /// isVEXTRACTIndex - Return true if the specified
3884 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3885 /// suitable for instruction that extract 128 or 256 bit vectors
3886 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3887   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3888   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3889     return false;
3890
3891   // The index should be aligned on a vecWidth-bit boundary.
3892   uint64_t Index =
3893     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3894
3895   MVT VT = N->getSimpleValueType(0);
3896   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3897   bool Result = (Index * ElSize) % vecWidth == 0;
3898
3899   return Result;
3900 }
3901
3902 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3903 /// operand specifies a subvector insert that is suitable for input to
3904 /// insertion of 128 or 256-bit subvectors
3905 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3906   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3907   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3908     return false;
3909   // The index should be aligned on a vecWidth-bit boundary.
3910   uint64_t Index =
3911     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3912
3913   MVT VT = N->getSimpleValueType(0);
3914   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3915   bool Result = (Index * ElSize) % vecWidth == 0;
3916
3917   return Result;
3918 }
3919
3920 bool X86::isVINSERT128Index(SDNode *N) {
3921   return isVINSERTIndex(N, 128);
3922 }
3923
3924 bool X86::isVINSERT256Index(SDNode *N) {
3925   return isVINSERTIndex(N, 256);
3926 }
3927
3928 bool X86::isVEXTRACT128Index(SDNode *N) {
3929   return isVEXTRACTIndex(N, 128);
3930 }
3931
3932 bool X86::isVEXTRACT256Index(SDNode *N) {
3933   return isVEXTRACTIndex(N, 256);
3934 }
3935
3936 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3937   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3938   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3939     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3940
3941   uint64_t Index =
3942     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3943
3944   MVT VecVT = N->getOperand(0).getSimpleValueType();
3945   MVT ElVT = VecVT.getVectorElementType();
3946
3947   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3948   return Index / NumElemsPerChunk;
3949 }
3950
3951 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3952   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3953   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3954     llvm_unreachable("Illegal insert subvector for VINSERT");
3955
3956   uint64_t Index =
3957     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3958
3959   MVT VecVT = N->getSimpleValueType(0);
3960   MVT ElVT = VecVT.getVectorElementType();
3961
3962   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3963   return Index / NumElemsPerChunk;
3964 }
3965
3966 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3967 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3968 /// and VINSERTI128 instructions.
3969 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3970   return getExtractVEXTRACTImmediate(N, 128);
3971 }
3972
3973 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3974 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3975 /// and VINSERTI64x4 instructions.
3976 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3977   return getExtractVEXTRACTImmediate(N, 256);
3978 }
3979
3980 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3981 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3982 /// and VINSERTI128 instructions.
3983 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3984   return getInsertVINSERTImmediate(N, 128);
3985 }
3986
3987 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3988 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3989 /// and VINSERTI64x4 instructions.
3990 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3991   return getInsertVINSERTImmediate(N, 256);
3992 }
3993
3994 /// isZero - Returns true if Elt is a constant integer zero
3995 static bool isZero(SDValue V) {
3996   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3997   return C && C->isNullValue();
3998 }
3999
4000 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4001 /// constant +0.0.
4002 bool X86::isZeroNode(SDValue Elt) {
4003   if (isZero(Elt))
4004     return true;
4005   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4006     return CFP->getValueAPF().isPosZero();
4007   return false;
4008 }
4009
4010 /// getZeroVector - Returns a vector of specified type with all zero elements.
4011 ///
4012 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4013                              SelectionDAG &DAG, SDLoc dl) {
4014   assert(VT.isVector() && "Expected a vector type");
4015
4016   // Always build SSE zero vectors as <4 x i32> bitcasted
4017   // to their dest type. This ensures they get CSE'd.
4018   SDValue Vec;
4019   if (VT.is128BitVector()) {  // SSE
4020     if (Subtarget->hasSSE2()) {  // SSE2
4021       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4022       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4023     } else { // SSE1
4024       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4025       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4026     }
4027   } else if (VT.is256BitVector()) { // AVX
4028     if (Subtarget->hasInt256()) { // AVX2
4029       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4030       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4031       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4032     } else {
4033       // 256-bit logic and arithmetic instructions in AVX are all
4034       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4035       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4036       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4037       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4038     }
4039   } else if (VT.is512BitVector()) { // AVX-512
4040       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4041       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4042                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4043       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4044   } else if (VT.getScalarType() == MVT::i1) {
4045
4046     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4047             && "Unexpected vector type");
4048     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4049             && "Unexpected vector type");
4050     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4051     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4052     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4053   } else
4054     llvm_unreachable("Unexpected vector type");
4055
4056   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4057 }
4058
4059 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4060                                 SelectionDAG &DAG, SDLoc dl,
4061                                 unsigned vectorWidth) {
4062   assert((vectorWidth == 128 || vectorWidth == 256) &&
4063          "Unsupported vector width");
4064   EVT VT = Vec.getValueType();
4065   EVT ElVT = VT.getVectorElementType();
4066   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4067   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4068                                   VT.getVectorNumElements()/Factor);
4069
4070   // Extract from UNDEF is UNDEF.
4071   if (Vec.getOpcode() == ISD::UNDEF)
4072     return DAG.getUNDEF(ResultVT);
4073
4074   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4075   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4076
4077   // This is the index of the first element of the vectorWidth-bit chunk
4078   // we want.
4079   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4080                                * ElemsPerChunk);
4081
4082   // If the input is a buildvector just emit a smaller one.
4083   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4084     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4085                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4086                                     ElemsPerChunk));
4087
4088   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4089   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4090 }
4091
4092 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4093 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4094 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4095 /// instructions or a simple subregister reference. Idx is an index in the
4096 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4097 /// lowering EXTRACT_VECTOR_ELT operations easier.
4098 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4099                                    SelectionDAG &DAG, SDLoc dl) {
4100   assert((Vec.getValueType().is256BitVector() ||
4101           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4102   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4103 }
4104
4105 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4106 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4107                                    SelectionDAG &DAG, SDLoc dl) {
4108   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4109   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4110 }
4111
4112 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4113                                unsigned IdxVal, SelectionDAG &DAG,
4114                                SDLoc dl, unsigned vectorWidth) {
4115   assert((vectorWidth == 128 || vectorWidth == 256) &&
4116          "Unsupported vector width");
4117   // Inserting UNDEF is Result
4118   if (Vec.getOpcode() == ISD::UNDEF)
4119     return Result;
4120   EVT VT = Vec.getValueType();
4121   EVT ElVT = VT.getVectorElementType();
4122   EVT ResultVT = Result.getValueType();
4123
4124   // Insert the relevant vectorWidth bits.
4125   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4126
4127   // This is the index of the first element of the vectorWidth-bit chunk
4128   // we want.
4129   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4130                                * ElemsPerChunk);
4131
4132   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4133   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4134 }
4135
4136 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4137 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4138 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4139 /// simple superregister reference.  Idx is an index in the 128 bits
4140 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4141 /// lowering INSERT_VECTOR_ELT operations easier.
4142 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4143                                   SelectionDAG &DAG, SDLoc dl) {
4144   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4145
4146   // For insertion into the zero index (low half) of a 256-bit vector, it is
4147   // more efficient to generate a blend with immediate instead of an insert*128.
4148   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4149   // extend the subvector to the size of the result vector. Make sure that
4150   // we are not recursing on that node by checking for undef here.
4151   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4152       Result.getOpcode() != ISD::UNDEF) {
4153     EVT ResultVT = Result.getValueType();
4154     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4155     SDValue Undef = DAG.getUNDEF(ResultVT);
4156     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4157                                  Vec, ZeroIndex);
4158
4159     // The blend instruction, and therefore its mask, depend on the data type.
4160     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4161     if (ScalarType.isFloatingPoint()) {
4162       // Choose either vblendps (float) or vblendpd (double).
4163       unsigned ScalarSize = ScalarType.getSizeInBits();
4164       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4165       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4166       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4167       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4168     }
4169
4170     const X86Subtarget &Subtarget =
4171     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4172
4173     // AVX2 is needed for 256-bit integer blend support.
4174     // Integers must be cast to 32-bit because there is only vpblendd;
4175     // vpblendw can't be used for this because it has a handicapped mask.
4176
4177     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4178     // is still more efficient than using the wrong domain vinsertf128 that
4179     // will be created by InsertSubVector().
4180     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4181
4182     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4183     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4184     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4185     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4186   }
4187
4188   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4189 }
4190
4191 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4192                                   SelectionDAG &DAG, SDLoc dl) {
4193   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4194   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4195 }
4196
4197 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4198 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4199 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4200 /// large BUILD_VECTORS.
4201 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4202                                    unsigned NumElems, SelectionDAG &DAG,
4203                                    SDLoc dl) {
4204   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4205   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4206 }
4207
4208 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4209                                    unsigned NumElems, SelectionDAG &DAG,
4210                                    SDLoc dl) {
4211   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4212   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4213 }
4214
4215 /// getOnesVector - Returns a vector of specified type with all bits set.
4216 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4217 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4218 /// Then bitcast to their original type, ensuring they get CSE'd.
4219 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4220                              SDLoc dl) {
4221   assert(VT.isVector() && "Expected a vector type");
4222
4223   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4224   SDValue Vec;
4225   if (VT.is256BitVector()) {
4226     if (HasInt256) { // AVX2
4227       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4228       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4229     } else { // AVX
4230       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4231       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4232     }
4233   } else if (VT.is128BitVector()) {
4234     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4235   } else
4236     llvm_unreachable("Unexpected vector type");
4237
4238   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4239 }
4240
4241 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4242 /// operation of specified width.
4243 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4244                        SDValue V2) {
4245   unsigned NumElems = VT.getVectorNumElements();
4246   SmallVector<int, 8> Mask;
4247   Mask.push_back(NumElems);
4248   for (unsigned i = 1; i != NumElems; ++i)
4249     Mask.push_back(i);
4250   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4251 }
4252
4253 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4254 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4255                           SDValue V2) {
4256   unsigned NumElems = VT.getVectorNumElements();
4257   SmallVector<int, 8> Mask;
4258   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4259     Mask.push_back(i);
4260     Mask.push_back(i + NumElems);
4261   }
4262   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4263 }
4264
4265 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4266 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4267                           SDValue V2) {
4268   unsigned NumElems = VT.getVectorNumElements();
4269   SmallVector<int, 8> Mask;
4270   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4271     Mask.push_back(i + Half);
4272     Mask.push_back(i + NumElems + Half);
4273   }
4274   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4275 }
4276
4277 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4278 /// vector of zero or undef vector.  This produces a shuffle where the low
4279 /// element of V2 is swizzled into the zero/undef vector, landing at element
4280 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4281 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4282                                            bool IsZero,
4283                                            const X86Subtarget *Subtarget,
4284                                            SelectionDAG &DAG) {
4285   MVT VT = V2.getSimpleValueType();
4286   SDValue V1 = IsZero
4287     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4288   unsigned NumElems = VT.getVectorNumElements();
4289   SmallVector<int, 16> MaskVec;
4290   for (unsigned i = 0; i != NumElems; ++i)
4291     // If this is the insertion idx, put the low elt of V2 here.
4292     MaskVec.push_back(i == Idx ? NumElems : i);
4293   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4294 }
4295
4296 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4297 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4298 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4299 /// shuffles which use a single input multiple times, and in those cases it will
4300 /// adjust the mask to only have indices within that single input.
4301 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4302                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4303   unsigned NumElems = VT.getVectorNumElements();
4304   SDValue ImmN;
4305
4306   IsUnary = false;
4307   bool IsFakeUnary = false;
4308   switch(N->getOpcode()) {
4309   case X86ISD::BLENDI:
4310     ImmN = N->getOperand(N->getNumOperands()-1);
4311     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4312     break;
4313   case X86ISD::SHUFP:
4314     ImmN = N->getOperand(N->getNumOperands()-1);
4315     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4316     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4317     break;
4318   case X86ISD::UNPCKH:
4319     DecodeUNPCKHMask(VT, Mask);
4320     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4321     break;
4322   case X86ISD::UNPCKL:
4323     DecodeUNPCKLMask(VT, Mask);
4324     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4325     break;
4326   case X86ISD::MOVHLPS:
4327     DecodeMOVHLPSMask(NumElems, Mask);
4328     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4329     break;
4330   case X86ISD::MOVLHPS:
4331     DecodeMOVLHPSMask(NumElems, Mask);
4332     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4333     break;
4334   case X86ISD::PALIGNR:
4335     ImmN = N->getOperand(N->getNumOperands()-1);
4336     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4337     break;
4338   case X86ISD::PSHUFD:
4339   case X86ISD::VPERMILPI:
4340     ImmN = N->getOperand(N->getNumOperands()-1);
4341     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4342     IsUnary = true;
4343     break;
4344   case X86ISD::PSHUFHW:
4345     ImmN = N->getOperand(N->getNumOperands()-1);
4346     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4347     IsUnary = true;
4348     break;
4349   case X86ISD::PSHUFLW:
4350     ImmN = N->getOperand(N->getNumOperands()-1);
4351     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4352     IsUnary = true;
4353     break;
4354   case X86ISD::PSHUFB: {
4355     IsUnary = true;
4356     SDValue MaskNode = N->getOperand(1);
4357     while (MaskNode->getOpcode() == ISD::BITCAST)
4358       MaskNode = MaskNode->getOperand(0);
4359
4360     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4361       // If we have a build-vector, then things are easy.
4362       EVT VT = MaskNode.getValueType();
4363       assert(VT.isVector() &&
4364              "Can't produce a non-vector with a build_vector!");
4365       if (!VT.isInteger())
4366         return false;
4367
4368       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4369
4370       SmallVector<uint64_t, 32> RawMask;
4371       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4372         SDValue Op = MaskNode->getOperand(i);
4373         if (Op->getOpcode() == ISD::UNDEF) {
4374           RawMask.push_back((uint64_t)SM_SentinelUndef);
4375           continue;
4376         }
4377         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4378         if (!CN)
4379           return false;
4380         APInt MaskElement = CN->getAPIntValue();
4381
4382         // We now have to decode the element which could be any integer size and
4383         // extract each byte of it.
4384         for (int j = 0; j < NumBytesPerElement; ++j) {
4385           // Note that this is x86 and so always little endian: the low byte is
4386           // the first byte of the mask.
4387           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4388           MaskElement = MaskElement.lshr(8);
4389         }
4390       }
4391       DecodePSHUFBMask(RawMask, Mask);
4392       break;
4393     }
4394
4395     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4396     if (!MaskLoad)
4397       return false;
4398
4399     SDValue Ptr = MaskLoad->getBasePtr();
4400     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4401         Ptr->getOpcode() == X86ISD::WrapperRIP)
4402       Ptr = Ptr->getOperand(0);
4403
4404     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4405     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4406       return false;
4407
4408     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4409       DecodePSHUFBMask(C, Mask);
4410       if (Mask.empty())
4411         return false;
4412       break;
4413     }
4414
4415     return false;
4416   }
4417   case X86ISD::VPERMI:
4418     ImmN = N->getOperand(N->getNumOperands()-1);
4419     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4420     IsUnary = true;
4421     break;
4422   case X86ISD::MOVSS:
4423   case X86ISD::MOVSD:
4424     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4425     break;
4426   case X86ISD::VPERM2X128:
4427     ImmN = N->getOperand(N->getNumOperands()-1);
4428     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4429     if (Mask.empty()) return false;
4430     break;
4431   case X86ISD::MOVSLDUP:
4432     DecodeMOVSLDUPMask(VT, Mask);
4433     IsUnary = true;
4434     break;
4435   case X86ISD::MOVSHDUP:
4436     DecodeMOVSHDUPMask(VT, Mask);
4437     IsUnary = true;
4438     break;
4439   case X86ISD::MOVDDUP:
4440     DecodeMOVDDUPMask(VT, Mask);
4441     IsUnary = true;
4442     break;
4443   case X86ISD::MOVLHPD:
4444   case X86ISD::MOVLPD:
4445   case X86ISD::MOVLPS:
4446     // Not yet implemented
4447     return false;
4448   default: llvm_unreachable("unknown target shuffle node");
4449   }
4450
4451   // If we have a fake unary shuffle, the shuffle mask is spread across two
4452   // inputs that are actually the same node. Re-map the mask to always point
4453   // into the first input.
4454   if (IsFakeUnary)
4455     for (int &M : Mask)
4456       if (M >= (int)Mask.size())
4457         M -= Mask.size();
4458
4459   return true;
4460 }
4461
4462 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4463 /// element of the result of the vector shuffle.
4464 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4465                                    unsigned Depth) {
4466   if (Depth == 6)
4467     return SDValue();  // Limit search depth.
4468
4469   SDValue V = SDValue(N, 0);
4470   EVT VT = V.getValueType();
4471   unsigned Opcode = V.getOpcode();
4472
4473   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4474   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4475     int Elt = SV->getMaskElt(Index);
4476
4477     if (Elt < 0)
4478       return DAG.getUNDEF(VT.getVectorElementType());
4479
4480     unsigned NumElems = VT.getVectorNumElements();
4481     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4482                                          : SV->getOperand(1);
4483     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4484   }
4485
4486   // Recurse into target specific vector shuffles to find scalars.
4487   if (isTargetShuffle(Opcode)) {
4488     MVT ShufVT = V.getSimpleValueType();
4489     unsigned NumElems = ShufVT.getVectorNumElements();
4490     SmallVector<int, 16> ShuffleMask;
4491     bool IsUnary;
4492
4493     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4494       return SDValue();
4495
4496     int Elt = ShuffleMask[Index];
4497     if (Elt < 0)
4498       return DAG.getUNDEF(ShufVT.getVectorElementType());
4499
4500     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4501                                          : N->getOperand(1);
4502     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4503                                Depth+1);
4504   }
4505
4506   // Actual nodes that may contain scalar elements
4507   if (Opcode == ISD::BITCAST) {
4508     V = V.getOperand(0);
4509     EVT SrcVT = V.getValueType();
4510     unsigned NumElems = VT.getVectorNumElements();
4511
4512     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4513       return SDValue();
4514   }
4515
4516   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4517     return (Index == 0) ? V.getOperand(0)
4518                         : DAG.getUNDEF(VT.getVectorElementType());
4519
4520   if (V.getOpcode() == ISD::BUILD_VECTOR)
4521     return V.getOperand(Index);
4522
4523   return SDValue();
4524 }
4525
4526 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4527 ///
4528 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4529                                        unsigned NumNonZero, unsigned NumZero,
4530                                        SelectionDAG &DAG,
4531                                        const X86Subtarget* Subtarget,
4532                                        const TargetLowering &TLI) {
4533   if (NumNonZero > 8)
4534     return SDValue();
4535
4536   SDLoc dl(Op);
4537   SDValue V;
4538   bool First = true;
4539
4540   // SSE4.1 - use PINSRB to insert each byte directly.
4541   if (Subtarget->hasSSE41()) {
4542     for (unsigned i = 0; i < 16; ++i) {
4543       bool isNonZero = (NonZeros & (1 << i)) != 0;
4544       if (isNonZero) {
4545         if (First) {
4546           if (NumZero)
4547             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4548           else
4549             V = DAG.getUNDEF(MVT::v16i8);
4550           First = false;
4551         }
4552         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4553                         MVT::v16i8, V, Op.getOperand(i),
4554                         DAG.getIntPtrConstant(i, dl));
4555       }
4556     }
4557
4558     return V;
4559   }
4560
4561   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4562   for (unsigned i = 0; i < 16; ++i) {
4563     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4564     if (ThisIsNonZero && First) {
4565       if (NumZero)
4566         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4567       else
4568         V = DAG.getUNDEF(MVT::v8i16);
4569       First = false;
4570     }
4571
4572     if ((i & 1) != 0) {
4573       SDValue ThisElt, LastElt;
4574       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4575       if (LastIsNonZero) {
4576         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4577                               MVT::i16, Op.getOperand(i-1));
4578       }
4579       if (ThisIsNonZero) {
4580         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4581         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4582                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4583         if (LastIsNonZero)
4584           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4585       } else
4586         ThisElt = LastElt;
4587
4588       if (ThisElt.getNode())
4589         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4590                         DAG.getIntPtrConstant(i/2, dl));
4591     }
4592   }
4593
4594   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4595 }
4596
4597 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4598 ///
4599 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4600                                      unsigned NumNonZero, unsigned NumZero,
4601                                      SelectionDAG &DAG,
4602                                      const X86Subtarget* Subtarget,
4603                                      const TargetLowering &TLI) {
4604   if (NumNonZero > 4)
4605     return SDValue();
4606
4607   SDLoc dl(Op);
4608   SDValue V;
4609   bool First = true;
4610   for (unsigned i = 0; i < 8; ++i) {
4611     bool isNonZero = (NonZeros & (1 << i)) != 0;
4612     if (isNonZero) {
4613       if (First) {
4614         if (NumZero)
4615           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4616         else
4617           V = DAG.getUNDEF(MVT::v8i16);
4618         First = false;
4619       }
4620       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4621                       MVT::v8i16, V, Op.getOperand(i),
4622                       DAG.getIntPtrConstant(i, dl));
4623     }
4624   }
4625
4626   return V;
4627 }
4628
4629 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4630 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4631                                      const X86Subtarget *Subtarget,
4632                                      const TargetLowering &TLI) {
4633   // Find all zeroable elements.
4634   std::bitset<4> Zeroable;
4635   for (int i=0; i < 4; ++i) {
4636     SDValue Elt = Op->getOperand(i);
4637     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4638   }
4639   assert(Zeroable.size() - Zeroable.count() > 1 &&
4640          "We expect at least two non-zero elements!");
4641
4642   // We only know how to deal with build_vector nodes where elements are either
4643   // zeroable or extract_vector_elt with constant index.
4644   SDValue FirstNonZero;
4645   unsigned FirstNonZeroIdx;
4646   for (unsigned i=0; i < 4; ++i) {
4647     if (Zeroable[i])
4648       continue;
4649     SDValue Elt = Op->getOperand(i);
4650     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4651         !isa<ConstantSDNode>(Elt.getOperand(1)))
4652       return SDValue();
4653     // Make sure that this node is extracting from a 128-bit vector.
4654     MVT VT = Elt.getOperand(0).getSimpleValueType();
4655     if (!VT.is128BitVector())
4656       return SDValue();
4657     if (!FirstNonZero.getNode()) {
4658       FirstNonZero = Elt;
4659       FirstNonZeroIdx = i;
4660     }
4661   }
4662
4663   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4664   SDValue V1 = FirstNonZero.getOperand(0);
4665   MVT VT = V1.getSimpleValueType();
4666
4667   // See if this build_vector can be lowered as a blend with zero.
4668   SDValue Elt;
4669   unsigned EltMaskIdx, EltIdx;
4670   int Mask[4];
4671   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4672     if (Zeroable[EltIdx]) {
4673       // The zero vector will be on the right hand side.
4674       Mask[EltIdx] = EltIdx+4;
4675       continue;
4676     }
4677
4678     Elt = Op->getOperand(EltIdx);
4679     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4680     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4681     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4682       break;
4683     Mask[EltIdx] = EltIdx;
4684   }
4685
4686   if (EltIdx == 4) {
4687     // Let the shuffle legalizer deal with blend operations.
4688     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4689     if (V1.getSimpleValueType() != VT)
4690       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4691     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4692   }
4693
4694   // See if we can lower this build_vector to a INSERTPS.
4695   if (!Subtarget->hasSSE41())
4696     return SDValue();
4697
4698   SDValue V2 = Elt.getOperand(0);
4699   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4700     V1 = SDValue();
4701
4702   bool CanFold = true;
4703   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4704     if (Zeroable[i])
4705       continue;
4706
4707     SDValue Current = Op->getOperand(i);
4708     SDValue SrcVector = Current->getOperand(0);
4709     if (!V1.getNode())
4710       V1 = SrcVector;
4711     CanFold = SrcVector == V1 &&
4712       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4713   }
4714
4715   if (!CanFold)
4716     return SDValue();
4717
4718   assert(V1.getNode() && "Expected at least two non-zero elements!");
4719   if (V1.getSimpleValueType() != MVT::v4f32)
4720     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4721   if (V2.getSimpleValueType() != MVT::v4f32)
4722     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4723
4724   // Ok, we can emit an INSERTPS instruction.
4725   unsigned ZMask = Zeroable.to_ulong();
4726
4727   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4728   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4729   SDLoc DL(Op);
4730   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4731                                DAG.getIntPtrConstant(InsertPSMask, DL));
4732   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4733 }
4734
4735 /// Return a vector logical shift node.
4736 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4737                          unsigned NumBits, SelectionDAG &DAG,
4738                          const TargetLowering &TLI, SDLoc dl) {
4739   assert(VT.is128BitVector() && "Unknown type for VShift");
4740   MVT ShVT = MVT::v2i64;
4741   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4742   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4743   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4744   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4745   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4746   return DAG.getNode(ISD::BITCAST, dl, VT,
4747                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4748 }
4749
4750 static SDValue
4751 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4752
4753   // Check if the scalar load can be widened into a vector load. And if
4754   // the address is "base + cst" see if the cst can be "absorbed" into
4755   // the shuffle mask.
4756   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4757     SDValue Ptr = LD->getBasePtr();
4758     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4759       return SDValue();
4760     EVT PVT = LD->getValueType(0);
4761     if (PVT != MVT::i32 && PVT != MVT::f32)
4762       return SDValue();
4763
4764     int FI = -1;
4765     int64_t Offset = 0;
4766     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4767       FI = FINode->getIndex();
4768       Offset = 0;
4769     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4770                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4771       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4772       Offset = Ptr.getConstantOperandVal(1);
4773       Ptr = Ptr.getOperand(0);
4774     } else {
4775       return SDValue();
4776     }
4777
4778     // FIXME: 256-bit vector instructions don't require a strict alignment,
4779     // improve this code to support it better.
4780     unsigned RequiredAlign = VT.getSizeInBits()/8;
4781     SDValue Chain = LD->getChain();
4782     // Make sure the stack object alignment is at least 16 or 32.
4783     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4784     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4785       if (MFI->isFixedObjectIndex(FI)) {
4786         // Can't change the alignment. FIXME: It's possible to compute
4787         // the exact stack offset and reference FI + adjust offset instead.
4788         // If someone *really* cares about this. That's the way to implement it.
4789         return SDValue();
4790       } else {
4791         MFI->setObjectAlignment(FI, RequiredAlign);
4792       }
4793     }
4794
4795     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4796     // Ptr + (Offset & ~15).
4797     if (Offset < 0)
4798       return SDValue();
4799     if ((Offset % RequiredAlign) & 3)
4800       return SDValue();
4801     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4802     if (StartOffset) {
4803       SDLoc DL(Ptr);
4804       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4805                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4806     }
4807
4808     int EltNo = (Offset - StartOffset) >> 2;
4809     unsigned NumElems = VT.getVectorNumElements();
4810
4811     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4812     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4813                              LD->getPointerInfo().getWithOffset(StartOffset),
4814                              false, false, false, 0);
4815
4816     SmallVector<int, 8> Mask(NumElems, EltNo);
4817
4818     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4819   }
4820
4821   return SDValue();
4822 }
4823
4824 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4825 /// elements can be replaced by a single large load which has the same value as
4826 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4827 ///
4828 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4829 ///
4830 /// FIXME: we'd also like to handle the case where the last elements are zero
4831 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4832 /// There's even a handy isZeroNode for that purpose.
4833 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4834                                         SDLoc &DL, SelectionDAG &DAG,
4835                                         bool isAfterLegalize) {
4836   unsigned NumElems = Elts.size();
4837
4838   LoadSDNode *LDBase = nullptr;
4839   unsigned LastLoadedElt = -1U;
4840
4841   // For each element in the initializer, see if we've found a load or an undef.
4842   // If we don't find an initial load element, or later load elements are
4843   // non-consecutive, bail out.
4844   for (unsigned i = 0; i < NumElems; ++i) {
4845     SDValue Elt = Elts[i];
4846     // Look through a bitcast.
4847     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4848       Elt = Elt.getOperand(0);
4849     if (!Elt.getNode() ||
4850         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4851       return SDValue();
4852     if (!LDBase) {
4853       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4854         return SDValue();
4855       LDBase = cast<LoadSDNode>(Elt.getNode());
4856       LastLoadedElt = i;
4857       continue;
4858     }
4859     if (Elt.getOpcode() == ISD::UNDEF)
4860       continue;
4861
4862     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4863     EVT LdVT = Elt.getValueType();
4864     // Each loaded element must be the correct fractional portion of the
4865     // requested vector load.
4866     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4867       return SDValue();
4868     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4869       return SDValue();
4870     LastLoadedElt = i;
4871   }
4872
4873   // If we have found an entire vector of loads and undefs, then return a large
4874   // load of the entire vector width starting at the base pointer.  If we found
4875   // consecutive loads for the low half, generate a vzext_load node.
4876   if (LastLoadedElt == NumElems - 1) {
4877     assert(LDBase && "Did not find base load for merging consecutive loads");
4878     EVT EltVT = LDBase->getValueType(0);
4879     // Ensure that the input vector size for the merged loads matches the
4880     // cumulative size of the input elements.
4881     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4882       return SDValue();
4883
4884     if (isAfterLegalize &&
4885         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4886       return SDValue();
4887
4888     SDValue NewLd = SDValue();
4889
4890     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4891                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4892                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4893                         LDBase->getAlignment());
4894
4895     if (LDBase->hasAnyUseOfValue(1)) {
4896       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4897                                      SDValue(LDBase, 1),
4898                                      SDValue(NewLd.getNode(), 1));
4899       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4900       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4901                              SDValue(NewLd.getNode(), 1));
4902     }
4903
4904     return NewLd;
4905   }
4906
4907   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4908   //of a v4i32 / v4f32. It's probably worth generalizing.
4909   EVT EltVT = VT.getVectorElementType();
4910   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4911       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4912     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4913     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4914     SDValue ResNode =
4915         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4916                                 LDBase->getPointerInfo(),
4917                                 LDBase->getAlignment(),
4918                                 false/*isVolatile*/, true/*ReadMem*/,
4919                                 false/*WriteMem*/);
4920
4921     // Make sure the newly-created LOAD is in the same position as LDBase in
4922     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4923     // update uses of LDBase's output chain to use the TokenFactor.
4924     if (LDBase->hasAnyUseOfValue(1)) {
4925       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4926                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4927       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4928       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4929                              SDValue(ResNode.getNode(), 1));
4930     }
4931
4932     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4933   }
4934   return SDValue();
4935 }
4936
4937 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4938 /// to generate a splat value for the following cases:
4939 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4940 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4941 /// a scalar load, or a constant.
4942 /// The VBROADCAST node is returned when a pattern is found,
4943 /// or SDValue() otherwise.
4944 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4945                                     SelectionDAG &DAG) {
4946   // VBROADCAST requires AVX.
4947   // TODO: Splats could be generated for non-AVX CPUs using SSE
4948   // instructions, but there's less potential gain for only 128-bit vectors.
4949   if (!Subtarget->hasAVX())
4950     return SDValue();
4951
4952   MVT VT = Op.getSimpleValueType();
4953   SDLoc dl(Op);
4954
4955   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4956          "Unsupported vector type for broadcast.");
4957
4958   SDValue Ld;
4959   bool ConstSplatVal;
4960
4961   switch (Op.getOpcode()) {
4962     default:
4963       // Unknown pattern found.
4964       return SDValue();
4965
4966     case ISD::BUILD_VECTOR: {
4967       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4968       BitVector UndefElements;
4969       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4970
4971       // We need a splat of a single value to use broadcast, and it doesn't
4972       // make any sense if the value is only in one element of the vector.
4973       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4974         return SDValue();
4975
4976       Ld = Splat;
4977       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4978                        Ld.getOpcode() == ISD::ConstantFP);
4979
4980       // Make sure that all of the users of a non-constant load are from the
4981       // BUILD_VECTOR node.
4982       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4983         return SDValue();
4984       break;
4985     }
4986
4987     case ISD::VECTOR_SHUFFLE: {
4988       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4989
4990       // Shuffles must have a splat mask where the first element is
4991       // broadcasted.
4992       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4993         return SDValue();
4994
4995       SDValue Sc = Op.getOperand(0);
4996       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4997           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4998
4999         if (!Subtarget->hasInt256())
5000           return SDValue();
5001
5002         // Use the register form of the broadcast instruction available on AVX2.
5003         if (VT.getSizeInBits() >= 256)
5004           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5005         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5006       }
5007
5008       Ld = Sc.getOperand(0);
5009       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5010                        Ld.getOpcode() == ISD::ConstantFP);
5011
5012       // The scalar_to_vector node and the suspected
5013       // load node must have exactly one user.
5014       // Constants may have multiple users.
5015
5016       // AVX-512 has register version of the broadcast
5017       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5018         Ld.getValueType().getSizeInBits() >= 32;
5019       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5020           !hasRegVer))
5021         return SDValue();
5022       break;
5023     }
5024   }
5025
5026   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5027   bool IsGE256 = (VT.getSizeInBits() >= 256);
5028
5029   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5030   // instruction to save 8 or more bytes of constant pool data.
5031   // TODO: If multiple splats are generated to load the same constant,
5032   // it may be detrimental to overall size. There needs to be a way to detect
5033   // that condition to know if this is truly a size win.
5034   const Function *F = DAG.getMachineFunction().getFunction();
5035   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5036
5037   // Handle broadcasting a single constant scalar from the constant pool
5038   // into a vector.
5039   // On Sandybridge (no AVX2), it is still better to load a constant vector
5040   // from the constant pool and not to broadcast it from a scalar.
5041   // But override that restriction when optimizing for size.
5042   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5043   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5044     EVT CVT = Ld.getValueType();
5045     assert(!CVT.isVector() && "Must not broadcast a vector type");
5046
5047     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5048     // For size optimization, also splat v2f64 and v2i64, and for size opt
5049     // with AVX2, also splat i8 and i16.
5050     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5051     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5052         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5053       const Constant *C = nullptr;
5054       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5055         C = CI->getConstantIntValue();
5056       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5057         C = CF->getConstantFPValue();
5058
5059       assert(C && "Invalid constant type");
5060
5061       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5062       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5063       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5064       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5065                        MachinePointerInfo::getConstantPool(),
5066                        false, false, false, Alignment);
5067
5068       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5069     }
5070   }
5071
5072   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5073
5074   // Handle AVX2 in-register broadcasts.
5075   if (!IsLoad && Subtarget->hasInt256() &&
5076       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5077     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5078
5079   // The scalar source must be a normal load.
5080   if (!IsLoad)
5081     return SDValue();
5082
5083   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5084       (Subtarget->hasVLX() && ScalarSize == 64))
5085     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5086
5087   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5088   // double since there is no vbroadcastsd xmm
5089   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5090     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5091       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5092   }
5093
5094   // Unsupported broadcast.
5095   return SDValue();
5096 }
5097
5098 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5099 /// underlying vector and index.
5100 ///
5101 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5102 /// index.
5103 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5104                                          SDValue ExtIdx) {
5105   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5106   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5107     return Idx;
5108
5109   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5110   // lowered this:
5111   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5112   // to:
5113   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5114   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5115   //                           undef)
5116   //                       Constant<0>)
5117   // In this case the vector is the extract_subvector expression and the index
5118   // is 2, as specified by the shuffle.
5119   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5120   SDValue ShuffleVec = SVOp->getOperand(0);
5121   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5122   assert(ShuffleVecVT.getVectorElementType() ==
5123          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5124
5125   int ShuffleIdx = SVOp->getMaskElt(Idx);
5126   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5127     ExtractedFromVec = ShuffleVec;
5128     return ShuffleIdx;
5129   }
5130   return Idx;
5131 }
5132
5133 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5134   MVT VT = Op.getSimpleValueType();
5135
5136   // Skip if insert_vec_elt is not supported.
5137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5138   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5139     return SDValue();
5140
5141   SDLoc DL(Op);
5142   unsigned NumElems = Op.getNumOperands();
5143
5144   SDValue VecIn1;
5145   SDValue VecIn2;
5146   SmallVector<unsigned, 4> InsertIndices;
5147   SmallVector<int, 8> Mask(NumElems, -1);
5148
5149   for (unsigned i = 0; i != NumElems; ++i) {
5150     unsigned Opc = Op.getOperand(i).getOpcode();
5151
5152     if (Opc == ISD::UNDEF)
5153       continue;
5154
5155     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5156       // Quit if more than 1 elements need inserting.
5157       if (InsertIndices.size() > 1)
5158         return SDValue();
5159
5160       InsertIndices.push_back(i);
5161       continue;
5162     }
5163
5164     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5165     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5166     // Quit if non-constant index.
5167     if (!isa<ConstantSDNode>(ExtIdx))
5168       return SDValue();
5169     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5170
5171     // Quit if extracted from vector of different type.
5172     if (ExtractedFromVec.getValueType() != VT)
5173       return SDValue();
5174
5175     if (!VecIn1.getNode())
5176       VecIn1 = ExtractedFromVec;
5177     else if (VecIn1 != ExtractedFromVec) {
5178       if (!VecIn2.getNode())
5179         VecIn2 = ExtractedFromVec;
5180       else if (VecIn2 != ExtractedFromVec)
5181         // Quit if more than 2 vectors to shuffle
5182         return SDValue();
5183     }
5184
5185     if (ExtractedFromVec == VecIn1)
5186       Mask[i] = Idx;
5187     else if (ExtractedFromVec == VecIn2)
5188       Mask[i] = Idx + NumElems;
5189   }
5190
5191   if (!VecIn1.getNode())
5192     return SDValue();
5193
5194   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5195   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5196   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5197     unsigned Idx = InsertIndices[i];
5198     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5199                      DAG.getIntPtrConstant(Idx, DL));
5200   }
5201
5202   return NV;
5203 }
5204
5205 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5206   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5207          Op.getScalarValueSizeInBits() == 1 &&
5208          "Can not convert non-constant vector");
5209   uint64_t Immediate = 0;
5210   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5211     SDValue In = Op.getOperand(idx);
5212     if (In.getOpcode() != ISD::UNDEF)
5213       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5214   }
5215   SDLoc dl(Op);
5216   MVT VT =
5217    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5218   return DAG.getConstant(Immediate, dl, VT);
5219 }
5220 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5221 SDValue
5222 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5223
5224   MVT VT = Op.getSimpleValueType();
5225   assert((VT.getVectorElementType() == MVT::i1) &&
5226          "Unexpected type in LowerBUILD_VECTORvXi1!");
5227
5228   SDLoc dl(Op);
5229   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5230     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5231     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5232     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5233   }
5234
5235   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5236     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5237     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5238     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5239   }
5240
5241   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5242     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5243     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5244       return DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5245     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5246     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5247                         DAG.getIntPtrConstant(0, dl));
5248   }
5249
5250   // Vector has one or more non-const elements
5251   uint64_t Immediate = 0;
5252   SmallVector<unsigned, 16> NonConstIdx;
5253   bool IsSplat = true;
5254   bool HasConstElts = false;
5255   int SplatIdx = -1;
5256   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5257     SDValue In = Op.getOperand(idx);
5258     if (In.getOpcode() == ISD::UNDEF)
5259       continue;
5260     if (!isa<ConstantSDNode>(In)) 
5261       NonConstIdx.push_back(idx);
5262     else {
5263       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5264       HasConstElts = true;
5265     }
5266     if (SplatIdx == -1)
5267       SplatIdx = idx;
5268     else if (In != Op.getOperand(SplatIdx))
5269       IsSplat = false;
5270   }
5271
5272   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5273   if (IsSplat)
5274     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5275                        DAG.getConstant(1, dl, VT),
5276                        DAG.getConstant(0, dl, VT));
5277
5278   // insert elements one by one
5279   SDValue DstVec;
5280   SDValue Imm;
5281   if (Immediate) {
5282     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5283     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5284   }
5285   else if (HasConstElts)
5286     Imm = DAG.getConstant(0, dl, VT);
5287   else 
5288     Imm = DAG.getUNDEF(VT);
5289   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5290     DstVec = DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5291   else {
5292     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5293     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5294                          DAG.getIntPtrConstant(0, dl));
5295   }
5296
5297   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5298     unsigned InsertIdx = NonConstIdx[i];
5299     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5300                          Op.getOperand(InsertIdx),
5301                          DAG.getIntPtrConstant(InsertIdx, dl));
5302   }
5303   return DstVec;
5304 }
5305
5306 /// \brief Return true if \p N implements a horizontal binop and return the
5307 /// operands for the horizontal binop into V0 and V1.
5308 ///
5309 /// This is a helper function of LowerToHorizontalOp().
5310 /// This function checks that the build_vector \p N in input implements a
5311 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5312 /// operation to match.
5313 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5314 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5315 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5316 /// arithmetic sub.
5317 ///
5318 /// This function only analyzes elements of \p N whose indices are
5319 /// in range [BaseIdx, LastIdx).
5320 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5321                               SelectionDAG &DAG,
5322                               unsigned BaseIdx, unsigned LastIdx,
5323                               SDValue &V0, SDValue &V1) {
5324   EVT VT = N->getValueType(0);
5325
5326   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5327   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5328          "Invalid Vector in input!");
5329
5330   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5331   bool CanFold = true;
5332   unsigned ExpectedVExtractIdx = BaseIdx;
5333   unsigned NumElts = LastIdx - BaseIdx;
5334   V0 = DAG.getUNDEF(VT);
5335   V1 = DAG.getUNDEF(VT);
5336
5337   // Check if N implements a horizontal binop.
5338   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5339     SDValue Op = N->getOperand(i + BaseIdx);
5340
5341     // Skip UNDEFs.
5342     if (Op->getOpcode() == ISD::UNDEF) {
5343       // Update the expected vector extract index.
5344       if (i * 2 == NumElts)
5345         ExpectedVExtractIdx = BaseIdx;
5346       ExpectedVExtractIdx += 2;
5347       continue;
5348     }
5349
5350     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5351
5352     if (!CanFold)
5353       break;
5354
5355     SDValue Op0 = Op.getOperand(0);
5356     SDValue Op1 = Op.getOperand(1);
5357
5358     // Try to match the following pattern:
5359     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5360     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5361         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5362         Op0.getOperand(0) == Op1.getOperand(0) &&
5363         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5364         isa<ConstantSDNode>(Op1.getOperand(1)));
5365     if (!CanFold)
5366       break;
5367
5368     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5369     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5370
5371     if (i * 2 < NumElts) {
5372       if (V0.getOpcode() == ISD::UNDEF) {
5373         V0 = Op0.getOperand(0);
5374         if (V0.getValueType() != VT)
5375           return false;
5376       }
5377     } else {
5378       if (V1.getOpcode() == ISD::UNDEF) {
5379         V1 = Op0.getOperand(0);
5380         if (V1.getValueType() != VT)
5381           return false;
5382       }
5383       if (i * 2 == NumElts)
5384         ExpectedVExtractIdx = BaseIdx;
5385     }
5386
5387     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5388     if (I0 == ExpectedVExtractIdx)
5389       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5390     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5391       // Try to match the following dag sequence:
5392       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5393       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5394     } else
5395       CanFold = false;
5396
5397     ExpectedVExtractIdx += 2;
5398   }
5399
5400   return CanFold;
5401 }
5402
5403 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5404 /// a concat_vector.
5405 ///
5406 /// This is a helper function of LowerToHorizontalOp().
5407 /// This function expects two 256-bit vectors called V0 and V1.
5408 /// At first, each vector is split into two separate 128-bit vectors.
5409 /// Then, the resulting 128-bit vectors are used to implement two
5410 /// horizontal binary operations.
5411 ///
5412 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5413 ///
5414 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5415 /// the two new horizontal binop.
5416 /// When Mode is set, the first horizontal binop dag node would take as input
5417 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5418 /// horizontal binop dag node would take as input the lower 128-bit of V1
5419 /// and the upper 128-bit of V1.
5420 ///   Example:
5421 ///     HADD V0_LO, V0_HI
5422 ///     HADD V1_LO, V1_HI
5423 ///
5424 /// Otherwise, the first horizontal binop dag node takes as input the lower
5425 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5426 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5427 ///   Example:
5428 ///     HADD V0_LO, V1_LO
5429 ///     HADD V0_HI, V1_HI
5430 ///
5431 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5432 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5433 /// the upper 128-bits of the result.
5434 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5435                                      SDLoc DL, SelectionDAG &DAG,
5436                                      unsigned X86Opcode, bool Mode,
5437                                      bool isUndefLO, bool isUndefHI) {
5438   EVT VT = V0.getValueType();
5439   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5440          "Invalid nodes in input!");
5441
5442   unsigned NumElts = VT.getVectorNumElements();
5443   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5444   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5445   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5446   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5447   EVT NewVT = V0_LO.getValueType();
5448
5449   SDValue LO = DAG.getUNDEF(NewVT);
5450   SDValue HI = DAG.getUNDEF(NewVT);
5451
5452   if (Mode) {
5453     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5454     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5455       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5456     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5457       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5458   } else {
5459     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5460     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5461                        V1_LO->getOpcode() != ISD::UNDEF))
5462       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5463
5464     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5465                        V1_HI->getOpcode() != ISD::UNDEF))
5466       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5467   }
5468
5469   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5470 }
5471
5472 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5473 /// node.
5474 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5475                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5476   EVT VT = BV->getValueType(0);
5477   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5478       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5479     return SDValue();
5480
5481   SDLoc DL(BV);
5482   unsigned NumElts = VT.getVectorNumElements();
5483   SDValue InVec0 = DAG.getUNDEF(VT);
5484   SDValue InVec1 = DAG.getUNDEF(VT);
5485
5486   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5487           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5488
5489   // Odd-numbered elements in the input build vector are obtained from
5490   // adding two integer/float elements.
5491   // Even-numbered elements in the input build vector are obtained from
5492   // subtracting two integer/float elements.
5493   unsigned ExpectedOpcode = ISD::FSUB;
5494   unsigned NextExpectedOpcode = ISD::FADD;
5495   bool AddFound = false;
5496   bool SubFound = false;
5497
5498   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5499     SDValue Op = BV->getOperand(i);
5500
5501     // Skip 'undef' values.
5502     unsigned Opcode = Op.getOpcode();
5503     if (Opcode == ISD::UNDEF) {
5504       std::swap(ExpectedOpcode, NextExpectedOpcode);
5505       continue;
5506     }
5507
5508     // Early exit if we found an unexpected opcode.
5509     if (Opcode != ExpectedOpcode)
5510       return SDValue();
5511
5512     SDValue Op0 = Op.getOperand(0);
5513     SDValue Op1 = Op.getOperand(1);
5514
5515     // Try to match the following pattern:
5516     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5517     // Early exit if we cannot match that sequence.
5518     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5519         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5520         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5521         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5522         Op0.getOperand(1) != Op1.getOperand(1))
5523       return SDValue();
5524
5525     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5526     if (I0 != i)
5527       return SDValue();
5528
5529     // We found a valid add/sub node. Update the information accordingly.
5530     if (i & 1)
5531       AddFound = true;
5532     else
5533       SubFound = true;
5534
5535     // Update InVec0 and InVec1.
5536     if (InVec0.getOpcode() == ISD::UNDEF) {
5537       InVec0 = Op0.getOperand(0);
5538       if (InVec0.getValueType() != VT)
5539         return SDValue();
5540     }
5541     if (InVec1.getOpcode() == ISD::UNDEF) {
5542       InVec1 = Op1.getOperand(0);
5543       if (InVec1.getValueType() != VT)
5544         return SDValue();
5545     }
5546
5547     // Make sure that operands in input to each add/sub node always
5548     // come from a same pair of vectors.
5549     if (InVec0 != Op0.getOperand(0)) {
5550       if (ExpectedOpcode == ISD::FSUB)
5551         return SDValue();
5552
5553       // FADD is commutable. Try to commute the operands
5554       // and then test again.
5555       std::swap(Op0, Op1);
5556       if (InVec0 != Op0.getOperand(0))
5557         return SDValue();
5558     }
5559
5560     if (InVec1 != Op1.getOperand(0))
5561       return SDValue();
5562
5563     // Update the pair of expected opcodes.
5564     std::swap(ExpectedOpcode, NextExpectedOpcode);
5565   }
5566
5567   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5568   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5569       InVec1.getOpcode() != ISD::UNDEF)
5570     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5571
5572   return SDValue();
5573 }
5574
5575 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5576 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5577                                    const X86Subtarget *Subtarget,
5578                                    SelectionDAG &DAG) {
5579   EVT VT = BV->getValueType(0);
5580   unsigned NumElts = VT.getVectorNumElements();
5581   unsigned NumUndefsLO = 0;
5582   unsigned NumUndefsHI = 0;
5583   unsigned Half = NumElts/2;
5584
5585   // Count the number of UNDEF operands in the build_vector in input.
5586   for (unsigned i = 0, e = Half; i != e; ++i)
5587     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5588       NumUndefsLO++;
5589
5590   for (unsigned i = Half, e = NumElts; i != e; ++i)
5591     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5592       NumUndefsHI++;
5593
5594   // Early exit if this is either a build_vector of all UNDEFs or all the
5595   // operands but one are UNDEF.
5596   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5597     return SDValue();
5598
5599   SDLoc DL(BV);
5600   SDValue InVec0, InVec1;
5601   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5602     // Try to match an SSE3 float HADD/HSUB.
5603     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5604       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5605
5606     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5607       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5608   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5609     // Try to match an SSSE3 integer HADD/HSUB.
5610     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5611       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5612
5613     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5614       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5615   }
5616
5617   if (!Subtarget->hasAVX())
5618     return SDValue();
5619
5620   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5621     // Try to match an AVX horizontal add/sub of packed single/double
5622     // precision floating point values from 256-bit vectors.
5623     SDValue InVec2, InVec3;
5624     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5625         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5626         ((InVec0.getOpcode() == ISD::UNDEF ||
5627           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5628         ((InVec1.getOpcode() == ISD::UNDEF ||
5629           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5630       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5631
5632     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5633         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5634         ((InVec0.getOpcode() == ISD::UNDEF ||
5635           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5636         ((InVec1.getOpcode() == ISD::UNDEF ||
5637           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5638       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5639   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5640     // Try to match an AVX2 horizontal add/sub of signed integers.
5641     SDValue InVec2, InVec3;
5642     unsigned X86Opcode;
5643     bool CanFold = true;
5644
5645     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5646         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5647         ((InVec0.getOpcode() == ISD::UNDEF ||
5648           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5649         ((InVec1.getOpcode() == ISD::UNDEF ||
5650           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5651       X86Opcode = X86ISD::HADD;
5652     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5653         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5654         ((InVec0.getOpcode() == ISD::UNDEF ||
5655           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5656         ((InVec1.getOpcode() == ISD::UNDEF ||
5657           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5658       X86Opcode = X86ISD::HSUB;
5659     else
5660       CanFold = false;
5661
5662     if (CanFold) {
5663       // Fold this build_vector into a single horizontal add/sub.
5664       // Do this only if the target has AVX2.
5665       if (Subtarget->hasAVX2())
5666         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5667
5668       // Do not try to expand this build_vector into a pair of horizontal
5669       // add/sub if we can emit a pair of scalar add/sub.
5670       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5671         return SDValue();
5672
5673       // Convert this build_vector into a pair of horizontal binop followed by
5674       // a concat vector.
5675       bool isUndefLO = NumUndefsLO == Half;
5676       bool isUndefHI = NumUndefsHI == Half;
5677       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5678                                    isUndefLO, isUndefHI);
5679     }
5680   }
5681
5682   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5683        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5684     unsigned X86Opcode;
5685     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5686       X86Opcode = X86ISD::HADD;
5687     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5688       X86Opcode = X86ISD::HSUB;
5689     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5690       X86Opcode = X86ISD::FHADD;
5691     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5692       X86Opcode = X86ISD::FHSUB;
5693     else
5694       return SDValue();
5695
5696     // Don't try to expand this build_vector into a pair of horizontal add/sub
5697     // if we can simply emit a pair of scalar add/sub.
5698     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5699       return SDValue();
5700
5701     // Convert this build_vector into two horizontal add/sub followed by
5702     // a concat vector.
5703     bool isUndefLO = NumUndefsLO == Half;
5704     bool isUndefHI = NumUndefsHI == Half;
5705     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5706                                  isUndefLO, isUndefHI);
5707   }
5708
5709   return SDValue();
5710 }
5711
5712 SDValue
5713 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5714   SDLoc dl(Op);
5715
5716   MVT VT = Op.getSimpleValueType();
5717   MVT ExtVT = VT.getVectorElementType();
5718   unsigned NumElems = Op.getNumOperands();
5719
5720   // Generate vectors for predicate vectors.
5721   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5722     return LowerBUILD_VECTORvXi1(Op, DAG);
5723
5724   // Vectors containing all zeros can be matched by pxor and xorps later
5725   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5726     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5727     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5728     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5729       return Op;
5730
5731     return getZeroVector(VT, Subtarget, DAG, dl);
5732   }
5733
5734   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5735   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5736   // vpcmpeqd on 256-bit vectors.
5737   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5738     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5739       return Op;
5740
5741     if (!VT.is512BitVector())
5742       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5743   }
5744
5745   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5746   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5747     return AddSub;
5748   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5749     return HorizontalOp;
5750   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5751     return Broadcast;
5752
5753   unsigned EVTBits = ExtVT.getSizeInBits();
5754
5755   unsigned NumZero  = 0;
5756   unsigned NumNonZero = 0;
5757   unsigned NonZeros = 0;
5758   bool IsAllConstants = true;
5759   SmallSet<SDValue, 8> Values;
5760   for (unsigned i = 0; i < NumElems; ++i) {
5761     SDValue Elt = Op.getOperand(i);
5762     if (Elt.getOpcode() == ISD::UNDEF)
5763       continue;
5764     Values.insert(Elt);
5765     if (Elt.getOpcode() != ISD::Constant &&
5766         Elt.getOpcode() != ISD::ConstantFP)
5767       IsAllConstants = false;
5768     if (X86::isZeroNode(Elt))
5769       NumZero++;
5770     else {
5771       NonZeros |= (1 << i);
5772       NumNonZero++;
5773     }
5774   }
5775
5776   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5777   if (NumNonZero == 0)
5778     return DAG.getUNDEF(VT);
5779
5780   // Special case for single non-zero, non-undef, element.
5781   if (NumNonZero == 1) {
5782     unsigned Idx = countTrailingZeros(NonZeros);
5783     SDValue Item = Op.getOperand(Idx);
5784
5785     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5786     // the value are obviously zero, truncate the value to i32 and do the
5787     // insertion that way.  Only do this if the value is non-constant or if the
5788     // value is a constant being inserted into element 0.  It is cheaper to do
5789     // a constant pool load than it is to do a movd + shuffle.
5790     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5791         (!IsAllConstants || Idx == 0)) {
5792       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5793         // Handle SSE only.
5794         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5795         EVT VecVT = MVT::v4i32;
5796
5797         // Truncate the value (which may itself be a constant) to i32, and
5798         // convert it to a vector with movd (S2V+shuffle to zero extend).
5799         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5800         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5801         return DAG.getNode(
5802             ISD::BITCAST, dl, VT,
5803             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5804       }
5805     }
5806
5807     // If we have a constant or non-constant insertion into the low element of
5808     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5809     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5810     // depending on what the source datatype is.
5811     if (Idx == 0) {
5812       if (NumZero == 0)
5813         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5814
5815       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5816           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5817         if (VT.is512BitVector()) {
5818           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5819           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5820                              Item, DAG.getIntPtrConstant(0, dl));
5821         }
5822         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5823                "Expected an SSE value type!");
5824         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5825         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5826         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5827       }
5828
5829       // We can't directly insert an i8 or i16 into a vector, so zero extend
5830       // it to i32 first.
5831       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5832         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5833         if (VT.is256BitVector()) {
5834           if (Subtarget->hasAVX()) {
5835             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5836             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5837           } else {
5838             // Without AVX, we need to extend to a 128-bit vector and then
5839             // insert into the 256-bit vector.
5840             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5841             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5842             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5843           }
5844         } else {
5845           assert(VT.is128BitVector() && "Expected an SSE value type!");
5846           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5847           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5848         }
5849         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5850       }
5851     }
5852
5853     // Is it a vector logical left shift?
5854     if (NumElems == 2 && Idx == 1 &&
5855         X86::isZeroNode(Op.getOperand(0)) &&
5856         !X86::isZeroNode(Op.getOperand(1))) {
5857       unsigned NumBits = VT.getSizeInBits();
5858       return getVShift(true, VT,
5859                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5860                                    VT, Op.getOperand(1)),
5861                        NumBits/2, DAG, *this, dl);
5862     }
5863
5864     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5865       return SDValue();
5866
5867     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5868     // is a non-constant being inserted into an element other than the low one,
5869     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5870     // movd/movss) to move this into the low element, then shuffle it into
5871     // place.
5872     if (EVTBits == 32) {
5873       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5874       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5875     }
5876   }
5877
5878   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5879   if (Values.size() == 1) {
5880     if (EVTBits == 32) {
5881       // Instead of a shuffle like this:
5882       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5883       // Check if it's possible to issue this instead.
5884       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5885       unsigned Idx = countTrailingZeros(NonZeros);
5886       SDValue Item = Op.getOperand(Idx);
5887       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5888         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5889     }
5890     return SDValue();
5891   }
5892
5893   // A vector full of immediates; various special cases are already
5894   // handled, so this is best done with a single constant-pool load.
5895   if (IsAllConstants)
5896     return SDValue();
5897
5898   // For AVX-length vectors, see if we can use a vector load to get all of the
5899   // elements, otherwise build the individual 128-bit pieces and use
5900   // shuffles to put them in place.
5901   if (VT.is256BitVector() || VT.is512BitVector()) {
5902     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5903
5904     // Check for a build vector of consecutive loads.
5905     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5906       return LD;
5907
5908     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5909
5910     // Build both the lower and upper subvector.
5911     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5912                                 makeArrayRef(&V[0], NumElems/2));
5913     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5914                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5915
5916     // Recreate the wider vector with the lower and upper part.
5917     if (VT.is256BitVector())
5918       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5919     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5920   }
5921
5922   // Let legalizer expand 2-wide build_vectors.
5923   if (EVTBits == 64) {
5924     if (NumNonZero == 1) {
5925       // One half is zero or undef.
5926       unsigned Idx = countTrailingZeros(NonZeros);
5927       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5928                                  Op.getOperand(Idx));
5929       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5930     }
5931     return SDValue();
5932   }
5933
5934   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5935   if (EVTBits == 8 && NumElems == 16)
5936     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5937                                         Subtarget, *this))
5938       return V;
5939
5940   if (EVTBits == 16 && NumElems == 8)
5941     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5942                                       Subtarget, *this))
5943       return V;
5944
5945   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5946   if (EVTBits == 32 && NumElems == 4)
5947     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5948       return V;
5949
5950   // If element VT is == 32 bits, turn it into a number of shuffles.
5951   SmallVector<SDValue, 8> V(NumElems);
5952   if (NumElems == 4 && NumZero > 0) {
5953     for (unsigned i = 0; i < 4; ++i) {
5954       bool isZero = !(NonZeros & (1 << i));
5955       if (isZero)
5956         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5957       else
5958         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5959     }
5960
5961     for (unsigned i = 0; i < 2; ++i) {
5962       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5963         default: break;
5964         case 0:
5965           V[i] = V[i*2];  // Must be a zero vector.
5966           break;
5967         case 1:
5968           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5969           break;
5970         case 2:
5971           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5972           break;
5973         case 3:
5974           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5975           break;
5976       }
5977     }
5978
5979     bool Reverse1 = (NonZeros & 0x3) == 2;
5980     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5981     int MaskVec[] = {
5982       Reverse1 ? 1 : 0,
5983       Reverse1 ? 0 : 1,
5984       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5985       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5986     };
5987     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5988   }
5989
5990   if (Values.size() > 1 && VT.is128BitVector()) {
5991     // Check for a build vector of consecutive loads.
5992     for (unsigned i = 0; i < NumElems; ++i)
5993       V[i] = Op.getOperand(i);
5994
5995     // Check for elements which are consecutive loads.
5996     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5997       return LD;
5998
5999     // Check for a build vector from mostly shuffle plus few inserting.
6000     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6001       return Sh;
6002
6003     // For SSE 4.1, use insertps to put the high elements into the low element.
6004     if (Subtarget->hasSSE41()) {
6005       SDValue Result;
6006       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6007         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6008       else
6009         Result = DAG.getUNDEF(VT);
6010
6011       for (unsigned i = 1; i < NumElems; ++i) {
6012         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6013         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6014                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6015       }
6016       return Result;
6017     }
6018
6019     // Otherwise, expand into a number of unpckl*, start by extending each of
6020     // our (non-undef) elements to the full vector width with the element in the
6021     // bottom slot of the vector (which generates no code for SSE).
6022     for (unsigned i = 0; i < NumElems; ++i) {
6023       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6024         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6025       else
6026         V[i] = DAG.getUNDEF(VT);
6027     }
6028
6029     // Next, we iteratively mix elements, e.g. for v4f32:
6030     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6031     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6032     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6033     unsigned EltStride = NumElems >> 1;
6034     while (EltStride != 0) {
6035       for (unsigned i = 0; i < EltStride; ++i) {
6036         // If V[i+EltStride] is undef and this is the first round of mixing,
6037         // then it is safe to just drop this shuffle: V[i] is already in the
6038         // right place, the one element (since it's the first round) being
6039         // inserted as undef can be dropped.  This isn't safe for successive
6040         // rounds because they will permute elements within both vectors.
6041         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6042             EltStride == NumElems/2)
6043           continue;
6044
6045         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6046       }
6047       EltStride >>= 1;
6048     }
6049     return V[0];
6050   }
6051   return SDValue();
6052 }
6053
6054 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6055 // to create 256-bit vectors from two other 128-bit ones.
6056 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6057   SDLoc dl(Op);
6058   MVT ResVT = Op.getSimpleValueType();
6059
6060   assert((ResVT.is256BitVector() ||
6061           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6062
6063   SDValue V1 = Op.getOperand(0);
6064   SDValue V2 = Op.getOperand(1);
6065   unsigned NumElems = ResVT.getVectorNumElements();
6066   if (ResVT.is256BitVector())
6067     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6068
6069   if (Op.getNumOperands() == 4) {
6070     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6071                                 ResVT.getVectorNumElements()/2);
6072     SDValue V3 = Op.getOperand(2);
6073     SDValue V4 = Op.getOperand(3);
6074     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6075       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6076   }
6077   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6078 }
6079
6080 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6081                                        const X86Subtarget *Subtarget,
6082                                        SelectionDAG & DAG) {
6083   SDLoc dl(Op);
6084   MVT ResVT = Op.getSimpleValueType();
6085   unsigned NumOfOperands = Op.getNumOperands();
6086
6087   assert(isPowerOf2_32(NumOfOperands) &&
6088          "Unexpected number of operands in CONCAT_VECTORS");
6089
6090   if (NumOfOperands > 2) {
6091     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6092                                   ResVT.getVectorNumElements()/2);
6093     SmallVector<SDValue, 2> Ops;
6094     for (unsigned i = 0; i < NumOfOperands/2; i++)
6095       Ops.push_back(Op.getOperand(i));
6096     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6097     Ops.clear();
6098     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6099       Ops.push_back(Op.getOperand(i));
6100     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6101     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6102   }
6103
6104   SDValue V1 = Op.getOperand(0);
6105   SDValue V2 = Op.getOperand(1);
6106   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6107   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6108
6109   if (IsZeroV1 && IsZeroV2)
6110     return getZeroVector(ResVT, Subtarget, DAG, dl);
6111
6112   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6113   SDValue Undef = DAG.getUNDEF(ResVT);
6114   unsigned NumElems = ResVT.getVectorNumElements();
6115   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6116
6117   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6118   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6119   if (IsZeroV1)
6120     return V2;
6121
6122   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6123   // Zero the upper bits of V1
6124   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6125   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6126   if (IsZeroV2)
6127     return V1;
6128   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6129 }
6130
6131 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6132                                    const X86Subtarget *Subtarget,
6133                                    SelectionDAG &DAG) {
6134   MVT VT = Op.getSimpleValueType();
6135   if (VT.getVectorElementType() == MVT::i1)
6136     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6137
6138   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6139          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6140           Op.getNumOperands() == 4)));
6141
6142   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6143   // from two other 128-bit ones.
6144
6145   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6146   return LowerAVXCONCAT_VECTORS(Op, DAG);
6147 }
6148
6149
6150 //===----------------------------------------------------------------------===//
6151 // Vector shuffle lowering
6152 //
6153 // This is an experimental code path for lowering vector shuffles on x86. It is
6154 // designed to handle arbitrary vector shuffles and blends, gracefully
6155 // degrading performance as necessary. It works hard to recognize idiomatic
6156 // shuffles and lower them to optimal instruction patterns without leaving
6157 // a framework that allows reasonably efficient handling of all vector shuffle
6158 // patterns.
6159 //===----------------------------------------------------------------------===//
6160
6161 /// \brief Tiny helper function to identify a no-op mask.
6162 ///
6163 /// This is a somewhat boring predicate function. It checks whether the mask
6164 /// array input, which is assumed to be a single-input shuffle mask of the kind
6165 /// used by the X86 shuffle instructions (not a fully general
6166 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6167 /// in-place shuffle are 'no-op's.
6168 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6169   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6170     if (Mask[i] != -1 && Mask[i] != i)
6171       return false;
6172   return true;
6173 }
6174
6175 /// \brief Helper function to classify a mask as a single-input mask.
6176 ///
6177 /// This isn't a generic single-input test because in the vector shuffle
6178 /// lowering we canonicalize single inputs to be the first input operand. This
6179 /// means we can more quickly test for a single input by only checking whether
6180 /// an input from the second operand exists. We also assume that the size of
6181 /// mask corresponds to the size of the input vectors which isn't true in the
6182 /// fully general case.
6183 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6184   for (int M : Mask)
6185     if (M >= (int)Mask.size())
6186       return false;
6187   return true;
6188 }
6189
6190 /// \brief Test whether there are elements crossing 128-bit lanes in this
6191 /// shuffle mask.
6192 ///
6193 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6194 /// and we routinely test for these.
6195 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6196   int LaneSize = 128 / VT.getScalarSizeInBits();
6197   int Size = Mask.size();
6198   for (int i = 0; i < Size; ++i)
6199     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6200       return true;
6201   return false;
6202 }
6203
6204 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6205 ///
6206 /// This checks a shuffle mask to see if it is performing the same
6207 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6208 /// that it is also not lane-crossing. It may however involve a blend from the
6209 /// same lane of a second vector.
6210 ///
6211 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6212 /// non-trivial to compute in the face of undef lanes. The representation is
6213 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6214 /// entries from both V1 and V2 inputs to the wider mask.
6215 static bool
6216 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6217                                 SmallVectorImpl<int> &RepeatedMask) {
6218   int LaneSize = 128 / VT.getScalarSizeInBits();
6219   RepeatedMask.resize(LaneSize, -1);
6220   int Size = Mask.size();
6221   for (int i = 0; i < Size; ++i) {
6222     if (Mask[i] < 0)
6223       continue;
6224     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6225       // This entry crosses lanes, so there is no way to model this shuffle.
6226       return false;
6227
6228     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6229     if (RepeatedMask[i % LaneSize] == -1)
6230       // This is the first non-undef entry in this slot of a 128-bit lane.
6231       RepeatedMask[i % LaneSize] =
6232           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6233     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6234       // Found a mismatch with the repeated mask.
6235       return false;
6236   }
6237   return true;
6238 }
6239
6240 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6241 /// arguments.
6242 ///
6243 /// This is a fast way to test a shuffle mask against a fixed pattern:
6244 ///
6245 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6246 ///
6247 /// It returns true if the mask is exactly as wide as the argument list, and
6248 /// each element of the mask is either -1 (signifying undef) or the value given
6249 /// in the argument.
6250 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6251                                 ArrayRef<int> ExpectedMask) {
6252   if (Mask.size() != ExpectedMask.size())
6253     return false;
6254
6255   int Size = Mask.size();
6256
6257   // If the values are build vectors, we can look through them to find
6258   // equivalent inputs that make the shuffles equivalent.
6259   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6260   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6261
6262   for (int i = 0; i < Size; ++i)
6263     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6264       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6265       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6266       if (!MaskBV || !ExpectedBV ||
6267           MaskBV->getOperand(Mask[i] % Size) !=
6268               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6269         return false;
6270     }
6271
6272   return true;
6273 }
6274
6275 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6276 ///
6277 /// This helper function produces an 8-bit shuffle immediate corresponding to
6278 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6279 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6280 /// example.
6281 ///
6282 /// NB: We rely heavily on "undef" masks preserving the input lane.
6283 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6284                                           SelectionDAG &DAG) {
6285   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6286   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6287   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6288   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6289   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6290
6291   unsigned Imm = 0;
6292   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6293   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6294   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6295   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6296   return DAG.getConstant(Imm, DL, MVT::i8);
6297 }
6298
6299 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6300 ///
6301 /// This is used as a fallback approach when first class blend instructions are
6302 /// unavailable. Currently it is only suitable for integer vectors, but could
6303 /// be generalized for floating point vectors if desirable.
6304 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6305                                             SDValue V2, ArrayRef<int> Mask,
6306                                             SelectionDAG &DAG) {
6307   assert(VT.isInteger() && "Only supports integer vector types!");
6308   MVT EltVT = VT.getScalarType();
6309   int NumEltBits = EltVT.getSizeInBits();
6310   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6311   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6312                                     EltVT);
6313   SmallVector<SDValue, 16> MaskOps;
6314   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6315     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6316       return SDValue(); // Shuffled input!
6317     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6318   }
6319
6320   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6321   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6322   // We have to cast V2 around.
6323   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6324   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6325                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6326                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6327                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6328   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6329 }
6330
6331 /// \brief Try to emit a blend instruction for a shuffle.
6332 ///
6333 /// This doesn't do any checks for the availability of instructions for blending
6334 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6335 /// be matched in the backend with the type given. What it does check for is
6336 /// that the shuffle mask is in fact a blend.
6337 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6338                                          SDValue V2, ArrayRef<int> Mask,
6339                                          const X86Subtarget *Subtarget,
6340                                          SelectionDAG &DAG) {
6341   unsigned BlendMask = 0;
6342   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6343     if (Mask[i] >= Size) {
6344       if (Mask[i] != i + Size)
6345         return SDValue(); // Shuffled V2 input!
6346       BlendMask |= 1u << i;
6347       continue;
6348     }
6349     if (Mask[i] >= 0 && Mask[i] != i)
6350       return SDValue(); // Shuffled V1 input!
6351   }
6352   switch (VT.SimpleTy) {
6353   case MVT::v2f64:
6354   case MVT::v4f32:
6355   case MVT::v4f64:
6356   case MVT::v8f32:
6357     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6358                        DAG.getConstant(BlendMask, DL, MVT::i8));
6359
6360   case MVT::v4i64:
6361   case MVT::v8i32:
6362     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6363     // FALLTHROUGH
6364   case MVT::v2i64:
6365   case MVT::v4i32:
6366     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6367     // that instruction.
6368     if (Subtarget->hasAVX2()) {
6369       // Scale the blend by the number of 32-bit dwords per element.
6370       int Scale =  VT.getScalarSizeInBits() / 32;
6371       BlendMask = 0;
6372       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6373         if (Mask[i] >= Size)
6374           for (int j = 0; j < Scale; ++j)
6375             BlendMask |= 1u << (i * Scale + j);
6376
6377       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6378       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6379       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6380       return DAG.getNode(ISD::BITCAST, DL, VT,
6381                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6382                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6383     }
6384     // FALLTHROUGH
6385   case MVT::v8i16: {
6386     // For integer shuffles we need to expand the mask and cast the inputs to
6387     // v8i16s prior to blending.
6388     int Scale = 8 / VT.getVectorNumElements();
6389     BlendMask = 0;
6390     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6391       if (Mask[i] >= Size)
6392         for (int j = 0; j < Scale; ++j)
6393           BlendMask |= 1u << (i * Scale + j);
6394
6395     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6396     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6397     return DAG.getNode(ISD::BITCAST, DL, VT,
6398                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6399                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6400   }
6401
6402   case MVT::v16i16: {
6403     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6404     SmallVector<int, 8> RepeatedMask;
6405     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6406       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6407       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6408       BlendMask = 0;
6409       for (int i = 0; i < 8; ++i)
6410         if (RepeatedMask[i] >= 16)
6411           BlendMask |= 1u << i;
6412       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6413                          DAG.getConstant(BlendMask, DL, MVT::i8));
6414     }
6415   }
6416     // FALLTHROUGH
6417   case MVT::v16i8:
6418   case MVT::v32i8: {
6419     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6420            "256-bit byte-blends require AVX2 support!");
6421
6422     // Scale the blend by the number of bytes per element.
6423     int Scale = VT.getScalarSizeInBits() / 8;
6424
6425     // This form of blend is always done on bytes. Compute the byte vector
6426     // type.
6427     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6428
6429     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6430     // mix of LLVM's code generator and the x86 backend. We tell the code
6431     // generator that boolean values in the elements of an x86 vector register
6432     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6433     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6434     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6435     // of the element (the remaining are ignored) and 0 in that high bit would
6436     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6437     // the LLVM model for boolean values in vector elements gets the relevant
6438     // bit set, it is set backwards and over constrained relative to x86's
6439     // actual model.
6440     SmallVector<SDValue, 32> VSELECTMask;
6441     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6442       for (int j = 0; j < Scale; ++j)
6443         VSELECTMask.push_back(
6444             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6445                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6446                                           MVT::i8));
6447
6448     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6449     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6450     return DAG.getNode(
6451         ISD::BITCAST, DL, VT,
6452         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6453                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6454                     V1, V2));
6455   }
6456
6457   default:
6458     llvm_unreachable("Not a supported integer vector type!");
6459   }
6460 }
6461
6462 /// \brief Try to lower as a blend of elements from two inputs followed by
6463 /// a single-input permutation.
6464 ///
6465 /// This matches the pattern where we can blend elements from two inputs and
6466 /// then reduce the shuffle to a single-input permutation.
6467 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6468                                                    SDValue V2,
6469                                                    ArrayRef<int> Mask,
6470                                                    SelectionDAG &DAG) {
6471   // We build up the blend mask while checking whether a blend is a viable way
6472   // to reduce the shuffle.
6473   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6474   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6475
6476   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6477     if (Mask[i] < 0)
6478       continue;
6479
6480     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6481
6482     if (BlendMask[Mask[i] % Size] == -1)
6483       BlendMask[Mask[i] % Size] = Mask[i];
6484     else if (BlendMask[Mask[i] % Size] != Mask[i])
6485       return SDValue(); // Can't blend in the needed input!
6486
6487     PermuteMask[i] = Mask[i] % Size;
6488   }
6489
6490   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6491   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6492 }
6493
6494 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6495 /// blends and permutes.
6496 ///
6497 /// This matches the extremely common pattern for handling combined
6498 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6499 /// operations. It will try to pick the best arrangement of shuffles and
6500 /// blends.
6501 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6502                                                           SDValue V1,
6503                                                           SDValue V2,
6504                                                           ArrayRef<int> Mask,
6505                                                           SelectionDAG &DAG) {
6506   // Shuffle the input elements into the desired positions in V1 and V2 and
6507   // blend them together.
6508   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6509   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6510   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6511   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6512     if (Mask[i] >= 0 && Mask[i] < Size) {
6513       V1Mask[i] = Mask[i];
6514       BlendMask[i] = i;
6515     } else if (Mask[i] >= Size) {
6516       V2Mask[i] = Mask[i] - Size;
6517       BlendMask[i] = i + Size;
6518     }
6519
6520   // Try to lower with the simpler initial blend strategy unless one of the
6521   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6522   // shuffle may be able to fold with a load or other benefit. However, when
6523   // we'll have to do 2x as many shuffles in order to achieve this, blending
6524   // first is a better strategy.
6525   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6526     if (SDValue BlendPerm =
6527             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6528       return BlendPerm;
6529
6530   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6531   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6532   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6533 }
6534
6535 /// \brief Try to lower a vector shuffle as a byte rotation.
6536 ///
6537 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6538 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6539 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6540 /// try to generically lower a vector shuffle through such an pattern. It
6541 /// does not check for the profitability of lowering either as PALIGNR or
6542 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6543 /// This matches shuffle vectors that look like:
6544 ///
6545 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6546 ///
6547 /// Essentially it concatenates V1 and V2, shifts right by some number of
6548 /// elements, and takes the low elements as the result. Note that while this is
6549 /// specified as a *right shift* because x86 is little-endian, it is a *left
6550 /// rotate* of the vector lanes.
6551 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6552                                               SDValue V2,
6553                                               ArrayRef<int> Mask,
6554                                               const X86Subtarget *Subtarget,
6555                                               SelectionDAG &DAG) {
6556   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6557
6558   int NumElts = Mask.size();
6559   int NumLanes = VT.getSizeInBits() / 128;
6560   int NumLaneElts = NumElts / NumLanes;
6561
6562   // We need to detect various ways of spelling a rotation:
6563   //   [11, 12, 13, 14, 15,  0,  1,  2]
6564   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6565   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6566   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6567   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6568   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6569   int Rotation = 0;
6570   SDValue Lo, Hi;
6571   for (int l = 0; l < NumElts; l += NumLaneElts) {
6572     for (int i = 0; i < NumLaneElts; ++i) {
6573       if (Mask[l + i] == -1)
6574         continue;
6575       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6576
6577       // Get the mod-Size index and lane correct it.
6578       int LaneIdx = (Mask[l + i] % NumElts) - l;
6579       // Make sure it was in this lane.
6580       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6581         return SDValue();
6582
6583       // Determine where a rotated vector would have started.
6584       int StartIdx = i - LaneIdx;
6585       if (StartIdx == 0)
6586         // The identity rotation isn't interesting, stop.
6587         return SDValue();
6588
6589       // If we found the tail of a vector the rotation must be the missing
6590       // front. If we found the head of a vector, it must be how much of the
6591       // head.
6592       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6593
6594       if (Rotation == 0)
6595         Rotation = CandidateRotation;
6596       else if (Rotation != CandidateRotation)
6597         // The rotations don't match, so we can't match this mask.
6598         return SDValue();
6599
6600       // Compute which value this mask is pointing at.
6601       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6602
6603       // Compute which of the two target values this index should be assigned
6604       // to. This reflects whether the high elements are remaining or the low
6605       // elements are remaining.
6606       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6607
6608       // Either set up this value if we've not encountered it before, or check
6609       // that it remains consistent.
6610       if (!TargetV)
6611         TargetV = MaskV;
6612       else if (TargetV != MaskV)
6613         // This may be a rotation, but it pulls from the inputs in some
6614         // unsupported interleaving.
6615         return SDValue();
6616     }
6617   }
6618
6619   // Check that we successfully analyzed the mask, and normalize the results.
6620   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6621   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6622   if (!Lo)
6623     Lo = Hi;
6624   else if (!Hi)
6625     Hi = Lo;
6626
6627   // The actual rotate instruction rotates bytes, so we need to scale the
6628   // rotation based on how many bytes are in the vector lane.
6629   int Scale = 16 / NumLaneElts;
6630
6631   // SSSE3 targets can use the palignr instruction.
6632   if (Subtarget->hasSSSE3()) {
6633     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6634     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6635     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6636     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6637
6638     return DAG.getNode(ISD::BITCAST, DL, VT,
6639                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6640                                    DAG.getConstant(Rotation * Scale, DL,
6641                                                    MVT::i8)));
6642   }
6643
6644   assert(VT.getSizeInBits() == 128 &&
6645          "Rotate-based lowering only supports 128-bit lowering!");
6646   assert(Mask.size() <= 16 &&
6647          "Can shuffle at most 16 bytes in a 128-bit vector!");
6648
6649   // Default SSE2 implementation
6650   int LoByteShift = 16 - Rotation * Scale;
6651   int HiByteShift = Rotation * Scale;
6652
6653   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6654   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6655   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6656
6657   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6658                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6659   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6660                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6661   return DAG.getNode(ISD::BITCAST, DL, VT,
6662                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6663 }
6664
6665 /// \brief Compute whether each element of a shuffle is zeroable.
6666 ///
6667 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6668 /// Either it is an undef element in the shuffle mask, the element of the input
6669 /// referenced is undef, or the element of the input referenced is known to be
6670 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6671 /// as many lanes with this technique as possible to simplify the remaining
6672 /// shuffle.
6673 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6674                                                      SDValue V1, SDValue V2) {
6675   SmallBitVector Zeroable(Mask.size(), false);
6676
6677   while (V1.getOpcode() == ISD::BITCAST)
6678     V1 = V1->getOperand(0);
6679   while (V2.getOpcode() == ISD::BITCAST)
6680     V2 = V2->getOperand(0);
6681
6682   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6683   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6684
6685   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6686     int M = Mask[i];
6687     // Handle the easy cases.
6688     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6689       Zeroable[i] = true;
6690       continue;
6691     }
6692
6693     // If this is an index into a build_vector node (which has the same number
6694     // of elements), dig out the input value and use it.
6695     SDValue V = M < Size ? V1 : V2;
6696     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6697       continue;
6698
6699     SDValue Input = V.getOperand(M % Size);
6700     // The UNDEF opcode check really should be dead code here, but not quite
6701     // worth asserting on (it isn't invalid, just unexpected).
6702     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6703       Zeroable[i] = true;
6704   }
6705
6706   return Zeroable;
6707 }
6708
6709 /// \brief Try to emit a bitmask instruction for a shuffle.
6710 ///
6711 /// This handles cases where we can model a blend exactly as a bitmask due to
6712 /// one of the inputs being zeroable.
6713 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6714                                            SDValue V2, ArrayRef<int> Mask,
6715                                            SelectionDAG &DAG) {
6716   MVT EltVT = VT.getScalarType();
6717   int NumEltBits = EltVT.getSizeInBits();
6718   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6719   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6720   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6721                                     IntEltVT);
6722   if (EltVT.isFloatingPoint()) {
6723     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6724     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6725   }
6726   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6727   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6728   SDValue V;
6729   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6730     if (Zeroable[i])
6731       continue;
6732     if (Mask[i] % Size != i)
6733       return SDValue(); // Not a blend.
6734     if (!V)
6735       V = Mask[i] < Size ? V1 : V2;
6736     else if (V != (Mask[i] < Size ? V1 : V2))
6737       return SDValue(); // Can only let one input through the mask.
6738
6739     VMaskOps[i] = AllOnes;
6740   }
6741   if (!V)
6742     return SDValue(); // No non-zeroable elements!
6743
6744   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6745   V = DAG.getNode(VT.isFloatingPoint()
6746                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6747                   DL, VT, V, VMask);
6748   return V;
6749 }
6750
6751 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6752 ///
6753 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6754 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6755 /// matches elements from one of the input vectors shuffled to the left or
6756 /// right with zeroable elements 'shifted in'. It handles both the strictly
6757 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6758 /// quad word lane.
6759 ///
6760 /// PSHL : (little-endian) left bit shift.
6761 /// [ zz, 0, zz,  2 ]
6762 /// [ -1, 4, zz, -1 ]
6763 /// PSRL : (little-endian) right bit shift.
6764 /// [  1, zz,  3, zz]
6765 /// [ -1, -1,  7, zz]
6766 /// PSLLDQ : (little-endian) left byte shift
6767 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6768 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6769 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6770 /// PSRLDQ : (little-endian) right byte shift
6771 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6772 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6773 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6774 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6775                                          SDValue V2, ArrayRef<int> Mask,
6776                                          SelectionDAG &DAG) {
6777   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6778
6779   int Size = Mask.size();
6780   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6781
6782   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6783     for (int i = 0; i < Size; i += Scale)
6784       for (int j = 0; j < Shift; ++j)
6785         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6786           return false;
6787
6788     return true;
6789   };
6790
6791   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6792     for (int i = 0; i != Size; i += Scale) {
6793       unsigned Pos = Left ? i + Shift : i;
6794       unsigned Low = Left ? i : i + Shift;
6795       unsigned Len = Scale - Shift;
6796       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6797                                       Low + (V == V1 ? 0 : Size)))
6798         return SDValue();
6799     }
6800
6801     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6802     bool ByteShift = ShiftEltBits > 64;
6803     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6804                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6805     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6806
6807     // Normalize the scale for byte shifts to still produce an i64 element
6808     // type.
6809     Scale = ByteShift ? Scale / 2 : Scale;
6810
6811     // We need to round trip through the appropriate type for the shift.
6812     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6813     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6814     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6815            "Illegal integer vector type");
6816     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6817
6818     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6819                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6820     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6821   };
6822
6823   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6824   // keep doubling the size of the integer elements up to that. We can
6825   // then shift the elements of the integer vector by whole multiples of
6826   // their width within the elements of the larger integer vector. Test each
6827   // multiple to see if we can find a match with the moved element indices
6828   // and that the shifted in elements are all zeroable.
6829   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6830     for (int Shift = 1; Shift != Scale; ++Shift)
6831       for (bool Left : {true, false})
6832         if (CheckZeros(Shift, Scale, Left))
6833           for (SDValue V : {V1, V2})
6834             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6835               return Match;
6836
6837   // no match
6838   return SDValue();
6839 }
6840
6841 /// \brief Lower a vector shuffle as a zero or any extension.
6842 ///
6843 /// Given a specific number of elements, element bit width, and extension
6844 /// stride, produce either a zero or any extension based on the available
6845 /// features of the subtarget.
6846 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6847     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6848     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6849   assert(Scale > 1 && "Need a scale to extend.");
6850   int NumElements = VT.getVectorNumElements();
6851   int EltBits = VT.getScalarSizeInBits();
6852   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6853          "Only 8, 16, and 32 bit elements can be extended.");
6854   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6855
6856   // Found a valid zext mask! Try various lowering strategies based on the
6857   // input type and available ISA extensions.
6858   if (Subtarget->hasSSE41()) {
6859     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6860                                  NumElements / Scale);
6861     return DAG.getNode(ISD::BITCAST, DL, VT,
6862                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6863   }
6864
6865   // For any extends we can cheat for larger element sizes and use shuffle
6866   // instructions that can fold with a load and/or copy.
6867   if (AnyExt && EltBits == 32) {
6868     int PSHUFDMask[4] = {0, -1, 1, -1};
6869     return DAG.getNode(
6870         ISD::BITCAST, DL, VT,
6871         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6872                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6873                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6874   }
6875   if (AnyExt && EltBits == 16 && Scale > 2) {
6876     int PSHUFDMask[4] = {0, -1, 0, -1};
6877     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6878                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6879                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6880     int PSHUFHWMask[4] = {1, -1, -1, -1};
6881     return DAG.getNode(
6882         ISD::BITCAST, DL, VT,
6883         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6884                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6885                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6886   }
6887
6888   // If this would require more than 2 unpack instructions to expand, use
6889   // pshufb when available. We can only use more than 2 unpack instructions
6890   // when zero extending i8 elements which also makes it easier to use pshufb.
6891   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6892     assert(NumElements == 16 && "Unexpected byte vector width!");
6893     SDValue PSHUFBMask[16];
6894     for (int i = 0; i < 16; ++i)
6895       PSHUFBMask[i] =
6896           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6897     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6898     return DAG.getNode(ISD::BITCAST, DL, VT,
6899                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6900                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6901                                                MVT::v16i8, PSHUFBMask)));
6902   }
6903
6904   // Otherwise emit a sequence of unpacks.
6905   do {
6906     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6907     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6908                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6909     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6910     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6911     Scale /= 2;
6912     EltBits *= 2;
6913     NumElements /= 2;
6914   } while (Scale > 1);
6915   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6916 }
6917
6918 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6919 ///
6920 /// This routine will try to do everything in its power to cleverly lower
6921 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6922 /// check for the profitability of this lowering,  it tries to aggressively
6923 /// match this pattern. It will use all of the micro-architectural details it
6924 /// can to emit an efficient lowering. It handles both blends with all-zero
6925 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6926 /// masking out later).
6927 ///
6928 /// The reason we have dedicated lowering for zext-style shuffles is that they
6929 /// are both incredibly common and often quite performance sensitive.
6930 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6931     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6932     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6933   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6934
6935   int Bits = VT.getSizeInBits();
6936   int NumElements = VT.getVectorNumElements();
6937   assert(VT.getScalarSizeInBits() <= 32 &&
6938          "Exceeds 32-bit integer zero extension limit");
6939   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6940
6941   // Define a helper function to check a particular ext-scale and lower to it if
6942   // valid.
6943   auto Lower = [&](int Scale) -> SDValue {
6944     SDValue InputV;
6945     bool AnyExt = true;
6946     for (int i = 0; i < NumElements; ++i) {
6947       if (Mask[i] == -1)
6948         continue; // Valid anywhere but doesn't tell us anything.
6949       if (i % Scale != 0) {
6950         // Each of the extended elements need to be zeroable.
6951         if (!Zeroable[i])
6952           return SDValue();
6953
6954         // We no longer are in the anyext case.
6955         AnyExt = false;
6956         continue;
6957       }
6958
6959       // Each of the base elements needs to be consecutive indices into the
6960       // same input vector.
6961       SDValue V = Mask[i] < NumElements ? V1 : V2;
6962       if (!InputV)
6963         InputV = V;
6964       else if (InputV != V)
6965         return SDValue(); // Flip-flopping inputs.
6966
6967       if (Mask[i] % NumElements != i / Scale)
6968         return SDValue(); // Non-consecutive strided elements.
6969     }
6970
6971     // If we fail to find an input, we have a zero-shuffle which should always
6972     // have already been handled.
6973     // FIXME: Maybe handle this here in case during blending we end up with one?
6974     if (!InputV)
6975       return SDValue();
6976
6977     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6978         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6979   };
6980
6981   // The widest scale possible for extending is to a 64-bit integer.
6982   assert(Bits % 64 == 0 &&
6983          "The number of bits in a vector must be divisible by 64 on x86!");
6984   int NumExtElements = Bits / 64;
6985
6986   // Each iteration, try extending the elements half as much, but into twice as
6987   // many elements.
6988   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6989     assert(NumElements % NumExtElements == 0 &&
6990            "The input vector size must be divisible by the extended size.");
6991     if (SDValue V = Lower(NumElements / NumExtElements))
6992       return V;
6993   }
6994
6995   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6996   if (Bits != 128)
6997     return SDValue();
6998
6999   // Returns one of the source operands if the shuffle can be reduced to a
7000   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7001   auto CanZExtLowHalf = [&]() {
7002     for (int i = NumElements / 2; i != NumElements; ++i)
7003       if (!Zeroable[i])
7004         return SDValue();
7005     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7006       return V1;
7007     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7008       return V2;
7009     return SDValue();
7010   };
7011
7012   if (SDValue V = CanZExtLowHalf()) {
7013     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
7014     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7015     return DAG.getNode(ISD::BITCAST, DL, VT, V);
7016   }
7017
7018   // No viable ext lowering found.
7019   return SDValue();
7020 }
7021
7022 /// \brief Try to get a scalar value for a specific element of a vector.
7023 ///
7024 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7025 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7026                                               SelectionDAG &DAG) {
7027   MVT VT = V.getSimpleValueType();
7028   MVT EltVT = VT.getVectorElementType();
7029   while (V.getOpcode() == ISD::BITCAST)
7030     V = V.getOperand(0);
7031   // If the bitcasts shift the element size, we can't extract an equivalent
7032   // element from it.
7033   MVT NewVT = V.getSimpleValueType();
7034   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7035     return SDValue();
7036
7037   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7038       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7039     // Ensure the scalar operand is the same size as the destination.
7040     // FIXME: Add support for scalar truncation where possible.
7041     SDValue S = V.getOperand(Idx);
7042     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7043       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7044   }
7045
7046   return SDValue();
7047 }
7048
7049 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7050 ///
7051 /// This is particularly important because the set of instructions varies
7052 /// significantly based on whether the operand is a load or not.
7053 static bool isShuffleFoldableLoad(SDValue V) {
7054   while (V.getOpcode() == ISD::BITCAST)
7055     V = V.getOperand(0);
7056
7057   return ISD::isNON_EXTLoad(V.getNode());
7058 }
7059
7060 /// \brief Try to lower insertion of a single element into a zero vector.
7061 ///
7062 /// This is a common pattern that we have especially efficient patterns to lower
7063 /// across all subtarget feature sets.
7064 static SDValue lowerVectorShuffleAsElementInsertion(
7065     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7066     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7067   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7068   MVT ExtVT = VT;
7069   MVT EltVT = VT.getVectorElementType();
7070
7071   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7072                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7073                 Mask.begin();
7074   bool IsV1Zeroable = true;
7075   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7076     if (i != V2Index && !Zeroable[i]) {
7077       IsV1Zeroable = false;
7078       break;
7079     }
7080
7081   // Check for a single input from a SCALAR_TO_VECTOR node.
7082   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7083   // all the smarts here sunk into that routine. However, the current
7084   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7085   // vector shuffle lowering is dead.
7086   if (SDValue V2S = getScalarValueForVectorElement(
7087           V2, Mask[V2Index] - Mask.size(), DAG)) {
7088     // We need to zext the scalar if it is smaller than an i32.
7089     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7090     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7091       // Using zext to expand a narrow element won't work for non-zero
7092       // insertions.
7093       if (!IsV1Zeroable)
7094         return SDValue();
7095
7096       // Zero-extend directly to i32.
7097       ExtVT = MVT::v4i32;
7098       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7099     }
7100     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7101   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7102              EltVT == MVT::i16) {
7103     // Either not inserting from the low element of the input or the input
7104     // element size is too small to use VZEXT_MOVL to clear the high bits.
7105     return SDValue();
7106   }
7107
7108   if (!IsV1Zeroable) {
7109     // If V1 can't be treated as a zero vector we have fewer options to lower
7110     // this. We can't support integer vectors or non-zero targets cheaply, and
7111     // the V1 elements can't be permuted in any way.
7112     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7113     if (!VT.isFloatingPoint() || V2Index != 0)
7114       return SDValue();
7115     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7116     V1Mask[V2Index] = -1;
7117     if (!isNoopShuffleMask(V1Mask))
7118       return SDValue();
7119     // This is essentially a special case blend operation, but if we have
7120     // general purpose blend operations, they are always faster. Bail and let
7121     // the rest of the lowering handle these as blends.
7122     if (Subtarget->hasSSE41())
7123       return SDValue();
7124
7125     // Otherwise, use MOVSD or MOVSS.
7126     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7127            "Only two types of floating point element types to handle!");
7128     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7129                        ExtVT, V1, V2);
7130   }
7131
7132   // This lowering only works for the low element with floating point vectors.
7133   if (VT.isFloatingPoint() && V2Index != 0)
7134     return SDValue();
7135
7136   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7137   if (ExtVT != VT)
7138     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7139
7140   if (V2Index != 0) {
7141     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7142     // the desired position. Otherwise it is more efficient to do a vector
7143     // shift left. We know that we can do a vector shift left because all
7144     // the inputs are zero.
7145     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7146       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7147       V2Shuffle[V2Index] = 0;
7148       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7149     } else {
7150       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7151       V2 = DAG.getNode(
7152           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7153           DAG.getConstant(
7154               V2Index * EltVT.getSizeInBits()/8, DL,
7155               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7156       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7157     }
7158   }
7159   return V2;
7160 }
7161
7162 /// \brief Try to lower broadcast of a single element.
7163 ///
7164 /// For convenience, this code also bundles all of the subtarget feature set
7165 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7166 /// a convenient way to factor it out.
7167 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7168                                              ArrayRef<int> Mask,
7169                                              const X86Subtarget *Subtarget,
7170                                              SelectionDAG &DAG) {
7171   if (!Subtarget->hasAVX())
7172     return SDValue();
7173   if (VT.isInteger() && !Subtarget->hasAVX2())
7174     return SDValue();
7175
7176   // Check that the mask is a broadcast.
7177   int BroadcastIdx = -1;
7178   for (int M : Mask)
7179     if (M >= 0 && BroadcastIdx == -1)
7180       BroadcastIdx = M;
7181     else if (M >= 0 && M != BroadcastIdx)
7182       return SDValue();
7183
7184   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7185                                             "a sorted mask where the broadcast "
7186                                             "comes from V1.");
7187
7188   // Go up the chain of (vector) values to find a scalar load that we can
7189   // combine with the broadcast.
7190   for (;;) {
7191     switch (V.getOpcode()) {
7192     case ISD::CONCAT_VECTORS: {
7193       int OperandSize = Mask.size() / V.getNumOperands();
7194       V = V.getOperand(BroadcastIdx / OperandSize);
7195       BroadcastIdx %= OperandSize;
7196       continue;
7197     }
7198
7199     case ISD::INSERT_SUBVECTOR: {
7200       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7201       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7202       if (!ConstantIdx)
7203         break;
7204
7205       int BeginIdx = (int)ConstantIdx->getZExtValue();
7206       int EndIdx =
7207           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7208       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7209         BroadcastIdx -= BeginIdx;
7210         V = VInner;
7211       } else {
7212         V = VOuter;
7213       }
7214       continue;
7215     }
7216     }
7217     break;
7218   }
7219
7220   // Check if this is a broadcast of a scalar. We special case lowering
7221   // for scalars so that we can more effectively fold with loads.
7222   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7223       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7224     V = V.getOperand(BroadcastIdx);
7225
7226     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7227     // Only AVX2 has register broadcasts.
7228     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7229       return SDValue();
7230   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7231     // We can't broadcast from a vector register without AVX2, and we can only
7232     // broadcast from the zero-element of a vector register.
7233     return SDValue();
7234   }
7235
7236   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7237 }
7238
7239 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7240 // INSERTPS when the V1 elements are already in the correct locations
7241 // because otherwise we can just always use two SHUFPS instructions which
7242 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7243 // perform INSERTPS if a single V1 element is out of place and all V2
7244 // elements are zeroable.
7245 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7246                                             ArrayRef<int> Mask,
7247                                             SelectionDAG &DAG) {
7248   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7249   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7250   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7251   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7252
7253   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7254
7255   unsigned ZMask = 0;
7256   int V1DstIndex = -1;
7257   int V2DstIndex = -1;
7258   bool V1UsedInPlace = false;
7259
7260   for (int i = 0; i < 4; ++i) {
7261     // Synthesize a zero mask from the zeroable elements (includes undefs).
7262     if (Zeroable[i]) {
7263       ZMask |= 1 << i;
7264       continue;
7265     }
7266
7267     // Flag if we use any V1 inputs in place.
7268     if (i == Mask[i]) {
7269       V1UsedInPlace = true;
7270       continue;
7271     }
7272
7273     // We can only insert a single non-zeroable element.
7274     if (V1DstIndex != -1 || V2DstIndex != -1)
7275       return SDValue();
7276
7277     if (Mask[i] < 4) {
7278       // V1 input out of place for insertion.
7279       V1DstIndex = i;
7280     } else {
7281       // V2 input for insertion.
7282       V2DstIndex = i;
7283     }
7284   }
7285
7286   // Don't bother if we have no (non-zeroable) element for insertion.
7287   if (V1DstIndex == -1 && V2DstIndex == -1)
7288     return SDValue();
7289
7290   // Determine element insertion src/dst indices. The src index is from the
7291   // start of the inserted vector, not the start of the concatenated vector.
7292   unsigned V2SrcIndex = 0;
7293   if (V1DstIndex != -1) {
7294     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7295     // and don't use the original V2 at all.
7296     V2SrcIndex = Mask[V1DstIndex];
7297     V2DstIndex = V1DstIndex;
7298     V2 = V1;
7299   } else {
7300     V2SrcIndex = Mask[V2DstIndex] - 4;
7301   }
7302
7303   // If no V1 inputs are used in place, then the result is created only from
7304   // the zero mask and the V2 insertion - so remove V1 dependency.
7305   if (!V1UsedInPlace)
7306     V1 = DAG.getUNDEF(MVT::v4f32);
7307
7308   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7309   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7310
7311   // Insert the V2 element into the desired position.
7312   SDLoc DL(Op);
7313   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7314                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7315 }
7316
7317 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7318 /// UNPCK instruction.
7319 ///
7320 /// This specifically targets cases where we end up with alternating between
7321 /// the two inputs, and so can permute them into something that feeds a single
7322 /// UNPCK instruction. Note that this routine only targets integer vectors
7323 /// because for floating point vectors we have a generalized SHUFPS lowering
7324 /// strategy that handles everything that doesn't *exactly* match an unpack,
7325 /// making this clever lowering unnecessary.
7326 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7327                                           SDValue V2, ArrayRef<int> Mask,
7328                                           SelectionDAG &DAG) {
7329   assert(!VT.isFloatingPoint() &&
7330          "This routine only supports integer vectors.");
7331   assert(!isSingleInputShuffleMask(Mask) &&
7332          "This routine should only be used when blending two inputs.");
7333   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7334
7335   int Size = Mask.size();
7336
7337   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7338     return M >= 0 && M % Size < Size / 2;
7339   });
7340   int NumHiInputs = std::count_if(
7341       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7342
7343   bool UnpackLo = NumLoInputs >= NumHiInputs;
7344
7345   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7346     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7347     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7348
7349     for (int i = 0; i < Size; ++i) {
7350       if (Mask[i] < 0)
7351         continue;
7352
7353       // Each element of the unpack contains Scale elements from this mask.
7354       int UnpackIdx = i / Scale;
7355
7356       // We only handle the case where V1 feeds the first slots of the unpack.
7357       // We rely on canonicalization to ensure this is the case.
7358       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7359         return SDValue();
7360
7361       // Setup the mask for this input. The indexing is tricky as we have to
7362       // handle the unpack stride.
7363       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7364       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7365           Mask[i] % Size;
7366     }
7367
7368     // If we will have to shuffle both inputs to use the unpack, check whether
7369     // we can just unpack first and shuffle the result. If so, skip this unpack.
7370     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7371         !isNoopShuffleMask(V2Mask))
7372       return SDValue();
7373
7374     // Shuffle the inputs into place.
7375     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7376     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7377
7378     // Cast the inputs to the type we will use to unpack them.
7379     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7380     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7381
7382     // Unpack the inputs and cast the result back to the desired type.
7383     return DAG.getNode(ISD::BITCAST, DL, VT,
7384                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7385                                    DL, UnpackVT, V1, V2));
7386   };
7387
7388   // We try each unpack from the largest to the smallest to try and find one
7389   // that fits this mask.
7390   int OrigNumElements = VT.getVectorNumElements();
7391   int OrigScalarSize = VT.getScalarSizeInBits();
7392   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7393     int Scale = ScalarSize / OrigScalarSize;
7394     int NumElements = OrigNumElements / Scale;
7395     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7396     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7397       return Unpack;
7398   }
7399
7400   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7401   // initial unpack.
7402   if (NumLoInputs == 0 || NumHiInputs == 0) {
7403     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7404            "We have to have *some* inputs!");
7405     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7406
7407     // FIXME: We could consider the total complexity of the permute of each
7408     // possible unpacking. Or at the least we should consider how many
7409     // half-crossings are created.
7410     // FIXME: We could consider commuting the unpacks.
7411
7412     SmallVector<int, 32> PermMask;
7413     PermMask.assign(Size, -1);
7414     for (int i = 0; i < Size; ++i) {
7415       if (Mask[i] < 0)
7416         continue;
7417
7418       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7419
7420       PermMask[i] =
7421           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7422     }
7423     return DAG.getVectorShuffle(
7424         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7425                             DL, VT, V1, V2),
7426         DAG.getUNDEF(VT), PermMask);
7427   }
7428
7429   return SDValue();
7430 }
7431
7432 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7433 ///
7434 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7435 /// support for floating point shuffles but not integer shuffles. These
7436 /// instructions will incur a domain crossing penalty on some chips though so
7437 /// it is better to avoid lowering through this for integer vectors where
7438 /// possible.
7439 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7440                                        const X86Subtarget *Subtarget,
7441                                        SelectionDAG &DAG) {
7442   SDLoc DL(Op);
7443   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7444   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7445   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7446   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7447   ArrayRef<int> Mask = SVOp->getMask();
7448   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7449
7450   if (isSingleInputShuffleMask(Mask)) {
7451     // Use low duplicate instructions for masks that match their pattern.
7452     if (Subtarget->hasSSE3())
7453       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7454         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7455
7456     // Straight shuffle of a single input vector. Simulate this by using the
7457     // single input as both of the "inputs" to this instruction..
7458     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7459
7460     if (Subtarget->hasAVX()) {
7461       // If we have AVX, we can use VPERMILPS which will allow folding a load
7462       // into the shuffle.
7463       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7464                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7465     }
7466
7467     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7468                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7469   }
7470   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7471   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7472
7473   // If we have a single input, insert that into V1 if we can do so cheaply.
7474   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7475     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7476             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7477       return Insertion;
7478     // Try inverting the insertion since for v2 masks it is easy to do and we
7479     // can't reliably sort the mask one way or the other.
7480     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7481                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7482     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7483             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7484       return Insertion;
7485   }
7486
7487   // Try to use one of the special instruction patterns to handle two common
7488   // blend patterns if a zero-blend above didn't work.
7489   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7490       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7491     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7492       // We can either use a special instruction to load over the low double or
7493       // to move just the low double.
7494       return DAG.getNode(
7495           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7496           DL, MVT::v2f64, V2,
7497           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7498
7499   if (Subtarget->hasSSE41())
7500     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7501                                                   Subtarget, DAG))
7502       return Blend;
7503
7504   // Use dedicated unpack instructions for masks that match their pattern.
7505   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7506     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7507   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7508     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7509
7510   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7511   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7512                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7513 }
7514
7515 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7516 ///
7517 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7518 /// the integer unit to minimize domain crossing penalties. However, for blends
7519 /// it falls back to the floating point shuffle operation with appropriate bit
7520 /// casting.
7521 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7522                                        const X86Subtarget *Subtarget,
7523                                        SelectionDAG &DAG) {
7524   SDLoc DL(Op);
7525   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7526   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7527   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7528   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7529   ArrayRef<int> Mask = SVOp->getMask();
7530   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7531
7532   if (isSingleInputShuffleMask(Mask)) {
7533     // Check for being able to broadcast a single element.
7534     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7535                                                           Mask, Subtarget, DAG))
7536       return Broadcast;
7537
7538     // Straight shuffle of a single input vector. For everything from SSE2
7539     // onward this has a single fast instruction with no scary immediates.
7540     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7541     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7542     int WidenedMask[4] = {
7543         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7544         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7545     return DAG.getNode(
7546         ISD::BITCAST, DL, MVT::v2i64,
7547         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7548                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7549   }
7550   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7551   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7552   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7553   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7554
7555   // If we have a blend of two PACKUS operations an the blend aligns with the
7556   // low and half halves, we can just merge the PACKUS operations. This is
7557   // particularly important as it lets us merge shuffles that this routine itself
7558   // creates.
7559   auto GetPackNode = [](SDValue V) {
7560     while (V.getOpcode() == ISD::BITCAST)
7561       V = V.getOperand(0);
7562
7563     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7564   };
7565   if (SDValue V1Pack = GetPackNode(V1))
7566     if (SDValue V2Pack = GetPackNode(V2))
7567       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7568                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7569                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7570                                                   : V1Pack.getOperand(1),
7571                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7572                                                   : V2Pack.getOperand(1)));
7573
7574   // Try to use shift instructions.
7575   if (SDValue Shift =
7576           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7577     return Shift;
7578
7579   // When loading a scalar and then shuffling it into a vector we can often do
7580   // the insertion cheaply.
7581   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7582           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7583     return Insertion;
7584   // Try inverting the insertion since for v2 masks it is easy to do and we
7585   // can't reliably sort the mask one way or the other.
7586   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7587   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7588           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7589     return Insertion;
7590
7591   // We have different paths for blend lowering, but they all must use the
7592   // *exact* same predicate.
7593   bool IsBlendSupported = Subtarget->hasSSE41();
7594   if (IsBlendSupported)
7595     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7596                                                   Subtarget, DAG))
7597       return Blend;
7598
7599   // Use dedicated unpack instructions for masks that match their pattern.
7600   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7601     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7602   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7603     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7604
7605   // Try to use byte rotation instructions.
7606   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7607   if (Subtarget->hasSSSE3())
7608     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7609             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7610       return Rotate;
7611
7612   // If we have direct support for blends, we should lower by decomposing into
7613   // a permute. That will be faster than the domain cross.
7614   if (IsBlendSupported)
7615     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7616                                                       Mask, DAG);
7617
7618   // We implement this with SHUFPD which is pretty lame because it will likely
7619   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7620   // However, all the alternatives are still more cycles and newer chips don't
7621   // have this problem. It would be really nice if x86 had better shuffles here.
7622   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7623   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7624   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7625                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7626 }
7627
7628 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7629 ///
7630 /// This is used to disable more specialized lowerings when the shufps lowering
7631 /// will happen to be efficient.
7632 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7633   // This routine only handles 128-bit shufps.
7634   assert(Mask.size() == 4 && "Unsupported mask size!");
7635
7636   // To lower with a single SHUFPS we need to have the low half and high half
7637   // each requiring a single input.
7638   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7639     return false;
7640   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7641     return false;
7642
7643   return true;
7644 }
7645
7646 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7647 ///
7648 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7649 /// It makes no assumptions about whether this is the *best* lowering, it simply
7650 /// uses it.
7651 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7652                                             ArrayRef<int> Mask, SDValue V1,
7653                                             SDValue V2, SelectionDAG &DAG) {
7654   SDValue LowV = V1, HighV = V2;
7655   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7656
7657   int NumV2Elements =
7658       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7659
7660   if (NumV2Elements == 1) {
7661     int V2Index =
7662         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7663         Mask.begin();
7664
7665     // Compute the index adjacent to V2Index and in the same half by toggling
7666     // the low bit.
7667     int V2AdjIndex = V2Index ^ 1;
7668
7669     if (Mask[V2AdjIndex] == -1) {
7670       // Handles all the cases where we have a single V2 element and an undef.
7671       // This will only ever happen in the high lanes because we commute the
7672       // vector otherwise.
7673       if (V2Index < 2)
7674         std::swap(LowV, HighV);
7675       NewMask[V2Index] -= 4;
7676     } else {
7677       // Handle the case where the V2 element ends up adjacent to a V1 element.
7678       // To make this work, blend them together as the first step.
7679       int V1Index = V2AdjIndex;
7680       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7681       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7682                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7683
7684       // Now proceed to reconstruct the final blend as we have the necessary
7685       // high or low half formed.
7686       if (V2Index < 2) {
7687         LowV = V2;
7688         HighV = V1;
7689       } else {
7690         HighV = V2;
7691       }
7692       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7693       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7694     }
7695   } else if (NumV2Elements == 2) {
7696     if (Mask[0] < 4 && Mask[1] < 4) {
7697       // Handle the easy case where we have V1 in the low lanes and V2 in the
7698       // high lanes.
7699       NewMask[2] -= 4;
7700       NewMask[3] -= 4;
7701     } else if (Mask[2] < 4 && Mask[3] < 4) {
7702       // We also handle the reversed case because this utility may get called
7703       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7704       // arrange things in the right direction.
7705       NewMask[0] -= 4;
7706       NewMask[1] -= 4;
7707       HighV = V1;
7708       LowV = V2;
7709     } else {
7710       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7711       // trying to place elements directly, just blend them and set up the final
7712       // shuffle to place them.
7713
7714       // The first two blend mask elements are for V1, the second two are for
7715       // V2.
7716       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7717                           Mask[2] < 4 ? Mask[2] : Mask[3],
7718                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7719                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7720       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7721                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7722
7723       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7724       // a blend.
7725       LowV = HighV = V1;
7726       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7727       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7728       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7729       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7730     }
7731   }
7732   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7733                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7734 }
7735
7736 /// \brief Lower 4-lane 32-bit floating point shuffles.
7737 ///
7738 /// Uses instructions exclusively from the floating point unit to minimize
7739 /// domain crossing penalties, as these are sufficient to implement all v4f32
7740 /// shuffles.
7741 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7742                                        const X86Subtarget *Subtarget,
7743                                        SelectionDAG &DAG) {
7744   SDLoc DL(Op);
7745   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7746   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7747   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7748   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7749   ArrayRef<int> Mask = SVOp->getMask();
7750   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7751
7752   int NumV2Elements =
7753       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7754
7755   if (NumV2Elements == 0) {
7756     // Check for being able to broadcast a single element.
7757     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7758                                                           Mask, Subtarget, DAG))
7759       return Broadcast;
7760
7761     // Use even/odd duplicate instructions for masks that match their pattern.
7762     if (Subtarget->hasSSE3()) {
7763       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7764         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7765       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7766         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7767     }
7768
7769     if (Subtarget->hasAVX()) {
7770       // If we have AVX, we can use VPERMILPS which will allow folding a load
7771       // into the shuffle.
7772       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7773                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7774     }
7775
7776     // Otherwise, use a straight shuffle of a single input vector. We pass the
7777     // input vector to both operands to simulate this with a SHUFPS.
7778     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7779                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7780   }
7781
7782   // There are special ways we can lower some single-element blends. However, we
7783   // have custom ways we can lower more complex single-element blends below that
7784   // we defer to if both this and BLENDPS fail to match, so restrict this to
7785   // when the V2 input is targeting element 0 of the mask -- that is the fast
7786   // case here.
7787   if (NumV2Elements == 1 && Mask[0] >= 4)
7788     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7789                                                          Mask, Subtarget, DAG))
7790       return V;
7791
7792   if (Subtarget->hasSSE41()) {
7793     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7794                                                   Subtarget, DAG))
7795       return Blend;
7796
7797     // Use INSERTPS if we can complete the shuffle efficiently.
7798     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7799       return V;
7800
7801     if (!isSingleSHUFPSMask(Mask))
7802       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7803               DL, MVT::v4f32, V1, V2, Mask, DAG))
7804         return BlendPerm;
7805   }
7806
7807   // Use dedicated unpack instructions for masks that match their pattern.
7808   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7809     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7810   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7811     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7812   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7813     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7814   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7815     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7816
7817   // Otherwise fall back to a SHUFPS lowering strategy.
7818   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7819 }
7820
7821 /// \brief Lower 4-lane i32 vector shuffles.
7822 ///
7823 /// We try to handle these with integer-domain shuffles where we can, but for
7824 /// blends we use the floating point domain blend instructions.
7825 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7826                                        const X86Subtarget *Subtarget,
7827                                        SelectionDAG &DAG) {
7828   SDLoc DL(Op);
7829   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7830   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7831   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7832   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7833   ArrayRef<int> Mask = SVOp->getMask();
7834   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7835
7836   // Whenever we can lower this as a zext, that instruction is strictly faster
7837   // than any alternative. It also allows us to fold memory operands into the
7838   // shuffle in many cases.
7839   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7840                                                          Mask, Subtarget, DAG))
7841     return ZExt;
7842
7843   int NumV2Elements =
7844       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7845
7846   if (NumV2Elements == 0) {
7847     // Check for being able to broadcast a single element.
7848     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7849                                                           Mask, Subtarget, DAG))
7850       return Broadcast;
7851
7852     // Straight shuffle of a single input vector. For everything from SSE2
7853     // onward this has a single fast instruction with no scary immediates.
7854     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7855     // but we aren't actually going to use the UNPCK instruction because doing
7856     // so prevents folding a load into this instruction or making a copy.
7857     const int UnpackLoMask[] = {0, 0, 1, 1};
7858     const int UnpackHiMask[] = {2, 2, 3, 3};
7859     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7860       Mask = UnpackLoMask;
7861     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7862       Mask = UnpackHiMask;
7863
7864     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7865                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7866   }
7867
7868   // Try to use shift instructions.
7869   if (SDValue Shift =
7870           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7871     return Shift;
7872
7873   // There are special ways we can lower some single-element blends.
7874   if (NumV2Elements == 1)
7875     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7876                                                          Mask, Subtarget, DAG))
7877       return V;
7878
7879   // We have different paths for blend lowering, but they all must use the
7880   // *exact* same predicate.
7881   bool IsBlendSupported = Subtarget->hasSSE41();
7882   if (IsBlendSupported)
7883     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7884                                                   Subtarget, DAG))
7885       return Blend;
7886
7887   if (SDValue Masked =
7888           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7889     return Masked;
7890
7891   // Use dedicated unpack instructions for masks that match their pattern.
7892   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7893     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7894   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7895     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7896   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7897     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7898   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7899     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7900
7901   // Try to use byte rotation instructions.
7902   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7903   if (Subtarget->hasSSSE3())
7904     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7905             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7906       return Rotate;
7907
7908   // If we have direct support for blends, we should lower by decomposing into
7909   // a permute. That will be faster than the domain cross.
7910   if (IsBlendSupported)
7911     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7912                                                       Mask, DAG);
7913
7914   // Try to lower by permuting the inputs into an unpack instruction.
7915   if (SDValue Unpack =
7916           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7917     return Unpack;
7918
7919   // We implement this with SHUFPS because it can blend from two vectors.
7920   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7921   // up the inputs, bypassing domain shift penalties that we would encur if we
7922   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7923   // relevant.
7924   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7925                      DAG.getVectorShuffle(
7926                          MVT::v4f32, DL,
7927                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7928                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7929 }
7930
7931 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7932 /// shuffle lowering, and the most complex part.
7933 ///
7934 /// The lowering strategy is to try to form pairs of input lanes which are
7935 /// targeted at the same half of the final vector, and then use a dword shuffle
7936 /// to place them onto the right half, and finally unpack the paired lanes into
7937 /// their final position.
7938 ///
7939 /// The exact breakdown of how to form these dword pairs and align them on the
7940 /// correct sides is really tricky. See the comments within the function for
7941 /// more of the details.
7942 ///
7943 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7944 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7945 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7946 /// vector, form the analogous 128-bit 8-element Mask.
7947 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7948     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7949     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7950   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7951   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7952
7953   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7954   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7955   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7956
7957   SmallVector<int, 4> LoInputs;
7958   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7959                [](int M) { return M >= 0; });
7960   std::sort(LoInputs.begin(), LoInputs.end());
7961   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7962   SmallVector<int, 4> HiInputs;
7963   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7964                [](int M) { return M >= 0; });
7965   std::sort(HiInputs.begin(), HiInputs.end());
7966   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7967   int NumLToL =
7968       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7969   int NumHToL = LoInputs.size() - NumLToL;
7970   int NumLToH =
7971       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7972   int NumHToH = HiInputs.size() - NumLToH;
7973   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7974   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7975   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7976   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7977
7978   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7979   // such inputs we can swap two of the dwords across the half mark and end up
7980   // with <=2 inputs to each half in each half. Once there, we can fall through
7981   // to the generic code below. For example:
7982   //
7983   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7984   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7985   //
7986   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7987   // and an existing 2-into-2 on the other half. In this case we may have to
7988   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7989   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7990   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7991   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7992   // half than the one we target for fixing) will be fixed when we re-enter this
7993   // path. We will also combine away any sequence of PSHUFD instructions that
7994   // result into a single instruction. Here is an example of the tricky case:
7995   //
7996   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7997   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7998   //
7999   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8000   //
8001   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8002   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8003   //
8004   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8005   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8006   //
8007   // The result is fine to be handled by the generic logic.
8008   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8009                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8010                           int AOffset, int BOffset) {
8011     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8012            "Must call this with A having 3 or 1 inputs from the A half.");
8013     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8014            "Must call this with B having 1 or 3 inputs from the B half.");
8015     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8016            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8017
8018     // Compute the index of dword with only one word among the three inputs in
8019     // a half by taking the sum of the half with three inputs and subtracting
8020     // the sum of the actual three inputs. The difference is the remaining
8021     // slot.
8022     int ADWord, BDWord;
8023     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8024     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8025     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8026     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8027     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8028     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8029     int TripleNonInputIdx =
8030         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8031     TripleDWord = TripleNonInputIdx / 2;
8032
8033     // We use xor with one to compute the adjacent DWord to whichever one the
8034     // OneInput is in.
8035     OneInputDWord = (OneInput / 2) ^ 1;
8036
8037     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8038     // and BToA inputs. If there is also such a problem with the BToB and AToB
8039     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8040     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8041     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8042     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8043       // Compute how many inputs will be flipped by swapping these DWords. We
8044       // need
8045       // to balance this to ensure we don't form a 3-1 shuffle in the other
8046       // half.
8047       int NumFlippedAToBInputs =
8048           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8049           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8050       int NumFlippedBToBInputs =
8051           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8052           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8053       if ((NumFlippedAToBInputs == 1 &&
8054            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8055           (NumFlippedBToBInputs == 1 &&
8056            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8057         // We choose whether to fix the A half or B half based on whether that
8058         // half has zero flipped inputs. At zero, we may not be able to fix it
8059         // with that half. We also bias towards fixing the B half because that
8060         // will more commonly be the high half, and we have to bias one way.
8061         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8062                                                        ArrayRef<int> Inputs) {
8063           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8064           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8065                                          PinnedIdx ^ 1) != Inputs.end();
8066           // Determine whether the free index is in the flipped dword or the
8067           // unflipped dword based on where the pinned index is. We use this bit
8068           // in an xor to conditionally select the adjacent dword.
8069           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8070           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8071                                              FixFreeIdx) != Inputs.end();
8072           if (IsFixIdxInput == IsFixFreeIdxInput)
8073             FixFreeIdx += 1;
8074           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8075                                         FixFreeIdx) != Inputs.end();
8076           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8077                  "We need to be changing the number of flipped inputs!");
8078           int PSHUFHalfMask[] = {0, 1, 2, 3};
8079           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8080           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8081                           MVT::v8i16, V,
8082                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8083
8084           for (int &M : Mask)
8085             if (M != -1 && M == FixIdx)
8086               M = FixFreeIdx;
8087             else if (M != -1 && M == FixFreeIdx)
8088               M = FixIdx;
8089         };
8090         if (NumFlippedBToBInputs != 0) {
8091           int BPinnedIdx =
8092               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8093           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8094         } else {
8095           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8096           int APinnedIdx =
8097               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8098           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8099         }
8100       }
8101     }
8102
8103     int PSHUFDMask[] = {0, 1, 2, 3};
8104     PSHUFDMask[ADWord] = BDWord;
8105     PSHUFDMask[BDWord] = ADWord;
8106     V = DAG.getNode(ISD::BITCAST, DL, VT,
8107                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8108                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8109                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8110                                                            DAG)));
8111
8112     // Adjust the mask to match the new locations of A and B.
8113     for (int &M : Mask)
8114       if (M != -1 && M/2 == ADWord)
8115         M = 2 * BDWord + M % 2;
8116       else if (M != -1 && M/2 == BDWord)
8117         M = 2 * ADWord + M % 2;
8118
8119     // Recurse back into this routine to re-compute state now that this isn't
8120     // a 3 and 1 problem.
8121     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8122                                                      DAG);
8123   };
8124   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8125     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8126   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8127     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8128
8129   // At this point there are at most two inputs to the low and high halves from
8130   // each half. That means the inputs can always be grouped into dwords and
8131   // those dwords can then be moved to the correct half with a dword shuffle.
8132   // We use at most one low and one high word shuffle to collect these paired
8133   // inputs into dwords, and finally a dword shuffle to place them.
8134   int PSHUFLMask[4] = {-1, -1, -1, -1};
8135   int PSHUFHMask[4] = {-1, -1, -1, -1};
8136   int PSHUFDMask[4] = {-1, -1, -1, -1};
8137
8138   // First fix the masks for all the inputs that are staying in their
8139   // original halves. This will then dictate the targets of the cross-half
8140   // shuffles.
8141   auto fixInPlaceInputs =
8142       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8143                     MutableArrayRef<int> SourceHalfMask,
8144                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8145     if (InPlaceInputs.empty())
8146       return;
8147     if (InPlaceInputs.size() == 1) {
8148       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8149           InPlaceInputs[0] - HalfOffset;
8150       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8151       return;
8152     }
8153     if (IncomingInputs.empty()) {
8154       // Just fix all of the in place inputs.
8155       for (int Input : InPlaceInputs) {
8156         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8157         PSHUFDMask[Input / 2] = Input / 2;
8158       }
8159       return;
8160     }
8161
8162     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8163     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8164         InPlaceInputs[0] - HalfOffset;
8165     // Put the second input next to the first so that they are packed into
8166     // a dword. We find the adjacent index by toggling the low bit.
8167     int AdjIndex = InPlaceInputs[0] ^ 1;
8168     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8169     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8170     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8171   };
8172   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8173   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8174
8175   // Now gather the cross-half inputs and place them into a free dword of
8176   // their target half.
8177   // FIXME: This operation could almost certainly be simplified dramatically to
8178   // look more like the 3-1 fixing operation.
8179   auto moveInputsToRightHalf = [&PSHUFDMask](
8180       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8181       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8182       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8183       int DestOffset) {
8184     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8185       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8186     };
8187     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8188                                                int Word) {
8189       int LowWord = Word & ~1;
8190       int HighWord = Word | 1;
8191       return isWordClobbered(SourceHalfMask, LowWord) ||
8192              isWordClobbered(SourceHalfMask, HighWord);
8193     };
8194
8195     if (IncomingInputs.empty())
8196       return;
8197
8198     if (ExistingInputs.empty()) {
8199       // Map any dwords with inputs from them into the right half.
8200       for (int Input : IncomingInputs) {
8201         // If the source half mask maps over the inputs, turn those into
8202         // swaps and use the swapped lane.
8203         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8204           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8205             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8206                 Input - SourceOffset;
8207             // We have to swap the uses in our half mask in one sweep.
8208             for (int &M : HalfMask)
8209               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8210                 M = Input;
8211               else if (M == Input)
8212                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8213           } else {
8214             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8215                        Input - SourceOffset &&
8216                    "Previous placement doesn't match!");
8217           }
8218           // Note that this correctly re-maps both when we do a swap and when
8219           // we observe the other side of the swap above. We rely on that to
8220           // avoid swapping the members of the input list directly.
8221           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8222         }
8223
8224         // Map the input's dword into the correct half.
8225         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8226           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8227         else
8228           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8229                      Input / 2 &&
8230                  "Previous placement doesn't match!");
8231       }
8232
8233       // And just directly shift any other-half mask elements to be same-half
8234       // as we will have mirrored the dword containing the element into the
8235       // same position within that half.
8236       for (int &M : HalfMask)
8237         if (M >= SourceOffset && M < SourceOffset + 4) {
8238           M = M - SourceOffset + DestOffset;
8239           assert(M >= 0 && "This should never wrap below zero!");
8240         }
8241       return;
8242     }
8243
8244     // Ensure we have the input in a viable dword of its current half. This
8245     // is particularly tricky because the original position may be clobbered
8246     // by inputs being moved and *staying* in that half.
8247     if (IncomingInputs.size() == 1) {
8248       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8249         int InputFixed = std::find(std::begin(SourceHalfMask),
8250                                    std::end(SourceHalfMask), -1) -
8251                          std::begin(SourceHalfMask) + SourceOffset;
8252         SourceHalfMask[InputFixed - SourceOffset] =
8253             IncomingInputs[0] - SourceOffset;
8254         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8255                      InputFixed);
8256         IncomingInputs[0] = InputFixed;
8257       }
8258     } else if (IncomingInputs.size() == 2) {
8259       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8260           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8261         // We have two non-adjacent or clobbered inputs we need to extract from
8262         // the source half. To do this, we need to map them into some adjacent
8263         // dword slot in the source mask.
8264         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8265                               IncomingInputs[1] - SourceOffset};
8266
8267         // If there is a free slot in the source half mask adjacent to one of
8268         // the inputs, place the other input in it. We use (Index XOR 1) to
8269         // compute an adjacent index.
8270         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8271             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8272           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8273           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8274           InputsFixed[1] = InputsFixed[0] ^ 1;
8275         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8276                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8277           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8278           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8279           InputsFixed[0] = InputsFixed[1] ^ 1;
8280         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8281                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8282           // The two inputs are in the same DWord but it is clobbered and the
8283           // adjacent DWord isn't used at all. Move both inputs to the free
8284           // slot.
8285           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8286           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8287           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8288           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8289         } else {
8290           // The only way we hit this point is if there is no clobbering
8291           // (because there are no off-half inputs to this half) and there is no
8292           // free slot adjacent to one of the inputs. In this case, we have to
8293           // swap an input with a non-input.
8294           for (int i = 0; i < 4; ++i)
8295             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8296                    "We can't handle any clobbers here!");
8297           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8298                  "Cannot have adjacent inputs here!");
8299
8300           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8301           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8302
8303           // We also have to update the final source mask in this case because
8304           // it may need to undo the above swap.
8305           for (int &M : FinalSourceHalfMask)
8306             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8307               M = InputsFixed[1] + SourceOffset;
8308             else if (M == InputsFixed[1] + SourceOffset)
8309               M = (InputsFixed[0] ^ 1) + SourceOffset;
8310
8311           InputsFixed[1] = InputsFixed[0] ^ 1;
8312         }
8313
8314         // Point everything at the fixed inputs.
8315         for (int &M : HalfMask)
8316           if (M == IncomingInputs[0])
8317             M = InputsFixed[0] + SourceOffset;
8318           else if (M == IncomingInputs[1])
8319             M = InputsFixed[1] + SourceOffset;
8320
8321         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8322         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8323       }
8324     } else {
8325       llvm_unreachable("Unhandled input size!");
8326     }
8327
8328     // Now hoist the DWord down to the right half.
8329     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8330     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8331     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8332     for (int &M : HalfMask)
8333       for (int Input : IncomingInputs)
8334         if (M == Input)
8335           M = FreeDWord * 2 + Input % 2;
8336   };
8337   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8338                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8339   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8340                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8341
8342   // Now enact all the shuffles we've computed to move the inputs into their
8343   // target half.
8344   if (!isNoopShuffleMask(PSHUFLMask))
8345     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8346                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8347   if (!isNoopShuffleMask(PSHUFHMask))
8348     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8349                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8350   if (!isNoopShuffleMask(PSHUFDMask))
8351     V = DAG.getNode(ISD::BITCAST, DL, VT,
8352                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8353                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8354                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8355                                                            DAG)));
8356
8357   // At this point, each half should contain all its inputs, and we can then
8358   // just shuffle them into their final position.
8359   assert(std::count_if(LoMask.begin(), LoMask.end(),
8360                        [](int M) { return M >= 4; }) == 0 &&
8361          "Failed to lift all the high half inputs to the low mask!");
8362   assert(std::count_if(HiMask.begin(), HiMask.end(),
8363                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8364          "Failed to lift all the low half inputs to the high mask!");
8365
8366   // Do a half shuffle for the low mask.
8367   if (!isNoopShuffleMask(LoMask))
8368     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8369                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8370
8371   // Do a half shuffle with the high mask after shifting its values down.
8372   for (int &M : HiMask)
8373     if (M >= 0)
8374       M -= 4;
8375   if (!isNoopShuffleMask(HiMask))
8376     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8377                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8378
8379   return V;
8380 }
8381
8382 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8383 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8384                                           SDValue V2, ArrayRef<int> Mask,
8385                                           SelectionDAG &DAG, bool &V1InUse,
8386                                           bool &V2InUse) {
8387   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8388   SDValue V1Mask[16];
8389   SDValue V2Mask[16];
8390   V1InUse = false;
8391   V2InUse = false;
8392
8393   int Size = Mask.size();
8394   int Scale = 16 / Size;
8395   for (int i = 0; i < 16; ++i) {
8396     if (Mask[i / Scale] == -1) {
8397       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8398     } else {
8399       const int ZeroMask = 0x80;
8400       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8401                                           : ZeroMask;
8402       int V2Idx = Mask[i / Scale] < Size
8403                       ? ZeroMask
8404                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8405       if (Zeroable[i / Scale])
8406         V1Idx = V2Idx = ZeroMask;
8407       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8408       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8409       V1InUse |= (ZeroMask != V1Idx);
8410       V2InUse |= (ZeroMask != V2Idx);
8411     }
8412   }
8413
8414   if (V1InUse)
8415     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8416                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8417                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8418   if (V2InUse)
8419     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8420                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8421                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8422
8423   // If we need shuffled inputs from both, blend the two.
8424   SDValue V;
8425   if (V1InUse && V2InUse)
8426     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8427   else
8428     V = V1InUse ? V1 : V2;
8429
8430   // Cast the result back to the correct type.
8431   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8432 }
8433
8434 /// \brief Generic lowering of 8-lane i16 shuffles.
8435 ///
8436 /// This handles both single-input shuffles and combined shuffle/blends with
8437 /// two inputs. The single input shuffles are immediately delegated to
8438 /// a dedicated lowering routine.
8439 ///
8440 /// The blends are lowered in one of three fundamental ways. If there are few
8441 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8442 /// of the input is significantly cheaper when lowered as an interleaving of
8443 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8444 /// halves of the inputs separately (making them have relatively few inputs)
8445 /// and then concatenate them.
8446 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8447                                        const X86Subtarget *Subtarget,
8448                                        SelectionDAG &DAG) {
8449   SDLoc DL(Op);
8450   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8451   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8452   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8453   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8454   ArrayRef<int> OrigMask = SVOp->getMask();
8455   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8456                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8457   MutableArrayRef<int> Mask(MaskStorage);
8458
8459   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8460
8461   // Whenever we can lower this as a zext, that instruction is strictly faster
8462   // than any alternative.
8463   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8464           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8465     return ZExt;
8466
8467   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8468   (void)isV1;
8469   auto isV2 = [](int M) { return M >= 8; };
8470
8471   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8472
8473   if (NumV2Inputs == 0) {
8474     // Check for being able to broadcast a single element.
8475     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8476                                                           Mask, Subtarget, DAG))
8477       return Broadcast;
8478
8479     // Try to use shift instructions.
8480     if (SDValue Shift =
8481             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8482       return Shift;
8483
8484     // Use dedicated unpack instructions for masks that match their pattern.
8485     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8486       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8487     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8488       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8489
8490     // Try to use byte rotation instructions.
8491     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8492                                                         Mask, Subtarget, DAG))
8493       return Rotate;
8494
8495     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8496                                                      Subtarget, DAG);
8497   }
8498
8499   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8500          "All single-input shuffles should be canonicalized to be V1-input "
8501          "shuffles.");
8502
8503   // Try to use shift instructions.
8504   if (SDValue Shift =
8505           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8506     return Shift;
8507
8508   // There are special ways we can lower some single-element blends.
8509   if (NumV2Inputs == 1)
8510     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8511                                                          Mask, Subtarget, DAG))
8512       return V;
8513
8514   // We have different paths for blend lowering, but they all must use the
8515   // *exact* same predicate.
8516   bool IsBlendSupported = Subtarget->hasSSE41();
8517   if (IsBlendSupported)
8518     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8519                                                   Subtarget, DAG))
8520       return Blend;
8521
8522   if (SDValue Masked =
8523           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8524     return Masked;
8525
8526   // Use dedicated unpack instructions for masks that match their pattern.
8527   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8528     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8529   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8530     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8531
8532   // Try to use byte rotation instructions.
8533   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8534           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8535     return Rotate;
8536
8537   if (SDValue BitBlend =
8538           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8539     return BitBlend;
8540
8541   if (SDValue Unpack =
8542           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8543     return Unpack;
8544
8545   // If we can't directly blend but can use PSHUFB, that will be better as it
8546   // can both shuffle and set up the inefficient blend.
8547   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8548     bool V1InUse, V2InUse;
8549     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8550                                       V1InUse, V2InUse);
8551   }
8552
8553   // We can always bit-blend if we have to so the fallback strategy is to
8554   // decompose into single-input permutes and blends.
8555   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8556                                                       Mask, DAG);
8557 }
8558
8559 /// \brief Check whether a compaction lowering can be done by dropping even
8560 /// elements and compute how many times even elements must be dropped.
8561 ///
8562 /// This handles shuffles which take every Nth element where N is a power of
8563 /// two. Example shuffle masks:
8564 ///
8565 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8566 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8567 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8568 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8569 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8570 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8571 ///
8572 /// Any of these lanes can of course be undef.
8573 ///
8574 /// This routine only supports N <= 3.
8575 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8576 /// for larger N.
8577 ///
8578 /// \returns N above, or the number of times even elements must be dropped if
8579 /// there is such a number. Otherwise returns zero.
8580 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8581   // Figure out whether we're looping over two inputs or just one.
8582   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8583
8584   // The modulus for the shuffle vector entries is based on whether this is
8585   // a single input or not.
8586   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8587   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8588          "We should only be called with masks with a power-of-2 size!");
8589
8590   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8591
8592   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8593   // and 2^3 simultaneously. This is because we may have ambiguity with
8594   // partially undef inputs.
8595   bool ViableForN[3] = {true, true, true};
8596
8597   for (int i = 0, e = Mask.size(); i < e; ++i) {
8598     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8599     // want.
8600     if (Mask[i] == -1)
8601       continue;
8602
8603     bool IsAnyViable = false;
8604     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8605       if (ViableForN[j]) {
8606         uint64_t N = j + 1;
8607
8608         // The shuffle mask must be equal to (i * 2^N) % M.
8609         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8610           IsAnyViable = true;
8611         else
8612           ViableForN[j] = false;
8613       }
8614     // Early exit if we exhaust the possible powers of two.
8615     if (!IsAnyViable)
8616       break;
8617   }
8618
8619   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8620     if (ViableForN[j])
8621       return j + 1;
8622
8623   // Return 0 as there is no viable power of two.
8624   return 0;
8625 }
8626
8627 /// \brief Generic lowering of v16i8 shuffles.
8628 ///
8629 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8630 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8631 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8632 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8633 /// back together.
8634 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8635                                        const X86Subtarget *Subtarget,
8636                                        SelectionDAG &DAG) {
8637   SDLoc DL(Op);
8638   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8639   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8640   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8641   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8642   ArrayRef<int> Mask = SVOp->getMask();
8643   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8644
8645   // Try to use shift instructions.
8646   if (SDValue Shift =
8647           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8648     return Shift;
8649
8650   // Try to use byte rotation instructions.
8651   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8652           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8653     return Rotate;
8654
8655   // Try to use a zext lowering.
8656   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8657           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8658     return ZExt;
8659
8660   int NumV2Elements =
8661       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8662
8663   // For single-input shuffles, there are some nicer lowering tricks we can use.
8664   if (NumV2Elements == 0) {
8665     // Check for being able to broadcast a single element.
8666     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8667                                                           Mask, Subtarget, DAG))
8668       return Broadcast;
8669
8670     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8671     // Notably, this handles splat and partial-splat shuffles more efficiently.
8672     // However, it only makes sense if the pre-duplication shuffle simplifies
8673     // things significantly. Currently, this means we need to be able to
8674     // express the pre-duplication shuffle as an i16 shuffle.
8675     //
8676     // FIXME: We should check for other patterns which can be widened into an
8677     // i16 shuffle as well.
8678     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8679       for (int i = 0; i < 16; i += 2)
8680         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8681           return false;
8682
8683       return true;
8684     };
8685     auto tryToWidenViaDuplication = [&]() -> SDValue {
8686       if (!canWidenViaDuplication(Mask))
8687         return SDValue();
8688       SmallVector<int, 4> LoInputs;
8689       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8690                    [](int M) { return M >= 0 && M < 8; });
8691       std::sort(LoInputs.begin(), LoInputs.end());
8692       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8693                      LoInputs.end());
8694       SmallVector<int, 4> HiInputs;
8695       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8696                    [](int M) { return M >= 8; });
8697       std::sort(HiInputs.begin(), HiInputs.end());
8698       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8699                      HiInputs.end());
8700
8701       bool TargetLo = LoInputs.size() >= HiInputs.size();
8702       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8703       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8704
8705       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8706       SmallDenseMap<int, int, 8> LaneMap;
8707       for (int I : InPlaceInputs) {
8708         PreDupI16Shuffle[I/2] = I/2;
8709         LaneMap[I] = I;
8710       }
8711       int j = TargetLo ? 0 : 4, je = j + 4;
8712       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8713         // Check if j is already a shuffle of this input. This happens when
8714         // there are two adjacent bytes after we move the low one.
8715         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8716           // If we haven't yet mapped the input, search for a slot into which
8717           // we can map it.
8718           while (j < je && PreDupI16Shuffle[j] != -1)
8719             ++j;
8720
8721           if (j == je)
8722             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8723             return SDValue();
8724
8725           // Map this input with the i16 shuffle.
8726           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8727         }
8728
8729         // Update the lane map based on the mapping we ended up with.
8730         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8731       }
8732       V1 = DAG.getNode(
8733           ISD::BITCAST, DL, MVT::v16i8,
8734           DAG.getVectorShuffle(MVT::v8i16, DL,
8735                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8736                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8737
8738       // Unpack the bytes to form the i16s that will be shuffled into place.
8739       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8740                        MVT::v16i8, V1, V1);
8741
8742       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8743       for (int i = 0; i < 16; ++i)
8744         if (Mask[i] != -1) {
8745           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8746           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8747           if (PostDupI16Shuffle[i / 2] == -1)
8748             PostDupI16Shuffle[i / 2] = MappedMask;
8749           else
8750             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8751                    "Conflicting entrties in the original shuffle!");
8752         }
8753       return DAG.getNode(
8754           ISD::BITCAST, DL, MVT::v16i8,
8755           DAG.getVectorShuffle(MVT::v8i16, DL,
8756                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8757                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8758     };
8759     if (SDValue V = tryToWidenViaDuplication())
8760       return V;
8761   }
8762
8763   // Use dedicated unpack instructions for masks that match their pattern.
8764   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8765                                          0, 16, 1, 17, 2, 18, 3, 19,
8766                                          // High half.
8767                                          4, 20, 5, 21, 6, 22, 7, 23}))
8768     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8769   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8770                                          8, 24, 9, 25, 10, 26, 11, 27,
8771                                          // High half.
8772                                          12, 28, 13, 29, 14, 30, 15, 31}))
8773     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8774
8775   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8776   // with PSHUFB. It is important to do this before we attempt to generate any
8777   // blends but after all of the single-input lowerings. If the single input
8778   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8779   // want to preserve that and we can DAG combine any longer sequences into
8780   // a PSHUFB in the end. But once we start blending from multiple inputs,
8781   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8782   // and there are *very* few patterns that would actually be faster than the
8783   // PSHUFB approach because of its ability to zero lanes.
8784   //
8785   // FIXME: The only exceptions to the above are blends which are exact
8786   // interleavings with direct instructions supporting them. We currently don't
8787   // handle those well here.
8788   if (Subtarget->hasSSSE3()) {
8789     bool V1InUse = false;
8790     bool V2InUse = false;
8791
8792     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8793                                                 DAG, V1InUse, V2InUse);
8794
8795     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8796     // do so. This avoids using them to handle blends-with-zero which is
8797     // important as a single pshufb is significantly faster for that.
8798     if (V1InUse && V2InUse) {
8799       if (Subtarget->hasSSE41())
8800         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8801                                                       Mask, Subtarget, DAG))
8802           return Blend;
8803
8804       // We can use an unpack to do the blending rather than an or in some
8805       // cases. Even though the or may be (very minorly) more efficient, we
8806       // preference this lowering because there are common cases where part of
8807       // the complexity of the shuffles goes away when we do the final blend as
8808       // an unpack.
8809       // FIXME: It might be worth trying to detect if the unpack-feeding
8810       // shuffles will both be pshufb, in which case we shouldn't bother with
8811       // this.
8812       if (SDValue Unpack =
8813               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8814         return Unpack;
8815     }
8816
8817     return PSHUFB;
8818   }
8819
8820   // There are special ways we can lower some single-element blends.
8821   if (NumV2Elements == 1)
8822     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8823                                                          Mask, Subtarget, DAG))
8824       return V;
8825
8826   if (SDValue BitBlend =
8827           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8828     return BitBlend;
8829
8830   // Check whether a compaction lowering can be done. This handles shuffles
8831   // which take every Nth element for some even N. See the helper function for
8832   // details.
8833   //
8834   // We special case these as they can be particularly efficiently handled with
8835   // the PACKUSB instruction on x86 and they show up in common patterns of
8836   // rearranging bytes to truncate wide elements.
8837   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8838     // NumEvenDrops is the power of two stride of the elements. Another way of
8839     // thinking about it is that we need to drop the even elements this many
8840     // times to get the original input.
8841     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8842
8843     // First we need to zero all the dropped bytes.
8844     assert(NumEvenDrops <= 3 &&
8845            "No support for dropping even elements more than 3 times.");
8846     // We use the mask type to pick which bytes are preserved based on how many
8847     // elements are dropped.
8848     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8849     SDValue ByteClearMask =
8850         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8851                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8852     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8853     if (!IsSingleInput)
8854       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8855
8856     // Now pack things back together.
8857     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8858     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8859     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8860     for (int i = 1; i < NumEvenDrops; ++i) {
8861       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8862       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8863     }
8864
8865     return Result;
8866   }
8867
8868   // Handle multi-input cases by blending single-input shuffles.
8869   if (NumV2Elements > 0)
8870     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8871                                                       Mask, DAG);
8872
8873   // The fallback path for single-input shuffles widens this into two v8i16
8874   // vectors with unpacks, shuffles those, and then pulls them back together
8875   // with a pack.
8876   SDValue V = V1;
8877
8878   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8879   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8880   for (int i = 0; i < 16; ++i)
8881     if (Mask[i] >= 0)
8882       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8883
8884   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8885
8886   SDValue VLoHalf, VHiHalf;
8887   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8888   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8889   // i16s.
8890   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8891                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8892       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8893                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8894     // Use a mask to drop the high bytes.
8895     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8896     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8897                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8898
8899     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8900     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8901
8902     // Squash the masks to point directly into VLoHalf.
8903     for (int &M : LoBlendMask)
8904       if (M >= 0)
8905         M /= 2;
8906     for (int &M : HiBlendMask)
8907       if (M >= 0)
8908         M /= 2;
8909   } else {
8910     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8911     // VHiHalf so that we can blend them as i16s.
8912     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8913                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8914     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8915                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8916   }
8917
8918   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8919   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8920
8921   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8922 }
8923
8924 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8925 ///
8926 /// This routine breaks down the specific type of 128-bit shuffle and
8927 /// dispatches to the lowering routines accordingly.
8928 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8929                                         MVT VT, const X86Subtarget *Subtarget,
8930                                         SelectionDAG &DAG) {
8931   switch (VT.SimpleTy) {
8932   case MVT::v2i64:
8933     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8934   case MVT::v2f64:
8935     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8936   case MVT::v4i32:
8937     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8938   case MVT::v4f32:
8939     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8940   case MVT::v8i16:
8941     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8942   case MVT::v16i8:
8943     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8944
8945   default:
8946     llvm_unreachable("Unimplemented!");
8947   }
8948 }
8949
8950 /// \brief Helper function to test whether a shuffle mask could be
8951 /// simplified by widening the elements being shuffled.
8952 ///
8953 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8954 /// leaves it in an unspecified state.
8955 ///
8956 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8957 /// shuffle masks. The latter have the special property of a '-2' representing
8958 /// a zero-ed lane of a vector.
8959 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8960                                     SmallVectorImpl<int> &WidenedMask) {
8961   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8962     // If both elements are undef, its trivial.
8963     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8964       WidenedMask.push_back(SM_SentinelUndef);
8965       continue;
8966     }
8967
8968     // Check for an undef mask and a mask value properly aligned to fit with
8969     // a pair of values. If we find such a case, use the non-undef mask's value.
8970     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8971       WidenedMask.push_back(Mask[i + 1] / 2);
8972       continue;
8973     }
8974     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8975       WidenedMask.push_back(Mask[i] / 2);
8976       continue;
8977     }
8978
8979     // When zeroing, we need to spread the zeroing across both lanes to widen.
8980     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8981       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8982           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8983         WidenedMask.push_back(SM_SentinelZero);
8984         continue;
8985       }
8986       return false;
8987     }
8988
8989     // Finally check if the two mask values are adjacent and aligned with
8990     // a pair.
8991     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8992       WidenedMask.push_back(Mask[i] / 2);
8993       continue;
8994     }
8995
8996     // Otherwise we can't safely widen the elements used in this shuffle.
8997     return false;
8998   }
8999   assert(WidenedMask.size() == Mask.size() / 2 &&
9000          "Incorrect size of mask after widening the elements!");
9001
9002   return true;
9003 }
9004
9005 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9006 ///
9007 /// This routine just extracts two subvectors, shuffles them independently, and
9008 /// then concatenates them back together. This should work effectively with all
9009 /// AVX vector shuffle types.
9010 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9011                                           SDValue V2, ArrayRef<int> Mask,
9012                                           SelectionDAG &DAG) {
9013   assert(VT.getSizeInBits() >= 256 &&
9014          "Only for 256-bit or wider vector shuffles!");
9015   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9016   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9017
9018   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9019   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9020
9021   int NumElements = VT.getVectorNumElements();
9022   int SplitNumElements = NumElements / 2;
9023   MVT ScalarVT = VT.getScalarType();
9024   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9025
9026   // Rather than splitting build-vectors, just build two narrower build
9027   // vectors. This helps shuffling with splats and zeros.
9028   auto SplitVector = [&](SDValue V) {
9029     while (V.getOpcode() == ISD::BITCAST)
9030       V = V->getOperand(0);
9031
9032     MVT OrigVT = V.getSimpleValueType();
9033     int OrigNumElements = OrigVT.getVectorNumElements();
9034     int OrigSplitNumElements = OrigNumElements / 2;
9035     MVT OrigScalarVT = OrigVT.getScalarType();
9036     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9037
9038     SDValue LoV, HiV;
9039
9040     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9041     if (!BV) {
9042       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9043                         DAG.getIntPtrConstant(0, DL));
9044       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9045                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9046     } else {
9047
9048       SmallVector<SDValue, 16> LoOps, HiOps;
9049       for (int i = 0; i < OrigSplitNumElements; ++i) {
9050         LoOps.push_back(BV->getOperand(i));
9051         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9052       }
9053       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9054       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9055     }
9056     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9057                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9058   };
9059
9060   SDValue LoV1, HiV1, LoV2, HiV2;
9061   std::tie(LoV1, HiV1) = SplitVector(V1);
9062   std::tie(LoV2, HiV2) = SplitVector(V2);
9063
9064   // Now create two 4-way blends of these half-width vectors.
9065   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9066     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9067     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9068     for (int i = 0; i < SplitNumElements; ++i) {
9069       int M = HalfMask[i];
9070       if (M >= NumElements) {
9071         if (M >= NumElements + SplitNumElements)
9072           UseHiV2 = true;
9073         else
9074           UseLoV2 = true;
9075         V2BlendMask.push_back(M - NumElements);
9076         V1BlendMask.push_back(-1);
9077         BlendMask.push_back(SplitNumElements + i);
9078       } else if (M >= 0) {
9079         if (M >= SplitNumElements)
9080           UseHiV1 = true;
9081         else
9082           UseLoV1 = true;
9083         V2BlendMask.push_back(-1);
9084         V1BlendMask.push_back(M);
9085         BlendMask.push_back(i);
9086       } else {
9087         V2BlendMask.push_back(-1);
9088         V1BlendMask.push_back(-1);
9089         BlendMask.push_back(-1);
9090       }
9091     }
9092
9093     // Because the lowering happens after all combining takes place, we need to
9094     // manually combine these blend masks as much as possible so that we create
9095     // a minimal number of high-level vector shuffle nodes.
9096
9097     // First try just blending the halves of V1 or V2.
9098     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9099       return DAG.getUNDEF(SplitVT);
9100     if (!UseLoV2 && !UseHiV2)
9101       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9102     if (!UseLoV1 && !UseHiV1)
9103       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9104
9105     SDValue V1Blend, V2Blend;
9106     if (UseLoV1 && UseHiV1) {
9107       V1Blend =
9108         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9109     } else {
9110       // We only use half of V1 so map the usage down into the final blend mask.
9111       V1Blend = UseLoV1 ? LoV1 : HiV1;
9112       for (int i = 0; i < SplitNumElements; ++i)
9113         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9114           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9115     }
9116     if (UseLoV2 && UseHiV2) {
9117       V2Blend =
9118         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9119     } else {
9120       // We only use half of V2 so map the usage down into the final blend mask.
9121       V2Blend = UseLoV2 ? LoV2 : HiV2;
9122       for (int i = 0; i < SplitNumElements; ++i)
9123         if (BlendMask[i] >= SplitNumElements)
9124           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9125     }
9126     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9127   };
9128   SDValue Lo = HalfBlend(LoMask);
9129   SDValue Hi = HalfBlend(HiMask);
9130   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9131 }
9132
9133 /// \brief Either split a vector in halves or decompose the shuffles and the
9134 /// blend.
9135 ///
9136 /// This is provided as a good fallback for many lowerings of non-single-input
9137 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9138 /// between splitting the shuffle into 128-bit components and stitching those
9139 /// back together vs. extracting the single-input shuffles and blending those
9140 /// results.
9141 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9142                                                 SDValue V2, ArrayRef<int> Mask,
9143                                                 SelectionDAG &DAG) {
9144   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9145                                             "lower single-input shuffles as it "
9146                                             "could then recurse on itself.");
9147   int Size = Mask.size();
9148
9149   // If this can be modeled as a broadcast of two elements followed by a blend,
9150   // prefer that lowering. This is especially important because broadcasts can
9151   // often fold with memory operands.
9152   auto DoBothBroadcast = [&] {
9153     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9154     for (int M : Mask)
9155       if (M >= Size) {
9156         if (V2BroadcastIdx == -1)
9157           V2BroadcastIdx = M - Size;
9158         else if (M - Size != V2BroadcastIdx)
9159           return false;
9160       } else if (M >= 0) {
9161         if (V1BroadcastIdx == -1)
9162           V1BroadcastIdx = M;
9163         else if (M != V1BroadcastIdx)
9164           return false;
9165       }
9166     return true;
9167   };
9168   if (DoBothBroadcast())
9169     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9170                                                       DAG);
9171
9172   // If the inputs all stem from a single 128-bit lane of each input, then we
9173   // split them rather than blending because the split will decompose to
9174   // unusually few instructions.
9175   int LaneCount = VT.getSizeInBits() / 128;
9176   int LaneSize = Size / LaneCount;
9177   SmallBitVector LaneInputs[2];
9178   LaneInputs[0].resize(LaneCount, false);
9179   LaneInputs[1].resize(LaneCount, false);
9180   for (int i = 0; i < Size; ++i)
9181     if (Mask[i] >= 0)
9182       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9183   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9184     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9185
9186   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9187   // that the decomposed single-input shuffles don't end up here.
9188   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9189 }
9190
9191 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9192 /// a permutation and blend of those lanes.
9193 ///
9194 /// This essentially blends the out-of-lane inputs to each lane into the lane
9195 /// from a permuted copy of the vector. This lowering strategy results in four
9196 /// instructions in the worst case for a single-input cross lane shuffle which
9197 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9198 /// of. Special cases for each particular shuffle pattern should be handled
9199 /// prior to trying this lowering.
9200 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9201                                                        SDValue V1, SDValue V2,
9202                                                        ArrayRef<int> Mask,
9203                                                        SelectionDAG &DAG) {
9204   // FIXME: This should probably be generalized for 512-bit vectors as well.
9205   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9206   int LaneSize = Mask.size() / 2;
9207
9208   // If there are only inputs from one 128-bit lane, splitting will in fact be
9209   // less expensive. The flags track whether the given lane contains an element
9210   // that crosses to another lane.
9211   bool LaneCrossing[2] = {false, false};
9212   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9213     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9214       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9215   if (!LaneCrossing[0] || !LaneCrossing[1])
9216     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9217
9218   if (isSingleInputShuffleMask(Mask)) {
9219     SmallVector<int, 32> FlippedBlendMask;
9220     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9221       FlippedBlendMask.push_back(
9222           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9223                                   ? Mask[i]
9224                                   : Mask[i] % LaneSize +
9225                                         (i / LaneSize) * LaneSize + Size));
9226
9227     // Flip the vector, and blend the results which should now be in-lane. The
9228     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9229     // 5 for the high source. The value 3 selects the high half of source 2 and
9230     // the value 2 selects the low half of source 2. We only use source 2 to
9231     // allow folding it into a memory operand.
9232     unsigned PERMMask = 3 | 2 << 4;
9233     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9234                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9235     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9236   }
9237
9238   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9239   // will be handled by the above logic and a blend of the results, much like
9240   // other patterns in AVX.
9241   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9242 }
9243
9244 /// \brief Handle lowering 2-lane 128-bit shuffles.
9245 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9246                                         SDValue V2, ArrayRef<int> Mask,
9247                                         const X86Subtarget *Subtarget,
9248                                         SelectionDAG &DAG) {
9249   // TODO: If minimizing size and one of the inputs is a zero vector and the
9250   // the zero vector has only one use, we could use a VPERM2X128 to save the
9251   // instruction bytes needed to explicitly generate the zero vector.
9252
9253   // Blends are faster and handle all the non-lane-crossing cases.
9254   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9255                                                 Subtarget, DAG))
9256     return Blend;
9257
9258   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9259   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9260
9261   // If either input operand is a zero vector, use VPERM2X128 because its mask
9262   // allows us to replace the zero input with an implicit zero.
9263   if (!IsV1Zero && !IsV2Zero) {
9264     // Check for patterns which can be matched with a single insert of a 128-bit
9265     // subvector.
9266     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9267     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9268       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9269                                    VT.getVectorNumElements() / 2);
9270       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9271                                 DAG.getIntPtrConstant(0, DL));
9272       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9273                                 OnlyUsesV1 ? V1 : V2,
9274                                 DAG.getIntPtrConstant(0, DL));
9275       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9276     }
9277   }
9278
9279   // Otherwise form a 128-bit permutation. After accounting for undefs,
9280   // convert the 64-bit shuffle mask selection values into 128-bit
9281   // selection bits by dividing the indexes by 2 and shifting into positions
9282   // defined by a vperm2*128 instruction's immediate control byte.
9283
9284   // The immediate permute control byte looks like this:
9285   //    [1:0] - select 128 bits from sources for low half of destination
9286   //    [2]   - ignore
9287   //    [3]   - zero low half of destination
9288   //    [5:4] - select 128 bits from sources for high half of destination
9289   //    [6]   - ignore
9290   //    [7]   - zero high half of destination
9291
9292   int MaskLO = Mask[0];
9293   if (MaskLO == SM_SentinelUndef)
9294     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9295
9296   int MaskHI = Mask[2];
9297   if (MaskHI == SM_SentinelUndef)
9298     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9299
9300   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9301
9302   // If either input is a zero vector, replace it with an undef input.
9303   // Shuffle mask values <  4 are selecting elements of V1.
9304   // Shuffle mask values >= 4 are selecting elements of V2.
9305   // Adjust each half of the permute mask by clearing the half that was
9306   // selecting the zero vector and setting the zero mask bit.
9307   if (IsV1Zero) {
9308     V1 = DAG.getUNDEF(VT);
9309     if (MaskLO < 4)
9310       PermMask = (PermMask & 0xf0) | 0x08;
9311     if (MaskHI < 4)
9312       PermMask = (PermMask & 0x0f) | 0x80;
9313   }
9314   if (IsV2Zero) {
9315     V2 = DAG.getUNDEF(VT);
9316     if (MaskLO >= 4)
9317       PermMask = (PermMask & 0xf0) | 0x08;
9318     if (MaskHI >= 4)
9319       PermMask = (PermMask & 0x0f) | 0x80;
9320   }
9321
9322   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9323                      DAG.getConstant(PermMask, DL, MVT::i8));
9324 }
9325
9326 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9327 /// shuffling each lane.
9328 ///
9329 /// This will only succeed when the result of fixing the 128-bit lanes results
9330 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9331 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9332 /// the lane crosses early and then use simpler shuffles within each lane.
9333 ///
9334 /// FIXME: It might be worthwhile at some point to support this without
9335 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9336 /// in x86 only floating point has interesting non-repeating shuffles, and even
9337 /// those are still *marginally* more expensive.
9338 static SDValue lowerVectorShuffleByMerging128BitLanes(
9339     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9340     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9341   assert(!isSingleInputShuffleMask(Mask) &&
9342          "This is only useful with multiple inputs.");
9343
9344   int Size = Mask.size();
9345   int LaneSize = 128 / VT.getScalarSizeInBits();
9346   int NumLanes = Size / LaneSize;
9347   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9348
9349   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9350   // check whether the in-128-bit lane shuffles share a repeating pattern.
9351   SmallVector<int, 4> Lanes;
9352   Lanes.resize(NumLanes, -1);
9353   SmallVector<int, 4> InLaneMask;
9354   InLaneMask.resize(LaneSize, -1);
9355   for (int i = 0; i < Size; ++i) {
9356     if (Mask[i] < 0)
9357       continue;
9358
9359     int j = i / LaneSize;
9360
9361     if (Lanes[j] < 0) {
9362       // First entry we've seen for this lane.
9363       Lanes[j] = Mask[i] / LaneSize;
9364     } else if (Lanes[j] != Mask[i] / LaneSize) {
9365       // This doesn't match the lane selected previously!
9366       return SDValue();
9367     }
9368
9369     // Check that within each lane we have a consistent shuffle mask.
9370     int k = i % LaneSize;
9371     if (InLaneMask[k] < 0) {
9372       InLaneMask[k] = Mask[i] % LaneSize;
9373     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9374       // This doesn't fit a repeating in-lane mask.
9375       return SDValue();
9376     }
9377   }
9378
9379   // First shuffle the lanes into place.
9380   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9381                                 VT.getSizeInBits() / 64);
9382   SmallVector<int, 8> LaneMask;
9383   LaneMask.resize(NumLanes * 2, -1);
9384   for (int i = 0; i < NumLanes; ++i)
9385     if (Lanes[i] >= 0) {
9386       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9387       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9388     }
9389
9390   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9391   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9392   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9393
9394   // Cast it back to the type we actually want.
9395   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9396
9397   // Now do a simple shuffle that isn't lane crossing.
9398   SmallVector<int, 8> NewMask;
9399   NewMask.resize(Size, -1);
9400   for (int i = 0; i < Size; ++i)
9401     if (Mask[i] >= 0)
9402       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9403   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9404          "Must not introduce lane crosses at this point!");
9405
9406   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9407 }
9408
9409 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9410 /// given mask.
9411 ///
9412 /// This returns true if the elements from a particular input are already in the
9413 /// slot required by the given mask and require no permutation.
9414 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9415   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9416   int Size = Mask.size();
9417   for (int i = 0; i < Size; ++i)
9418     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9419       return false;
9420
9421   return true;
9422 }
9423
9424 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9425 ///
9426 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9427 /// isn't available.
9428 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9429                                        const X86Subtarget *Subtarget,
9430                                        SelectionDAG &DAG) {
9431   SDLoc DL(Op);
9432   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9433   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9434   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9435   ArrayRef<int> Mask = SVOp->getMask();
9436   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9437
9438   SmallVector<int, 4> WidenedMask;
9439   if (canWidenShuffleElements(Mask, WidenedMask))
9440     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9441                                     DAG);
9442
9443   if (isSingleInputShuffleMask(Mask)) {
9444     // Check for being able to broadcast a single element.
9445     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9446                                                           Mask, Subtarget, DAG))
9447       return Broadcast;
9448
9449     // Use low duplicate instructions for masks that match their pattern.
9450     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9451       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9452
9453     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9454       // Non-half-crossing single input shuffles can be lowerid with an
9455       // interleaved permutation.
9456       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9457                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9458       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9459                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9460     }
9461
9462     // With AVX2 we have direct support for this permutation.
9463     if (Subtarget->hasAVX2())
9464       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9465                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9466
9467     // Otherwise, fall back.
9468     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9469                                                    DAG);
9470   }
9471
9472   // X86 has dedicated unpack instructions that can handle specific blend
9473   // operations: UNPCKH and UNPCKL.
9474   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9475     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9476   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9477     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9478   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9479     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9480   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9481     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9482
9483   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9484                                                 Subtarget, DAG))
9485     return Blend;
9486
9487   // Check if the blend happens to exactly fit that of SHUFPD.
9488   if ((Mask[0] == -1 || Mask[0] < 2) &&
9489       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9490       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9491       (Mask[3] == -1 || Mask[3] >= 6)) {
9492     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9493                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9494     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9495                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9496   }
9497   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9498       (Mask[1] == -1 || Mask[1] < 2) &&
9499       (Mask[2] == -1 || Mask[2] >= 6) &&
9500       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9501     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9502                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9503     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9504                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9505   }
9506
9507   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9508   // shuffle. However, if we have AVX2 and either inputs are already in place,
9509   // we will be able to shuffle even across lanes the other input in a single
9510   // instruction so skip this pattern.
9511   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9512                                  isShuffleMaskInputInPlace(1, Mask))))
9513     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9514             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9515       return Result;
9516
9517   // If we have AVX2 then we always want to lower with a blend because an v4 we
9518   // can fully permute the elements.
9519   if (Subtarget->hasAVX2())
9520     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9521                                                       Mask, DAG);
9522
9523   // Otherwise fall back on generic lowering.
9524   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9525 }
9526
9527 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9528 ///
9529 /// This routine is only called when we have AVX2 and thus a reasonable
9530 /// instruction set for v4i64 shuffling..
9531 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9532                                        const X86Subtarget *Subtarget,
9533                                        SelectionDAG &DAG) {
9534   SDLoc DL(Op);
9535   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9536   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9537   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9538   ArrayRef<int> Mask = SVOp->getMask();
9539   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9540   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9541
9542   SmallVector<int, 4> WidenedMask;
9543   if (canWidenShuffleElements(Mask, WidenedMask))
9544     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9545                                     DAG);
9546
9547   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9548                                                 Subtarget, DAG))
9549     return Blend;
9550
9551   // Check for being able to broadcast a single element.
9552   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9553                                                         Mask, Subtarget, DAG))
9554     return Broadcast;
9555
9556   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9557   // use lower latency instructions that will operate on both 128-bit lanes.
9558   SmallVector<int, 2> RepeatedMask;
9559   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9560     if (isSingleInputShuffleMask(Mask)) {
9561       int PSHUFDMask[] = {-1, -1, -1, -1};
9562       for (int i = 0; i < 2; ++i)
9563         if (RepeatedMask[i] >= 0) {
9564           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9565           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9566         }
9567       return DAG.getNode(
9568           ISD::BITCAST, DL, MVT::v4i64,
9569           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9570                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9571                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9572     }
9573   }
9574
9575   // AVX2 provides a direct instruction for permuting a single input across
9576   // lanes.
9577   if (isSingleInputShuffleMask(Mask))
9578     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9579                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9580
9581   // Try to use shift instructions.
9582   if (SDValue Shift =
9583           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9584     return Shift;
9585
9586   // Use dedicated unpack instructions for masks that match their pattern.
9587   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9588     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9589   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9590     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9591   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9592     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9593   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9594     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9595
9596   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9597   // shuffle. However, if we have AVX2 and either inputs are already in place,
9598   // we will be able to shuffle even across lanes the other input in a single
9599   // instruction so skip this pattern.
9600   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9601                                  isShuffleMaskInputInPlace(1, Mask))))
9602     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9603             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9604       return Result;
9605
9606   // Otherwise fall back on generic blend lowering.
9607   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9608                                                     Mask, DAG);
9609 }
9610
9611 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9612 ///
9613 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9614 /// isn't available.
9615 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9616                                        const X86Subtarget *Subtarget,
9617                                        SelectionDAG &DAG) {
9618   SDLoc DL(Op);
9619   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9620   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9621   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9622   ArrayRef<int> Mask = SVOp->getMask();
9623   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9624
9625   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9626                                                 Subtarget, DAG))
9627     return Blend;
9628
9629   // Check for being able to broadcast a single element.
9630   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9631                                                         Mask, Subtarget, DAG))
9632     return Broadcast;
9633
9634   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9635   // options to efficiently lower the shuffle.
9636   SmallVector<int, 4> RepeatedMask;
9637   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9638     assert(RepeatedMask.size() == 4 &&
9639            "Repeated masks must be half the mask width!");
9640
9641     // Use even/odd duplicate instructions for masks that match their pattern.
9642     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9643       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9644     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9645       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9646
9647     if (isSingleInputShuffleMask(Mask))
9648       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9649                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9650
9651     // Use dedicated unpack instructions for masks that match their pattern.
9652     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9653       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9654     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9655       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9656     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9657       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9658     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9659       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9660
9661     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9662     // have already handled any direct blends. We also need to squash the
9663     // repeated mask into a simulated v4f32 mask.
9664     for (int i = 0; i < 4; ++i)
9665       if (RepeatedMask[i] >= 8)
9666         RepeatedMask[i] -= 4;
9667     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9668   }
9669
9670   // If we have a single input shuffle with different shuffle patterns in the
9671   // two 128-bit lanes use the variable mask to VPERMILPS.
9672   if (isSingleInputShuffleMask(Mask)) {
9673     SDValue VPermMask[8];
9674     for (int i = 0; i < 8; ++i)
9675       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9676                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9677     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9678       return DAG.getNode(
9679           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9680           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9681
9682     if (Subtarget->hasAVX2())
9683       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9684                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9685                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9686                                                  MVT::v8i32, VPermMask)),
9687                          V1);
9688
9689     // Otherwise, fall back.
9690     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9691                                                    DAG);
9692   }
9693
9694   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9695   // shuffle.
9696   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9697           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9698     return Result;
9699
9700   // If we have AVX2 then we always want to lower with a blend because at v8 we
9701   // can fully permute the elements.
9702   if (Subtarget->hasAVX2())
9703     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9704                                                       Mask, DAG);
9705
9706   // Otherwise fall back on generic lowering.
9707   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9708 }
9709
9710 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9711 ///
9712 /// This routine is only called when we have AVX2 and thus a reasonable
9713 /// instruction set for v8i32 shuffling..
9714 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9715                                        const X86Subtarget *Subtarget,
9716                                        SelectionDAG &DAG) {
9717   SDLoc DL(Op);
9718   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9719   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9720   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9721   ArrayRef<int> Mask = SVOp->getMask();
9722   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9723   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9724
9725   // Whenever we can lower this as a zext, that instruction is strictly faster
9726   // than any alternative. It also allows us to fold memory operands into the
9727   // shuffle in many cases.
9728   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9729                                                          Mask, Subtarget, DAG))
9730     return ZExt;
9731
9732   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9733                                                 Subtarget, DAG))
9734     return Blend;
9735
9736   // Check for being able to broadcast a single element.
9737   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9738                                                         Mask, Subtarget, DAG))
9739     return Broadcast;
9740
9741   // If the shuffle mask is repeated in each 128-bit lane we can use more
9742   // efficient instructions that mirror the shuffles across the two 128-bit
9743   // lanes.
9744   SmallVector<int, 4> RepeatedMask;
9745   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9746     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9747     if (isSingleInputShuffleMask(Mask))
9748       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9749                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9750
9751     // Use dedicated unpack instructions for masks that match their pattern.
9752     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9753       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9754     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9755       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9756     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9757       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9758     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9759       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9760   }
9761
9762   // Try to use shift instructions.
9763   if (SDValue Shift =
9764           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9765     return Shift;
9766
9767   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9768           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9769     return Rotate;
9770
9771   // If the shuffle patterns aren't repeated but it is a single input, directly
9772   // generate a cross-lane VPERMD instruction.
9773   if (isSingleInputShuffleMask(Mask)) {
9774     SDValue VPermMask[8];
9775     for (int i = 0; i < 8; ++i)
9776       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9777                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9778     return DAG.getNode(
9779         X86ISD::VPERMV, DL, MVT::v8i32,
9780         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9781   }
9782
9783   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9784   // shuffle.
9785   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9786           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9787     return Result;
9788
9789   // Otherwise fall back on generic blend lowering.
9790   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9791                                                     Mask, DAG);
9792 }
9793
9794 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9795 ///
9796 /// This routine is only called when we have AVX2 and thus a reasonable
9797 /// instruction set for v16i16 shuffling..
9798 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9799                                         const X86Subtarget *Subtarget,
9800                                         SelectionDAG &DAG) {
9801   SDLoc DL(Op);
9802   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9803   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9804   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9805   ArrayRef<int> Mask = SVOp->getMask();
9806   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9807   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9808
9809   // Whenever we can lower this as a zext, that instruction is strictly faster
9810   // than any alternative. It also allows us to fold memory operands into the
9811   // shuffle in many cases.
9812   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9813                                                          Mask, Subtarget, DAG))
9814     return ZExt;
9815
9816   // Check for being able to broadcast a single element.
9817   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9818                                                         Mask, Subtarget, DAG))
9819     return Broadcast;
9820
9821   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9822                                                 Subtarget, DAG))
9823     return Blend;
9824
9825   // Use dedicated unpack instructions for masks that match their pattern.
9826   if (isShuffleEquivalent(V1, V2, Mask,
9827                           {// First 128-bit lane:
9828                            0, 16, 1, 17, 2, 18, 3, 19,
9829                            // Second 128-bit lane:
9830                            8, 24, 9, 25, 10, 26, 11, 27}))
9831     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9832   if (isShuffleEquivalent(V1, V2, Mask,
9833                           {// First 128-bit lane:
9834                            4, 20, 5, 21, 6, 22, 7, 23,
9835                            // Second 128-bit lane:
9836                            12, 28, 13, 29, 14, 30, 15, 31}))
9837     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9838
9839   // Try to use shift instructions.
9840   if (SDValue Shift =
9841           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9842     return Shift;
9843
9844   // Try to use byte rotation instructions.
9845   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9846           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9847     return Rotate;
9848
9849   if (isSingleInputShuffleMask(Mask)) {
9850     // There are no generalized cross-lane shuffle operations available on i16
9851     // element types.
9852     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9853       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9854                                                      Mask, DAG);
9855
9856     SmallVector<int, 8> RepeatedMask;
9857     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9858       // As this is a single-input shuffle, the repeated mask should be
9859       // a strictly valid v8i16 mask that we can pass through to the v8i16
9860       // lowering to handle even the v16 case.
9861       return lowerV8I16GeneralSingleInputVectorShuffle(
9862           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9863     }
9864
9865     SDValue PSHUFBMask[32];
9866     for (int i = 0; i < 16; ++i) {
9867       if (Mask[i] == -1) {
9868         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9869         continue;
9870       }
9871
9872       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9873       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9874       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9875       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9876     }
9877     return DAG.getNode(
9878         ISD::BITCAST, DL, MVT::v16i16,
9879         DAG.getNode(
9880             X86ISD::PSHUFB, DL, MVT::v32i8,
9881             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9882             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9883   }
9884
9885   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9886   // shuffle.
9887   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9888           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9889     return Result;
9890
9891   // Otherwise fall back on generic lowering.
9892   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9893 }
9894
9895 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9896 ///
9897 /// This routine is only called when we have AVX2 and thus a reasonable
9898 /// instruction set for v32i8 shuffling..
9899 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9900                                        const X86Subtarget *Subtarget,
9901                                        SelectionDAG &DAG) {
9902   SDLoc DL(Op);
9903   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9904   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9905   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9906   ArrayRef<int> Mask = SVOp->getMask();
9907   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9908   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9909
9910   // Whenever we can lower this as a zext, that instruction is strictly faster
9911   // than any alternative. It also allows us to fold memory operands into the
9912   // shuffle in many cases.
9913   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9914                                                          Mask, Subtarget, DAG))
9915     return ZExt;
9916
9917   // Check for being able to broadcast a single element.
9918   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9919                                                         Mask, Subtarget, DAG))
9920     return Broadcast;
9921
9922   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9923                                                 Subtarget, DAG))
9924     return Blend;
9925
9926   // Use dedicated unpack instructions for masks that match their pattern.
9927   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9928   // 256-bit lanes.
9929   if (isShuffleEquivalent(
9930           V1, V2, Mask,
9931           {// First 128-bit lane:
9932            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9933            // Second 128-bit lane:
9934            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9935     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9936   if (isShuffleEquivalent(
9937           V1, V2, Mask,
9938           {// First 128-bit lane:
9939            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9940            // Second 128-bit lane:
9941            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9942     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9943
9944   // Try to use shift instructions.
9945   if (SDValue Shift =
9946           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9947     return Shift;
9948
9949   // Try to use byte rotation instructions.
9950   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9951           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9952     return Rotate;
9953
9954   if (isSingleInputShuffleMask(Mask)) {
9955     // There are no generalized cross-lane shuffle operations available on i8
9956     // element types.
9957     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9958       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9959                                                      Mask, DAG);
9960
9961     SDValue PSHUFBMask[32];
9962     for (int i = 0; i < 32; ++i)
9963       PSHUFBMask[i] =
9964           Mask[i] < 0
9965               ? DAG.getUNDEF(MVT::i8)
9966               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9967                                 MVT::i8);
9968
9969     return DAG.getNode(
9970         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9971         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9972   }
9973
9974   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9975   // shuffle.
9976   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9977           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9978     return Result;
9979
9980   // Otherwise fall back on generic lowering.
9981   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9982 }
9983
9984 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9985 ///
9986 /// This routine either breaks down the specific type of a 256-bit x86 vector
9987 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9988 /// together based on the available instructions.
9989 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9990                                         MVT VT, const X86Subtarget *Subtarget,
9991                                         SelectionDAG &DAG) {
9992   SDLoc DL(Op);
9993   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9994   ArrayRef<int> Mask = SVOp->getMask();
9995
9996   // If we have a single input to the zero element, insert that into V1 if we
9997   // can do so cheaply.
9998   int NumElts = VT.getVectorNumElements();
9999   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10000     return M >= NumElts;
10001   });
10002
10003   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10004     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10005                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10006       return Insertion;
10007
10008   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10009   // check for those subtargets here and avoid much of the subtarget querying in
10010   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10011   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10012   // floating point types there eventually, just immediately cast everything to
10013   // a float and operate entirely in that domain.
10014   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10015     int ElementBits = VT.getScalarSizeInBits();
10016     if (ElementBits < 32)
10017       // No floating point type available, decompose into 128-bit vectors.
10018       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10019
10020     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10021                                 VT.getVectorNumElements());
10022     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10023     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10024     return DAG.getNode(ISD::BITCAST, DL, VT,
10025                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10026   }
10027
10028   switch (VT.SimpleTy) {
10029   case MVT::v4f64:
10030     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10031   case MVT::v4i64:
10032     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10033   case MVT::v8f32:
10034     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10035   case MVT::v8i32:
10036     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10037   case MVT::v16i16:
10038     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10039   case MVT::v32i8:
10040     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10041
10042   default:
10043     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10044   }
10045 }
10046
10047 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10048 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10049                                        const X86Subtarget *Subtarget,
10050                                        SelectionDAG &DAG) {
10051   SDLoc DL(Op);
10052   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10053   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10054   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10055   ArrayRef<int> Mask = SVOp->getMask();
10056   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10057
10058   // X86 has dedicated unpack instructions that can handle specific blend
10059   // operations: UNPCKH and UNPCKL.
10060   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10061     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10062   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10063     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10064
10065   // FIXME: Implement direct support for this type!
10066   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10067 }
10068
10069 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10070 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10071                                        const X86Subtarget *Subtarget,
10072                                        SelectionDAG &DAG) {
10073   SDLoc DL(Op);
10074   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10075   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10076   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10077   ArrayRef<int> Mask = SVOp->getMask();
10078   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10079
10080   // Use dedicated unpack instructions for masks that match their pattern.
10081   if (isShuffleEquivalent(V1, V2, Mask,
10082                           {// First 128-bit lane.
10083                            0, 16, 1, 17, 4, 20, 5, 21,
10084                            // Second 128-bit lane.
10085                            8, 24, 9, 25, 12, 28, 13, 29}))
10086     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10087   if (isShuffleEquivalent(V1, V2, Mask,
10088                           {// First 128-bit lane.
10089                            2, 18, 3, 19, 6, 22, 7, 23,
10090                            // Second 128-bit lane.
10091                            10, 26, 11, 27, 14, 30, 15, 31}))
10092     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10093
10094   // FIXME: Implement direct support for this type!
10095   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10096 }
10097
10098 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10099 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10100                                        const X86Subtarget *Subtarget,
10101                                        SelectionDAG &DAG) {
10102   SDLoc DL(Op);
10103   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10104   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10105   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10106   ArrayRef<int> Mask = SVOp->getMask();
10107   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10108
10109   // X86 has dedicated unpack instructions that can handle specific blend
10110   // operations: UNPCKH and UNPCKL.
10111   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10112     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10113   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10114     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10115
10116   // FIXME: Implement direct support for this type!
10117   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10118 }
10119
10120 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10121 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10122                                        const X86Subtarget *Subtarget,
10123                                        SelectionDAG &DAG) {
10124   SDLoc DL(Op);
10125   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10126   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10127   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10128   ArrayRef<int> Mask = SVOp->getMask();
10129   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10130
10131   // Use dedicated unpack instructions for masks that match their pattern.
10132   if (isShuffleEquivalent(V1, V2, Mask,
10133                           {// First 128-bit lane.
10134                            0, 16, 1, 17, 4, 20, 5, 21,
10135                            // Second 128-bit lane.
10136                            8, 24, 9, 25, 12, 28, 13, 29}))
10137     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10138   if (isShuffleEquivalent(V1, V2, Mask,
10139                           {// First 128-bit lane.
10140                            2, 18, 3, 19, 6, 22, 7, 23,
10141                            // Second 128-bit lane.
10142                            10, 26, 11, 27, 14, 30, 15, 31}))
10143     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10144
10145   // FIXME: Implement direct support for this type!
10146   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10147 }
10148
10149 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10150 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10151                                         const X86Subtarget *Subtarget,
10152                                         SelectionDAG &DAG) {
10153   SDLoc DL(Op);
10154   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10155   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10156   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10157   ArrayRef<int> Mask = SVOp->getMask();
10158   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10159   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10160
10161   // FIXME: Implement direct support for this type!
10162   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10163 }
10164
10165 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10166 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10167                                        const X86Subtarget *Subtarget,
10168                                        SelectionDAG &DAG) {
10169   SDLoc DL(Op);
10170   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10171   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10172   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10173   ArrayRef<int> Mask = SVOp->getMask();
10174   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10175   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10176
10177   // FIXME: Implement direct support for this type!
10178   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10179 }
10180
10181 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10182 ///
10183 /// This routine either breaks down the specific type of a 512-bit x86 vector
10184 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10185 /// together based on the available instructions.
10186 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10187                                         MVT VT, const X86Subtarget *Subtarget,
10188                                         SelectionDAG &DAG) {
10189   SDLoc DL(Op);
10190   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10191   ArrayRef<int> Mask = SVOp->getMask();
10192   assert(Subtarget->hasAVX512() &&
10193          "Cannot lower 512-bit vectors w/ basic ISA!");
10194
10195   // Check for being able to broadcast a single element.
10196   if (SDValue Broadcast =
10197           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10198     return Broadcast;
10199
10200   // Dispatch to each element type for lowering. If we don't have supprot for
10201   // specific element type shuffles at 512 bits, immediately split them and
10202   // lower them. Each lowering routine of a given type is allowed to assume that
10203   // the requisite ISA extensions for that element type are available.
10204   switch (VT.SimpleTy) {
10205   case MVT::v8f64:
10206     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10207   case MVT::v16f32:
10208     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10209   case MVT::v8i64:
10210     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10211   case MVT::v16i32:
10212     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10213   case MVT::v32i16:
10214     if (Subtarget->hasBWI())
10215       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10216     break;
10217   case MVT::v64i8:
10218     if (Subtarget->hasBWI())
10219       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10220     break;
10221
10222   default:
10223     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10224   }
10225
10226   // Otherwise fall back on splitting.
10227   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10228 }
10229
10230 /// \brief Top-level lowering for x86 vector shuffles.
10231 ///
10232 /// This handles decomposition, canonicalization, and lowering of all x86
10233 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10234 /// above in helper routines. The canonicalization attempts to widen shuffles
10235 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10236 /// s.t. only one of the two inputs needs to be tested, etc.
10237 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10238                                   SelectionDAG &DAG) {
10239   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10240   ArrayRef<int> Mask = SVOp->getMask();
10241   SDValue V1 = Op.getOperand(0);
10242   SDValue V2 = Op.getOperand(1);
10243   MVT VT = Op.getSimpleValueType();
10244   int NumElements = VT.getVectorNumElements();
10245   SDLoc dl(Op);
10246
10247   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10248
10249   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10250   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10251   if (V1IsUndef && V2IsUndef)
10252     return DAG.getUNDEF(VT);
10253
10254   // When we create a shuffle node we put the UNDEF node to second operand,
10255   // but in some cases the first operand may be transformed to UNDEF.
10256   // In this case we should just commute the node.
10257   if (V1IsUndef)
10258     return DAG.getCommutedVectorShuffle(*SVOp);
10259
10260   // Check for non-undef masks pointing at an undef vector and make the masks
10261   // undef as well. This makes it easier to match the shuffle based solely on
10262   // the mask.
10263   if (V2IsUndef)
10264     for (int M : Mask)
10265       if (M >= NumElements) {
10266         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10267         for (int &M : NewMask)
10268           if (M >= NumElements)
10269             M = -1;
10270         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10271       }
10272
10273   // We actually see shuffles that are entirely re-arrangements of a set of
10274   // zero inputs. This mostly happens while decomposing complex shuffles into
10275   // simple ones. Directly lower these as a buildvector of zeros.
10276   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10277   if (Zeroable.all())
10278     return getZeroVector(VT, Subtarget, DAG, dl);
10279
10280   // Try to collapse shuffles into using a vector type with fewer elements but
10281   // wider element types. We cap this to not form integers or floating point
10282   // elements wider than 64 bits, but it might be interesting to form i128
10283   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10284   SmallVector<int, 16> WidenedMask;
10285   if (VT.getScalarSizeInBits() < 64 &&
10286       canWidenShuffleElements(Mask, WidenedMask)) {
10287     MVT NewEltVT = VT.isFloatingPoint()
10288                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10289                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10290     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10291     // Make sure that the new vector type is legal. For example, v2f64 isn't
10292     // legal on SSE1.
10293     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10294       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10295       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10296       return DAG.getNode(ISD::BITCAST, dl, VT,
10297                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10298     }
10299   }
10300
10301   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10302   for (int M : SVOp->getMask())
10303     if (M < 0)
10304       ++NumUndefElements;
10305     else if (M < NumElements)
10306       ++NumV1Elements;
10307     else
10308       ++NumV2Elements;
10309
10310   // Commute the shuffle as needed such that more elements come from V1 than
10311   // V2. This allows us to match the shuffle pattern strictly on how many
10312   // elements come from V1 without handling the symmetric cases.
10313   if (NumV2Elements > NumV1Elements)
10314     return DAG.getCommutedVectorShuffle(*SVOp);
10315
10316   // When the number of V1 and V2 elements are the same, try to minimize the
10317   // number of uses of V2 in the low half of the vector. When that is tied,
10318   // ensure that the sum of indices for V1 is equal to or lower than the sum
10319   // indices for V2. When those are equal, try to ensure that the number of odd
10320   // indices for V1 is lower than the number of odd indices for V2.
10321   if (NumV1Elements == NumV2Elements) {
10322     int LowV1Elements = 0, LowV2Elements = 0;
10323     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10324       if (M >= NumElements)
10325         ++LowV2Elements;
10326       else if (M >= 0)
10327         ++LowV1Elements;
10328     if (LowV2Elements > LowV1Elements) {
10329       return DAG.getCommutedVectorShuffle(*SVOp);
10330     } else if (LowV2Elements == LowV1Elements) {
10331       int SumV1Indices = 0, SumV2Indices = 0;
10332       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10333         if (SVOp->getMask()[i] >= NumElements)
10334           SumV2Indices += i;
10335         else if (SVOp->getMask()[i] >= 0)
10336           SumV1Indices += i;
10337       if (SumV2Indices < SumV1Indices) {
10338         return DAG.getCommutedVectorShuffle(*SVOp);
10339       } else if (SumV2Indices == SumV1Indices) {
10340         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10341         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10342           if (SVOp->getMask()[i] >= NumElements)
10343             NumV2OddIndices += i % 2;
10344           else if (SVOp->getMask()[i] >= 0)
10345             NumV1OddIndices += i % 2;
10346         if (NumV2OddIndices < NumV1OddIndices)
10347           return DAG.getCommutedVectorShuffle(*SVOp);
10348       }
10349     }
10350   }
10351
10352   // For each vector width, delegate to a specialized lowering routine.
10353   if (VT.getSizeInBits() == 128)
10354     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10355
10356   if (VT.getSizeInBits() == 256)
10357     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10358
10359   // Force AVX-512 vectors to be scalarized for now.
10360   // FIXME: Implement AVX-512 support!
10361   if (VT.getSizeInBits() == 512)
10362     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10363
10364   llvm_unreachable("Unimplemented!");
10365 }
10366
10367 // This function assumes its argument is a BUILD_VECTOR of constants or
10368 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10369 // true.
10370 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10371                                     unsigned &MaskValue) {
10372   MaskValue = 0;
10373   unsigned NumElems = BuildVector->getNumOperands();
10374   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10375   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10376   unsigned NumElemsInLane = NumElems / NumLanes;
10377
10378   // Blend for v16i16 should be symetric for the both lanes.
10379   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10380     SDValue EltCond = BuildVector->getOperand(i);
10381     SDValue SndLaneEltCond =
10382         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10383
10384     int Lane1Cond = -1, Lane2Cond = -1;
10385     if (isa<ConstantSDNode>(EltCond))
10386       Lane1Cond = !isZero(EltCond);
10387     if (isa<ConstantSDNode>(SndLaneEltCond))
10388       Lane2Cond = !isZero(SndLaneEltCond);
10389
10390     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10391       // Lane1Cond != 0, means we want the first argument.
10392       // Lane1Cond == 0, means we want the second argument.
10393       // The encoding of this argument is 0 for the first argument, 1
10394       // for the second. Therefore, invert the condition.
10395       MaskValue |= !Lane1Cond << i;
10396     else if (Lane1Cond < 0)
10397       MaskValue |= !Lane2Cond << i;
10398     else
10399       return false;
10400   }
10401   return true;
10402 }
10403
10404 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10405 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10406                                            const X86Subtarget *Subtarget,
10407                                            SelectionDAG &DAG) {
10408   SDValue Cond = Op.getOperand(0);
10409   SDValue LHS = Op.getOperand(1);
10410   SDValue RHS = Op.getOperand(2);
10411   SDLoc dl(Op);
10412   MVT VT = Op.getSimpleValueType();
10413
10414   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10415     return SDValue();
10416   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10417
10418   // Only non-legal VSELECTs reach this lowering, convert those into generic
10419   // shuffles and re-use the shuffle lowering path for blends.
10420   SmallVector<int, 32> Mask;
10421   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10422     SDValue CondElt = CondBV->getOperand(i);
10423     Mask.push_back(
10424         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10425   }
10426   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10427 }
10428
10429 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10430   // A vselect where all conditions and data are constants can be optimized into
10431   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10432   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10433       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10434       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10435     return SDValue();
10436
10437   // Try to lower this to a blend-style vector shuffle. This can handle all
10438   // constant condition cases.
10439   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10440     return BlendOp;
10441
10442   // Variable blends are only legal from SSE4.1 onward.
10443   if (!Subtarget->hasSSE41())
10444     return SDValue();
10445
10446   // Only some types will be legal on some subtargets. If we can emit a legal
10447   // VSELECT-matching blend, return Op, and but if we need to expand, return
10448   // a null value.
10449   switch (Op.getSimpleValueType().SimpleTy) {
10450   default:
10451     // Most of the vector types have blends past SSE4.1.
10452     return Op;
10453
10454   case MVT::v32i8:
10455     // The byte blends for AVX vectors were introduced only in AVX2.
10456     if (Subtarget->hasAVX2())
10457       return Op;
10458
10459     return SDValue();
10460
10461   case MVT::v8i16:
10462   case MVT::v16i16:
10463     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10464     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10465       return Op;
10466
10467     // FIXME: We should custom lower this by fixing the condition and using i8
10468     // blends.
10469     return SDValue();
10470   }
10471 }
10472
10473 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10474   MVT VT = Op.getSimpleValueType();
10475   SDLoc dl(Op);
10476
10477   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10478     return SDValue();
10479
10480   if (VT.getSizeInBits() == 8) {
10481     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10482                                   Op.getOperand(0), Op.getOperand(1));
10483     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10484                                   DAG.getValueType(VT));
10485     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10486   }
10487
10488   if (VT.getSizeInBits() == 16) {
10489     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10490     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10491     if (Idx == 0)
10492       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10493                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10494                                      DAG.getNode(ISD::BITCAST, dl,
10495                                                  MVT::v4i32,
10496                                                  Op.getOperand(0)),
10497                                      Op.getOperand(1)));
10498     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10499                                   Op.getOperand(0), Op.getOperand(1));
10500     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10501                                   DAG.getValueType(VT));
10502     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10503   }
10504
10505   if (VT == MVT::f32) {
10506     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10507     // the result back to FR32 register. It's only worth matching if the
10508     // result has a single use which is a store or a bitcast to i32.  And in
10509     // the case of a store, it's not worth it if the index is a constant 0,
10510     // because a MOVSSmr can be used instead, which is smaller and faster.
10511     if (!Op.hasOneUse())
10512       return SDValue();
10513     SDNode *User = *Op.getNode()->use_begin();
10514     if ((User->getOpcode() != ISD::STORE ||
10515          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10516           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10517         (User->getOpcode() != ISD::BITCAST ||
10518          User->getValueType(0) != MVT::i32))
10519       return SDValue();
10520     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10521                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10522                                               Op.getOperand(0)),
10523                                               Op.getOperand(1));
10524     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10525   }
10526
10527   if (VT == MVT::i32 || VT == MVT::i64) {
10528     // ExtractPS/pextrq works with constant index.
10529     if (isa<ConstantSDNode>(Op.getOperand(1)))
10530       return Op;
10531   }
10532   return SDValue();
10533 }
10534
10535 /// Extract one bit from mask vector, like v16i1 or v8i1.
10536 /// AVX-512 feature.
10537 SDValue
10538 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10539   SDValue Vec = Op.getOperand(0);
10540   SDLoc dl(Vec);
10541   MVT VecVT = Vec.getSimpleValueType();
10542   SDValue Idx = Op.getOperand(1);
10543   MVT EltVT = Op.getSimpleValueType();
10544
10545   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10546   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10547          "Unexpected vector type in ExtractBitFromMaskVector");
10548
10549   // variable index can't be handled in mask registers,
10550   // extend vector to VR512
10551   if (!isa<ConstantSDNode>(Idx)) {
10552     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10553     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10554     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10555                               ExtVT.getVectorElementType(), Ext, Idx);
10556     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10557   }
10558
10559   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10560   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10561   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10562     rc = getRegClassFor(MVT::v16i1);
10563   unsigned MaxSift = rc->getSize()*8 - 1;
10564   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10565                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10566   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10567                     DAG.getConstant(MaxSift, dl, MVT::i8));
10568   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10569                        DAG.getIntPtrConstant(0, dl));
10570 }
10571
10572 SDValue
10573 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10574                                            SelectionDAG &DAG) const {
10575   SDLoc dl(Op);
10576   SDValue Vec = Op.getOperand(0);
10577   MVT VecVT = Vec.getSimpleValueType();
10578   SDValue Idx = Op.getOperand(1);
10579
10580   if (Op.getSimpleValueType() == MVT::i1)
10581     return ExtractBitFromMaskVector(Op, DAG);
10582
10583   if (!isa<ConstantSDNode>(Idx)) {
10584     if (VecVT.is512BitVector() ||
10585         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10586          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10587
10588       MVT MaskEltVT =
10589         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10590       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10591                                     MaskEltVT.getSizeInBits());
10592
10593       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10594       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10595                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10596                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10597       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10598       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10599                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10600     }
10601     return SDValue();
10602   }
10603
10604   // If this is a 256-bit vector result, first extract the 128-bit vector and
10605   // then extract the element from the 128-bit vector.
10606   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10607
10608     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10609     // Get the 128-bit vector.
10610     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10611     MVT EltVT = VecVT.getVectorElementType();
10612
10613     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10614
10615     //if (IdxVal >= NumElems/2)
10616     //  IdxVal -= NumElems/2;
10617     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10618     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10619                        DAG.getConstant(IdxVal, dl, MVT::i32));
10620   }
10621
10622   assert(VecVT.is128BitVector() && "Unexpected vector length");
10623
10624   if (Subtarget->hasSSE41()) {
10625     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10626     if (Res.getNode())
10627       return Res;
10628   }
10629
10630   MVT VT = Op.getSimpleValueType();
10631   // TODO: handle v16i8.
10632   if (VT.getSizeInBits() == 16) {
10633     SDValue Vec = Op.getOperand(0);
10634     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10635     if (Idx == 0)
10636       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10637                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10638                                      DAG.getNode(ISD::BITCAST, dl,
10639                                                  MVT::v4i32, Vec),
10640                                      Op.getOperand(1)));
10641     // Transform it so it match pextrw which produces a 32-bit result.
10642     MVT EltVT = MVT::i32;
10643     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10644                                   Op.getOperand(0), Op.getOperand(1));
10645     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10646                                   DAG.getValueType(VT));
10647     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10648   }
10649
10650   if (VT.getSizeInBits() == 32) {
10651     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10652     if (Idx == 0)
10653       return Op;
10654
10655     // SHUFPS the element to the lowest double word, then movss.
10656     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10657     MVT VVT = Op.getOperand(0).getSimpleValueType();
10658     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10659                                        DAG.getUNDEF(VVT), Mask);
10660     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10661                        DAG.getIntPtrConstant(0, dl));
10662   }
10663
10664   if (VT.getSizeInBits() == 64) {
10665     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10666     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10667     //        to match extract_elt for f64.
10668     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10669     if (Idx == 0)
10670       return Op;
10671
10672     // UNPCKHPD the element to the lowest double word, then movsd.
10673     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10674     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10675     int Mask[2] = { 1, -1 };
10676     MVT VVT = Op.getOperand(0).getSimpleValueType();
10677     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10678                                        DAG.getUNDEF(VVT), Mask);
10679     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10680                        DAG.getIntPtrConstant(0, dl));
10681   }
10682
10683   return SDValue();
10684 }
10685
10686 /// Insert one bit to mask vector, like v16i1 or v8i1.
10687 /// AVX-512 feature.
10688 SDValue
10689 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10690   SDLoc dl(Op);
10691   SDValue Vec = Op.getOperand(0);
10692   SDValue Elt = Op.getOperand(1);
10693   SDValue Idx = Op.getOperand(2);
10694   MVT VecVT = Vec.getSimpleValueType();
10695
10696   if (!isa<ConstantSDNode>(Idx)) {
10697     // Non constant index. Extend source and destination,
10698     // insert element and then truncate the result.
10699     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10700     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10701     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10702       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10703       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10704     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10705   }
10706
10707   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10708   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10709   if (IdxVal)
10710     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10711                            DAG.getConstant(IdxVal, dl, MVT::i8));
10712   if (Vec.getOpcode() == ISD::UNDEF)
10713     return EltInVec;
10714   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10715 }
10716
10717 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10718                                                   SelectionDAG &DAG) const {
10719   MVT VT = Op.getSimpleValueType();
10720   MVT EltVT = VT.getVectorElementType();
10721
10722   if (EltVT == MVT::i1)
10723     return InsertBitToMaskVector(Op, DAG);
10724
10725   SDLoc dl(Op);
10726   SDValue N0 = Op.getOperand(0);
10727   SDValue N1 = Op.getOperand(1);
10728   SDValue N2 = Op.getOperand(2);
10729   if (!isa<ConstantSDNode>(N2))
10730     return SDValue();
10731   auto *N2C = cast<ConstantSDNode>(N2);
10732   unsigned IdxVal = N2C->getZExtValue();
10733
10734   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10735   // into that, and then insert the subvector back into the result.
10736   if (VT.is256BitVector() || VT.is512BitVector()) {
10737     // With a 256-bit vector, we can insert into the zero element efficiently
10738     // using a blend if we have AVX or AVX2 and the right data type.
10739     if (VT.is256BitVector() && IdxVal == 0) {
10740       // TODO: It is worthwhile to cast integer to floating point and back
10741       // and incur a domain crossing penalty if that's what we'll end up
10742       // doing anyway after extracting to a 128-bit vector.
10743       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10744           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10745         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10746         N2 = DAG.getIntPtrConstant(1, dl);
10747         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10748       }
10749     }
10750
10751     // Get the desired 128-bit vector chunk.
10752     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10753
10754     // Insert the element into the desired chunk.
10755     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10756     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10757
10758     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10759                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10760
10761     // Insert the changed part back into the bigger vector
10762     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10763   }
10764   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10765
10766   if (Subtarget->hasSSE41()) {
10767     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10768       unsigned Opc;
10769       if (VT == MVT::v8i16) {
10770         Opc = X86ISD::PINSRW;
10771       } else {
10772         assert(VT == MVT::v16i8);
10773         Opc = X86ISD::PINSRB;
10774       }
10775
10776       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10777       // argument.
10778       if (N1.getValueType() != MVT::i32)
10779         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10780       if (N2.getValueType() != MVT::i32)
10781         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10782       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10783     }
10784
10785     if (EltVT == MVT::f32) {
10786       // Bits [7:6] of the constant are the source select. This will always be
10787       //   zero here. The DAG Combiner may combine an extract_elt index into
10788       //   these bits. For example (insert (extract, 3), 2) could be matched by
10789       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10790       // Bits [5:4] of the constant are the destination select. This is the
10791       //   value of the incoming immediate.
10792       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10793       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10794
10795       const Function *F = DAG.getMachineFunction().getFunction();
10796       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10797       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10798         // If this is an insertion of 32-bits into the low 32-bits of
10799         // a vector, we prefer to generate a blend with immediate rather
10800         // than an insertps. Blends are simpler operations in hardware and so
10801         // will always have equal or better performance than insertps.
10802         // But if optimizing for size and there's a load folding opportunity,
10803         // generate insertps because blendps does not have a 32-bit memory
10804         // operand form.
10805         N2 = DAG.getIntPtrConstant(1, dl);
10806         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10807         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10808       }
10809       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10810       // Create this as a scalar to vector..
10811       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10812       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10813     }
10814
10815     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10816       // PINSR* works with constant index.
10817       return Op;
10818     }
10819   }
10820
10821   if (EltVT == MVT::i8)
10822     return SDValue();
10823
10824   if (EltVT.getSizeInBits() == 16) {
10825     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10826     // as its second argument.
10827     if (N1.getValueType() != MVT::i32)
10828       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10829     if (N2.getValueType() != MVT::i32)
10830       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10831     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10832   }
10833   return SDValue();
10834 }
10835
10836 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10837   SDLoc dl(Op);
10838   MVT OpVT = Op.getSimpleValueType();
10839
10840   // If this is a 256-bit vector result, first insert into a 128-bit
10841   // vector and then insert into the 256-bit vector.
10842   if (!OpVT.is128BitVector()) {
10843     // Insert into a 128-bit vector.
10844     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10845     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10846                                  OpVT.getVectorNumElements() / SizeFactor);
10847
10848     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10849
10850     // Insert the 128-bit vector.
10851     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10852   }
10853
10854   if (OpVT == MVT::v1i64 &&
10855       Op.getOperand(0).getValueType() == MVT::i64)
10856     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10857
10858   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10859   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10860   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10861                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10862 }
10863
10864 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10865 // a simple subregister reference or explicit instructions to grab
10866 // upper bits of a vector.
10867 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10868                                       SelectionDAG &DAG) {
10869   SDLoc dl(Op);
10870   SDValue In =  Op.getOperand(0);
10871   SDValue Idx = Op.getOperand(1);
10872   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10873   MVT ResVT   = Op.getSimpleValueType();
10874   MVT InVT    = In.getSimpleValueType();
10875
10876   if (Subtarget->hasFp256()) {
10877     if (ResVT.is128BitVector() &&
10878         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10879         isa<ConstantSDNode>(Idx)) {
10880       return Extract128BitVector(In, IdxVal, DAG, dl);
10881     }
10882     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10883         isa<ConstantSDNode>(Idx)) {
10884       return Extract256BitVector(In, IdxVal, DAG, dl);
10885     }
10886   }
10887   return SDValue();
10888 }
10889
10890 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10891 // simple superregister reference or explicit instructions to insert
10892 // the upper bits of a vector.
10893 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10894                                      SelectionDAG &DAG) {
10895   if (!Subtarget->hasAVX())
10896     return SDValue();
10897
10898   SDLoc dl(Op);
10899   SDValue Vec = Op.getOperand(0);
10900   SDValue SubVec = Op.getOperand(1);
10901   SDValue Idx = Op.getOperand(2);
10902
10903   if (!isa<ConstantSDNode>(Idx))
10904     return SDValue();
10905
10906   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10907   MVT OpVT = Op.getSimpleValueType();
10908   MVT SubVecVT = SubVec.getSimpleValueType();
10909
10910   // Fold two 16-byte subvector loads into one 32-byte load:
10911   // (insert_subvector (insert_subvector undef, (load addr), 0),
10912   //                   (load addr + 16), Elts/2)
10913   // --> load32 addr
10914   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10915       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10916       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10917       !Subtarget->isUnalignedMem32Slow()) {
10918     SDValue SubVec2 = Vec.getOperand(1);
10919     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10920       if (Idx2->getZExtValue() == 0) {
10921         SDValue Ops[] = { SubVec2, SubVec };
10922         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10923         if (LD.getNode())
10924           return LD;
10925       }
10926     }
10927   }
10928
10929   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10930       SubVecVT.is128BitVector())
10931     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10932
10933   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10934     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10935
10936   if (OpVT.getVectorElementType() == MVT::i1) {
10937     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10938       return Op;
10939     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10940     SDValue Undef = DAG.getUNDEF(OpVT);
10941     unsigned NumElems = OpVT.getVectorNumElements();
10942     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10943
10944     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10945       // Zero upper bits of the Vec
10946       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10947       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10948
10949       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10950                                  SubVec, ZeroIdx);
10951       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10952       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10953     }
10954     if (IdxVal == 0) {
10955       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10956                                  SubVec, ZeroIdx);
10957       // Zero upper bits of the Vec2
10958       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10959       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10960       // Zero lower bits of the Vec
10961       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10962       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10963       // Merge them together
10964       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10965     }
10966   }
10967   return SDValue();
10968 }
10969
10970 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10971 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10972 // one of the above mentioned nodes. It has to be wrapped because otherwise
10973 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10974 // be used to form addressing mode. These wrapped nodes will be selected
10975 // into MOV32ri.
10976 SDValue
10977 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10978   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10979
10980   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10981   // global base reg.
10982   unsigned char OpFlag = 0;
10983   unsigned WrapperKind = X86ISD::Wrapper;
10984   CodeModel::Model M = DAG.getTarget().getCodeModel();
10985
10986   if (Subtarget->isPICStyleRIPRel() &&
10987       (M == CodeModel::Small || M == CodeModel::Kernel))
10988     WrapperKind = X86ISD::WrapperRIP;
10989   else if (Subtarget->isPICStyleGOT())
10990     OpFlag = X86II::MO_GOTOFF;
10991   else if (Subtarget->isPICStyleStubPIC())
10992     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10993
10994   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10995                                              CP->getAlignment(),
10996                                              CP->getOffset(), OpFlag);
10997   SDLoc DL(CP);
10998   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10999   // With PIC, the address is actually $g + Offset.
11000   if (OpFlag) {
11001     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11002                          DAG.getNode(X86ISD::GlobalBaseReg,
11003                                      SDLoc(), getPointerTy()),
11004                          Result);
11005   }
11006
11007   return Result;
11008 }
11009
11010 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11011   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11012
11013   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11014   // global base reg.
11015   unsigned char OpFlag = 0;
11016   unsigned WrapperKind = X86ISD::Wrapper;
11017   CodeModel::Model M = DAG.getTarget().getCodeModel();
11018
11019   if (Subtarget->isPICStyleRIPRel() &&
11020       (M == CodeModel::Small || M == CodeModel::Kernel))
11021     WrapperKind = X86ISD::WrapperRIP;
11022   else if (Subtarget->isPICStyleGOT())
11023     OpFlag = X86II::MO_GOTOFF;
11024   else if (Subtarget->isPICStyleStubPIC())
11025     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11026
11027   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11028                                           OpFlag);
11029   SDLoc DL(JT);
11030   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11031
11032   // With PIC, the address is actually $g + Offset.
11033   if (OpFlag)
11034     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11035                          DAG.getNode(X86ISD::GlobalBaseReg,
11036                                      SDLoc(), getPointerTy()),
11037                          Result);
11038
11039   return Result;
11040 }
11041
11042 SDValue
11043 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11044   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11045
11046   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11047   // global base reg.
11048   unsigned char OpFlag = 0;
11049   unsigned WrapperKind = X86ISD::Wrapper;
11050   CodeModel::Model M = DAG.getTarget().getCodeModel();
11051
11052   if (Subtarget->isPICStyleRIPRel() &&
11053       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11054     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11055       OpFlag = X86II::MO_GOTPCREL;
11056     WrapperKind = X86ISD::WrapperRIP;
11057   } else if (Subtarget->isPICStyleGOT()) {
11058     OpFlag = X86II::MO_GOT;
11059   } else if (Subtarget->isPICStyleStubPIC()) {
11060     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11061   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11062     OpFlag = X86II::MO_DARWIN_NONLAZY;
11063   }
11064
11065   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11066
11067   SDLoc DL(Op);
11068   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11069
11070   // With PIC, the address is actually $g + Offset.
11071   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11072       !Subtarget->is64Bit()) {
11073     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11074                          DAG.getNode(X86ISD::GlobalBaseReg,
11075                                      SDLoc(), getPointerTy()),
11076                          Result);
11077   }
11078
11079   // For symbols that require a load from a stub to get the address, emit the
11080   // load.
11081   if (isGlobalStubReference(OpFlag))
11082     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11083                          MachinePointerInfo::getGOT(), false, false, false, 0);
11084
11085   return Result;
11086 }
11087
11088 SDValue
11089 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11090   // Create the TargetBlockAddressAddress node.
11091   unsigned char OpFlags =
11092     Subtarget->ClassifyBlockAddressReference();
11093   CodeModel::Model M = DAG.getTarget().getCodeModel();
11094   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11095   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11096   SDLoc dl(Op);
11097   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11098                                              OpFlags);
11099
11100   if (Subtarget->isPICStyleRIPRel() &&
11101       (M == CodeModel::Small || M == CodeModel::Kernel))
11102     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11103   else
11104     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11105
11106   // With PIC, the address is actually $g + Offset.
11107   if (isGlobalRelativeToPICBase(OpFlags)) {
11108     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11109                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11110                          Result);
11111   }
11112
11113   return Result;
11114 }
11115
11116 SDValue
11117 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11118                                       int64_t Offset, SelectionDAG &DAG) const {
11119   // Create the TargetGlobalAddress node, folding in the constant
11120   // offset if it is legal.
11121   unsigned char OpFlags =
11122       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11123   CodeModel::Model M = DAG.getTarget().getCodeModel();
11124   SDValue Result;
11125   if (OpFlags == X86II::MO_NO_FLAG &&
11126       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11127     // A direct static reference to a global.
11128     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11129     Offset = 0;
11130   } else {
11131     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11132   }
11133
11134   if (Subtarget->isPICStyleRIPRel() &&
11135       (M == CodeModel::Small || M == CodeModel::Kernel))
11136     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11137   else
11138     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11139
11140   // With PIC, the address is actually $g + Offset.
11141   if (isGlobalRelativeToPICBase(OpFlags)) {
11142     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11143                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11144                          Result);
11145   }
11146
11147   // For globals that require a load from a stub to get the address, emit the
11148   // load.
11149   if (isGlobalStubReference(OpFlags))
11150     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11151                          MachinePointerInfo::getGOT(), false, false, false, 0);
11152
11153   // If there was a non-zero offset that we didn't fold, create an explicit
11154   // addition for it.
11155   if (Offset != 0)
11156     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11157                          DAG.getConstant(Offset, dl, getPointerTy()));
11158
11159   return Result;
11160 }
11161
11162 SDValue
11163 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11164   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11165   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11166   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11167 }
11168
11169 static SDValue
11170 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11171            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11172            unsigned char OperandFlags, bool LocalDynamic = false) {
11173   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11174   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11175   SDLoc dl(GA);
11176   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11177                                            GA->getValueType(0),
11178                                            GA->getOffset(),
11179                                            OperandFlags);
11180
11181   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11182                                            : X86ISD::TLSADDR;
11183
11184   if (InFlag) {
11185     SDValue Ops[] = { Chain,  TGA, *InFlag };
11186     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11187   } else {
11188     SDValue Ops[]  = { Chain, TGA };
11189     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11190   }
11191
11192   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11193   MFI->setAdjustsStack(true);
11194   MFI->setHasCalls(true);
11195
11196   SDValue Flag = Chain.getValue(1);
11197   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11198 }
11199
11200 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11201 static SDValue
11202 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11203                                 const EVT PtrVT) {
11204   SDValue InFlag;
11205   SDLoc dl(GA);  // ? function entry point might be better
11206   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11207                                    DAG.getNode(X86ISD::GlobalBaseReg,
11208                                                SDLoc(), PtrVT), InFlag);
11209   InFlag = Chain.getValue(1);
11210
11211   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11212 }
11213
11214 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11215 static SDValue
11216 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11217                                 const EVT PtrVT) {
11218   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11219                     X86::RAX, X86II::MO_TLSGD);
11220 }
11221
11222 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11223                                            SelectionDAG &DAG,
11224                                            const EVT PtrVT,
11225                                            bool is64Bit) {
11226   SDLoc dl(GA);
11227
11228   // Get the start address of the TLS block for this module.
11229   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11230       .getInfo<X86MachineFunctionInfo>();
11231   MFI->incNumLocalDynamicTLSAccesses();
11232
11233   SDValue Base;
11234   if (is64Bit) {
11235     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11236                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11237   } else {
11238     SDValue InFlag;
11239     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11240         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11241     InFlag = Chain.getValue(1);
11242     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11243                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11244   }
11245
11246   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11247   // of Base.
11248
11249   // Build x@dtpoff.
11250   unsigned char OperandFlags = X86II::MO_DTPOFF;
11251   unsigned WrapperKind = X86ISD::Wrapper;
11252   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11253                                            GA->getValueType(0),
11254                                            GA->getOffset(), OperandFlags);
11255   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11256
11257   // Add x@dtpoff with the base.
11258   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11259 }
11260
11261 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11262 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11263                                    const EVT PtrVT, TLSModel::Model model,
11264                                    bool is64Bit, bool isPIC) {
11265   SDLoc dl(GA);
11266
11267   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11268   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11269                                                          is64Bit ? 257 : 256));
11270
11271   SDValue ThreadPointer =
11272       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11273                   MachinePointerInfo(Ptr), false, false, false, 0);
11274
11275   unsigned char OperandFlags = 0;
11276   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11277   // initialexec.
11278   unsigned WrapperKind = X86ISD::Wrapper;
11279   if (model == TLSModel::LocalExec) {
11280     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11281   } else if (model == TLSModel::InitialExec) {
11282     if (is64Bit) {
11283       OperandFlags = X86II::MO_GOTTPOFF;
11284       WrapperKind = X86ISD::WrapperRIP;
11285     } else {
11286       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11287     }
11288   } else {
11289     llvm_unreachable("Unexpected model");
11290   }
11291
11292   // emit "addl x@ntpoff,%eax" (local exec)
11293   // or "addl x@indntpoff,%eax" (initial exec)
11294   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11295   SDValue TGA =
11296       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11297                                  GA->getOffset(), OperandFlags);
11298   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11299
11300   if (model == TLSModel::InitialExec) {
11301     if (isPIC && !is64Bit) {
11302       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11303                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11304                            Offset);
11305     }
11306
11307     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11308                          MachinePointerInfo::getGOT(), false, false, false, 0);
11309   }
11310
11311   // The address of the thread local variable is the add of the thread
11312   // pointer with the offset of the variable.
11313   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11314 }
11315
11316 SDValue
11317 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11318
11319   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11320   const GlobalValue *GV = GA->getGlobal();
11321
11322   if (Subtarget->isTargetELF()) {
11323     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11324     switch (model) {
11325       case TLSModel::GeneralDynamic:
11326         if (Subtarget->is64Bit())
11327           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11328         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11329       case TLSModel::LocalDynamic:
11330         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11331                                            Subtarget->is64Bit());
11332       case TLSModel::InitialExec:
11333       case TLSModel::LocalExec:
11334         return LowerToTLSExecModel(
11335             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11336             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11337     }
11338     llvm_unreachable("Unknown TLS model.");
11339   }
11340
11341   if (Subtarget->isTargetDarwin()) {
11342     // Darwin only has one model of TLS.  Lower to that.
11343     unsigned char OpFlag = 0;
11344     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11345                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11346
11347     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11348     // global base reg.
11349     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11350                  !Subtarget->is64Bit();
11351     if (PIC32)
11352       OpFlag = X86II::MO_TLVP_PIC_BASE;
11353     else
11354       OpFlag = X86II::MO_TLVP;
11355     SDLoc DL(Op);
11356     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11357                                                 GA->getValueType(0),
11358                                                 GA->getOffset(), OpFlag);
11359     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11360
11361     // With PIC32, the address is actually $g + Offset.
11362     if (PIC32)
11363       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11364                            DAG.getNode(X86ISD::GlobalBaseReg,
11365                                        SDLoc(), getPointerTy()),
11366                            Offset);
11367
11368     // Lowering the machine isd will make sure everything is in the right
11369     // location.
11370     SDValue Chain = DAG.getEntryNode();
11371     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11372     SDValue Args[] = { Chain, Offset };
11373     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11374
11375     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11376     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11377     MFI->setAdjustsStack(true);
11378
11379     // And our return value (tls address) is in the standard call return value
11380     // location.
11381     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11382     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11383                               Chain.getValue(1));
11384   }
11385
11386   if (Subtarget->isTargetKnownWindowsMSVC() ||
11387       Subtarget->isTargetWindowsGNU()) {
11388     // Just use the implicit TLS architecture
11389     // Need to generate someting similar to:
11390     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11391     //                                  ; from TEB
11392     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11393     //   mov     rcx, qword [rdx+rcx*8]
11394     //   mov     eax, .tls$:tlsvar
11395     //   [rax+rcx] contains the address
11396     // Windows 64bit: gs:0x58
11397     // Windows 32bit: fs:__tls_array
11398
11399     SDLoc dl(GA);
11400     SDValue Chain = DAG.getEntryNode();
11401
11402     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11403     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11404     // use its literal value of 0x2C.
11405     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11406                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11407                                                              256)
11408                                         : Type::getInt32PtrTy(*DAG.getContext(),
11409                                                               257));
11410
11411     SDValue TlsArray =
11412         Subtarget->is64Bit()
11413             ? DAG.getIntPtrConstant(0x58, dl)
11414             : (Subtarget->isTargetWindowsGNU()
11415                    ? DAG.getIntPtrConstant(0x2C, dl)
11416                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11417
11418     SDValue ThreadPointer =
11419         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11420                     MachinePointerInfo(Ptr), false, false, false, 0);
11421
11422     SDValue res;
11423     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11424       res = ThreadPointer;
11425     } else {
11426       // Load the _tls_index variable
11427       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11428       if (Subtarget->is64Bit())
11429         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11430                              MachinePointerInfo(), MVT::i32, false, false,
11431                              false, 0);
11432       else
11433         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11434                           false, false, false, 0);
11435
11436       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11437                                       getPointerTy());
11438       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11439
11440       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11441     }
11442
11443     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11444                       false, false, false, 0);
11445
11446     // Get the offset of start of .tls section
11447     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11448                                              GA->getValueType(0),
11449                                              GA->getOffset(), X86II::MO_SECREL);
11450     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11451
11452     // The address of the thread local variable is the add of the thread
11453     // pointer with the offset of the variable.
11454     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11455   }
11456
11457   llvm_unreachable("TLS not implemented for this target.");
11458 }
11459
11460 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11461 /// and take a 2 x i32 value to shift plus a shift amount.
11462 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11463   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11464   MVT VT = Op.getSimpleValueType();
11465   unsigned VTBits = VT.getSizeInBits();
11466   SDLoc dl(Op);
11467   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11468   SDValue ShOpLo = Op.getOperand(0);
11469   SDValue ShOpHi = Op.getOperand(1);
11470   SDValue ShAmt  = Op.getOperand(2);
11471   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11472   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11473   // during isel.
11474   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11475                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11476   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11477                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11478                        : DAG.getConstant(0, dl, VT);
11479
11480   SDValue Tmp2, Tmp3;
11481   if (Op.getOpcode() == ISD::SHL_PARTS) {
11482     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11483     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11484   } else {
11485     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11486     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11487   }
11488
11489   // If the shift amount is larger or equal than the width of a part we can't
11490   // rely on the results of shld/shrd. Insert a test and select the appropriate
11491   // values for large shift amounts.
11492   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11493                                 DAG.getConstant(VTBits, dl, MVT::i8));
11494   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11495                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11496
11497   SDValue Hi, Lo;
11498   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11499   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11500   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11501
11502   if (Op.getOpcode() == ISD::SHL_PARTS) {
11503     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11504     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11505   } else {
11506     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11507     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11508   }
11509
11510   SDValue Ops[2] = { Lo, Hi };
11511   return DAG.getMergeValues(Ops, dl);
11512 }
11513
11514 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11515                                            SelectionDAG &DAG) const {
11516   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11517   SDLoc dl(Op);
11518
11519   if (SrcVT.isVector()) {
11520     if (SrcVT.getVectorElementType() == MVT::i1) {
11521       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11522       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11523                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11524                                      Op.getOperand(0)));
11525     }
11526     return SDValue();
11527   }
11528
11529   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11530          "Unknown SINT_TO_FP to lower!");
11531
11532   // These are really Legal; return the operand so the caller accepts it as
11533   // Legal.
11534   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11535     return Op;
11536   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11537       Subtarget->is64Bit()) {
11538     return Op;
11539   }
11540
11541   unsigned Size = SrcVT.getSizeInBits()/8;
11542   MachineFunction &MF = DAG.getMachineFunction();
11543   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11544   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11545   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11546                                StackSlot,
11547                                MachinePointerInfo::getFixedStack(SSFI),
11548                                false, false, 0);
11549   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11550 }
11551
11552 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11553                                      SDValue StackSlot,
11554                                      SelectionDAG &DAG) const {
11555   // Build the FILD
11556   SDLoc DL(Op);
11557   SDVTList Tys;
11558   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11559   if (useSSE)
11560     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11561   else
11562     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11563
11564   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11565
11566   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11567   MachineMemOperand *MMO;
11568   if (FI) {
11569     int SSFI = FI->getIndex();
11570     MMO =
11571       DAG.getMachineFunction()
11572       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11573                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11574   } else {
11575     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11576     StackSlot = StackSlot.getOperand(1);
11577   }
11578   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11579   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11580                                            X86ISD::FILD, DL,
11581                                            Tys, Ops, SrcVT, MMO);
11582
11583   if (useSSE) {
11584     Chain = Result.getValue(1);
11585     SDValue InFlag = Result.getValue(2);
11586
11587     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11588     // shouldn't be necessary except that RFP cannot be live across
11589     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11590     MachineFunction &MF = DAG.getMachineFunction();
11591     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11592     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11593     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11594     Tys = DAG.getVTList(MVT::Other);
11595     SDValue Ops[] = {
11596       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11597     };
11598     MachineMemOperand *MMO =
11599       DAG.getMachineFunction()
11600       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11601                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11602
11603     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11604                                     Ops, Op.getValueType(), MMO);
11605     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11606                          MachinePointerInfo::getFixedStack(SSFI),
11607                          false, false, false, 0);
11608   }
11609
11610   return Result;
11611 }
11612
11613 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11614 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11615                                                SelectionDAG &DAG) const {
11616   // This algorithm is not obvious. Here it is what we're trying to output:
11617   /*
11618      movq       %rax,  %xmm0
11619      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11620      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11621      #ifdef __SSE3__
11622        haddpd   %xmm0, %xmm0
11623      #else
11624        pshufd   $0x4e, %xmm0, %xmm1
11625        addpd    %xmm1, %xmm0
11626      #endif
11627   */
11628
11629   SDLoc dl(Op);
11630   LLVMContext *Context = DAG.getContext();
11631
11632   // Build some magic constants.
11633   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11634   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11635   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11636
11637   SmallVector<Constant*,2> CV1;
11638   CV1.push_back(
11639     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11640                                       APInt(64, 0x4330000000000000ULL))));
11641   CV1.push_back(
11642     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11643                                       APInt(64, 0x4530000000000000ULL))));
11644   Constant *C1 = ConstantVector::get(CV1);
11645   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11646
11647   // Load the 64-bit value into an XMM register.
11648   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11649                             Op.getOperand(0));
11650   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11651                               MachinePointerInfo::getConstantPool(),
11652                               false, false, false, 16);
11653   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11654                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11655                               CLod0);
11656
11657   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11658                               MachinePointerInfo::getConstantPool(),
11659                               false, false, false, 16);
11660   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11661   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11662   SDValue Result;
11663
11664   if (Subtarget->hasSSE3()) {
11665     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11666     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11667   } else {
11668     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11669     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11670                                            S2F, 0x4E, DAG);
11671     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11672                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11673                          Sub);
11674   }
11675
11676   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11677                      DAG.getIntPtrConstant(0, dl));
11678 }
11679
11680 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11681 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11682                                                SelectionDAG &DAG) const {
11683   SDLoc dl(Op);
11684   // FP constant to bias correct the final result.
11685   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11686                                    MVT::f64);
11687
11688   // Load the 32-bit value into an XMM register.
11689   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11690                              Op.getOperand(0));
11691
11692   // Zero out the upper parts of the register.
11693   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11694
11695   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11696                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11697                      DAG.getIntPtrConstant(0, dl));
11698
11699   // Or the load with the bias.
11700   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11701                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11702                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11703                                                    MVT::v2f64, Load)),
11704                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11705                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11706                                                    MVT::v2f64, Bias)));
11707   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11708                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11709                    DAG.getIntPtrConstant(0, dl));
11710
11711   // Subtract the bias.
11712   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11713
11714   // Handle final rounding.
11715   EVT DestVT = Op.getValueType();
11716
11717   if (DestVT.bitsLT(MVT::f64))
11718     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11719                        DAG.getIntPtrConstant(0, dl));
11720   if (DestVT.bitsGT(MVT::f64))
11721     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11722
11723   // Handle final rounding.
11724   return Sub;
11725 }
11726
11727 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11728                                      const X86Subtarget &Subtarget) {
11729   // The algorithm is the following:
11730   // #ifdef __SSE4_1__
11731   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11732   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11733   //                                 (uint4) 0x53000000, 0xaa);
11734   // #else
11735   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11736   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11737   // #endif
11738   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11739   //     return (float4) lo + fhi;
11740
11741   SDLoc DL(Op);
11742   SDValue V = Op->getOperand(0);
11743   EVT VecIntVT = V.getValueType();
11744   bool Is128 = VecIntVT == MVT::v4i32;
11745   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11746   // If we convert to something else than the supported type, e.g., to v4f64,
11747   // abort early.
11748   if (VecFloatVT != Op->getValueType(0))
11749     return SDValue();
11750
11751   unsigned NumElts = VecIntVT.getVectorNumElements();
11752   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11753          "Unsupported custom type");
11754   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11755
11756   // In the #idef/#else code, we have in common:
11757   // - The vector of constants:
11758   // -- 0x4b000000
11759   // -- 0x53000000
11760   // - A shift:
11761   // -- v >> 16
11762
11763   // Create the splat vector for 0x4b000000.
11764   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11765   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11766                            CstLow, CstLow, CstLow, CstLow};
11767   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11768                                   makeArrayRef(&CstLowArray[0], NumElts));
11769   // Create the splat vector for 0x53000000.
11770   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11771   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11772                             CstHigh, CstHigh, CstHigh, CstHigh};
11773   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11774                                    makeArrayRef(&CstHighArray[0], NumElts));
11775
11776   // Create the right shift.
11777   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11778   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11779                              CstShift, CstShift, CstShift, CstShift};
11780   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11781                                     makeArrayRef(&CstShiftArray[0], NumElts));
11782   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11783
11784   SDValue Low, High;
11785   if (Subtarget.hasSSE41()) {
11786     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11787     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11788     SDValue VecCstLowBitcast =
11789         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11790     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11791     // Low will be bitcasted right away, so do not bother bitcasting back to its
11792     // original type.
11793     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11794                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11795     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11796     //                                 (uint4) 0x53000000, 0xaa);
11797     SDValue VecCstHighBitcast =
11798         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11799     SDValue VecShiftBitcast =
11800         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11801     // High will be bitcasted right away, so do not bother bitcasting back to
11802     // its original type.
11803     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11804                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11805   } else {
11806     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11807     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11808                                      CstMask, CstMask, CstMask);
11809     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11810     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11811     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11812
11813     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11814     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11815   }
11816
11817   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11818   SDValue CstFAdd = DAG.getConstantFP(
11819       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11820   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11821                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11822   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11823                                    makeArrayRef(&CstFAddArray[0], NumElts));
11824
11825   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11826   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11827   SDValue FHigh =
11828       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11829   //     return (float4) lo + fhi;
11830   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11831   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11832 }
11833
11834 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11835                                                SelectionDAG &DAG) const {
11836   SDValue N0 = Op.getOperand(0);
11837   MVT SVT = N0.getSimpleValueType();
11838   SDLoc dl(Op);
11839
11840   switch (SVT.SimpleTy) {
11841   default:
11842     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11843   case MVT::v4i8:
11844   case MVT::v4i16:
11845   case MVT::v8i8:
11846   case MVT::v8i16: {
11847     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11848     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11849                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11850   }
11851   case MVT::v4i32:
11852   case MVT::v8i32:
11853     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11854   case MVT::v16i8:
11855   case MVT::v16i16:
11856     if (Subtarget->hasAVX512())
11857       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11858                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11859   }
11860   llvm_unreachable(nullptr);
11861 }
11862
11863 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11864                                            SelectionDAG &DAG) const {
11865   SDValue N0 = Op.getOperand(0);
11866   SDLoc dl(Op);
11867
11868   if (Op.getValueType().isVector())
11869     return lowerUINT_TO_FP_vec(Op, DAG);
11870
11871   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11872   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11873   // the optimization here.
11874   if (DAG.SignBitIsZero(N0))
11875     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11876
11877   MVT SrcVT = N0.getSimpleValueType();
11878   MVT DstVT = Op.getSimpleValueType();
11879   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11880     return LowerUINT_TO_FP_i64(Op, DAG);
11881   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11882     return LowerUINT_TO_FP_i32(Op, DAG);
11883   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11884     return SDValue();
11885
11886   // Make a 64-bit buffer, and use it to build an FILD.
11887   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11888   if (SrcVT == MVT::i32) {
11889     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11890     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11891                                      getPointerTy(), StackSlot, WordOff);
11892     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11893                                   StackSlot, MachinePointerInfo(),
11894                                   false, false, 0);
11895     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11896                                   OffsetSlot, MachinePointerInfo(),
11897                                   false, false, 0);
11898     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11899     return Fild;
11900   }
11901
11902   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11903   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11904                                StackSlot, MachinePointerInfo(),
11905                                false, false, 0);
11906   // For i64 source, we need to add the appropriate power of 2 if the input
11907   // was negative.  This is the same as the optimization in
11908   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11909   // we must be careful to do the computation in x87 extended precision, not
11910   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11911   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11912   MachineMemOperand *MMO =
11913     DAG.getMachineFunction()
11914     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11915                           MachineMemOperand::MOLoad, 8, 8);
11916
11917   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11918   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11919   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11920                                          MVT::i64, MMO);
11921
11922   APInt FF(32, 0x5F800000ULL);
11923
11924   // Check whether the sign bit is set.
11925   SDValue SignSet = DAG.getSetCC(dl,
11926                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11927                                  Op.getOperand(0),
11928                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11929
11930   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11931   SDValue FudgePtr = DAG.getConstantPool(
11932                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11933                                          getPointerTy());
11934
11935   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11936   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11937   SDValue Four = DAG.getIntPtrConstant(4, dl);
11938   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11939                                Zero, Four);
11940   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11941
11942   // Load the value out, extending it from f32 to f80.
11943   // FIXME: Avoid the extend by constructing the right constant pool?
11944   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11945                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11946                                  MVT::f32, false, false, false, 4);
11947   // Extend everything to 80 bits to force it to be done on x87.
11948   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11949   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11950                      DAG.getIntPtrConstant(0, dl));
11951 }
11952
11953 std::pair<SDValue,SDValue>
11954 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11955                                     bool IsSigned, bool IsReplace) const {
11956   SDLoc DL(Op);
11957
11958   EVT DstTy = Op.getValueType();
11959
11960   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11961     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11962     DstTy = MVT::i64;
11963   }
11964
11965   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11966          DstTy.getSimpleVT() >= MVT::i16 &&
11967          "Unknown FP_TO_INT to lower!");
11968
11969   // These are really Legal.
11970   if (DstTy == MVT::i32 &&
11971       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11972     return std::make_pair(SDValue(), SDValue());
11973   if (Subtarget->is64Bit() &&
11974       DstTy == MVT::i64 &&
11975       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11976     return std::make_pair(SDValue(), SDValue());
11977
11978   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11979   // stack slot, or into the FTOL runtime function.
11980   MachineFunction &MF = DAG.getMachineFunction();
11981   unsigned MemSize = DstTy.getSizeInBits()/8;
11982   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11983   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11984
11985   unsigned Opc;
11986   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11987     Opc = X86ISD::WIN_FTOL;
11988   else
11989     switch (DstTy.getSimpleVT().SimpleTy) {
11990     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11991     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11992     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11993     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11994     }
11995
11996   SDValue Chain = DAG.getEntryNode();
11997   SDValue Value = Op.getOperand(0);
11998   EVT TheVT = Op.getOperand(0).getValueType();
11999   // FIXME This causes a redundant load/store if the SSE-class value is already
12000   // in memory, such as if it is on the callstack.
12001   if (isScalarFPTypeInSSEReg(TheVT)) {
12002     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12003     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12004                          MachinePointerInfo::getFixedStack(SSFI),
12005                          false, false, 0);
12006     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12007     SDValue Ops[] = {
12008       Chain, StackSlot, DAG.getValueType(TheVT)
12009     };
12010
12011     MachineMemOperand *MMO =
12012       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12013                               MachineMemOperand::MOLoad, MemSize, MemSize);
12014     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12015     Chain = Value.getValue(1);
12016     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12017     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12018   }
12019
12020   MachineMemOperand *MMO =
12021     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12022                             MachineMemOperand::MOStore, MemSize, MemSize);
12023
12024   if (Opc != X86ISD::WIN_FTOL) {
12025     // Build the FP_TO_INT*_IN_MEM
12026     SDValue Ops[] = { Chain, Value, StackSlot };
12027     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12028                                            Ops, DstTy, MMO);
12029     return std::make_pair(FIST, StackSlot);
12030   } else {
12031     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12032       DAG.getVTList(MVT::Other, MVT::Glue),
12033       Chain, Value);
12034     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12035       MVT::i32, ftol.getValue(1));
12036     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12037       MVT::i32, eax.getValue(2));
12038     SDValue Ops[] = { eax, edx };
12039     SDValue pair = IsReplace
12040       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12041       : DAG.getMergeValues(Ops, DL);
12042     return std::make_pair(pair, SDValue());
12043   }
12044 }
12045
12046 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12047                               const X86Subtarget *Subtarget) {
12048   MVT VT = Op->getSimpleValueType(0);
12049   SDValue In = Op->getOperand(0);
12050   MVT InVT = In.getSimpleValueType();
12051   SDLoc dl(Op);
12052
12053   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12054     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12055
12056   // Optimize vectors in AVX mode:
12057   //
12058   //   v8i16 -> v8i32
12059   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12060   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12061   //   Concat upper and lower parts.
12062   //
12063   //   v4i32 -> v4i64
12064   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12065   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12066   //   Concat upper and lower parts.
12067   //
12068
12069   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12070       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12071       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12072     return SDValue();
12073
12074   if (Subtarget->hasInt256())
12075     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12076
12077   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12078   SDValue Undef = DAG.getUNDEF(InVT);
12079   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12080   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12081   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12082
12083   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12084                              VT.getVectorNumElements()/2);
12085
12086   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12087   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12088
12089   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12090 }
12091
12092 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12093                                         SelectionDAG &DAG) {
12094   MVT VT = Op->getSimpleValueType(0);
12095   SDValue In = Op->getOperand(0);
12096   MVT InVT = In.getSimpleValueType();
12097   SDLoc DL(Op);
12098   unsigned int NumElts = VT.getVectorNumElements();
12099   if (NumElts != 8 && NumElts != 16)
12100     return SDValue();
12101
12102   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12103     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12104
12105   assert(InVT.getVectorElementType() == MVT::i1);
12106   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12107   SDValue One =
12108    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12109   SDValue Zero =
12110    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12111
12112   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12113   if (VT.is512BitVector())
12114     return V;
12115   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12116 }
12117
12118 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12119                                SelectionDAG &DAG) {
12120   if (Subtarget->hasFp256()) {
12121     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12122     if (Res.getNode())
12123       return Res;
12124   }
12125
12126   return SDValue();
12127 }
12128
12129 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12130                                 SelectionDAG &DAG) {
12131   SDLoc DL(Op);
12132   MVT VT = Op.getSimpleValueType();
12133   SDValue In = Op.getOperand(0);
12134   MVT SVT = In.getSimpleValueType();
12135
12136   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12137     return LowerZERO_EXTEND_AVX512(Op, DAG);
12138
12139   if (Subtarget->hasFp256()) {
12140     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12141     if (Res.getNode())
12142       return Res;
12143   }
12144
12145   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12146          VT.getVectorNumElements() != SVT.getVectorNumElements());
12147   return SDValue();
12148 }
12149
12150 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12151   SDLoc DL(Op);
12152   MVT VT = Op.getSimpleValueType();
12153   SDValue In = Op.getOperand(0);
12154   MVT InVT = In.getSimpleValueType();
12155
12156   if (VT == MVT::i1) {
12157     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12158            "Invalid scalar TRUNCATE operation");
12159     if (InVT.getSizeInBits() >= 32)
12160       return SDValue();
12161     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12162     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12163   }
12164   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12165          "Invalid TRUNCATE operation");
12166
12167   // move vector to mask - truncate solution for SKX
12168   if (VT.getVectorElementType() == MVT::i1) {
12169     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12170         Subtarget->hasBWI())
12171       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12172     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12173         && InVT.getScalarSizeInBits() <= 16 &&
12174         Subtarget->hasBWI() && Subtarget->hasVLX())
12175       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12176     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12177         Subtarget->hasDQI())
12178       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12179     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12180         && InVT.getScalarSizeInBits() >= 32 &&
12181         Subtarget->hasDQI() && Subtarget->hasVLX())
12182       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12183   }
12184   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12185     if (VT.getVectorElementType().getSizeInBits() >=8)
12186       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12187
12188     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12189     unsigned NumElts = InVT.getVectorNumElements();
12190     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12191     if (InVT.getSizeInBits() < 512) {
12192       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12193       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12194       InVT = ExtVT;
12195     }
12196
12197     SDValue OneV =
12198      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12199     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12200     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12201   }
12202
12203   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12204     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12205     if (Subtarget->hasInt256()) {
12206       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12207       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12208       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12209                                 ShufMask);
12210       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12211                          DAG.getIntPtrConstant(0, DL));
12212     }
12213
12214     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12215                                DAG.getIntPtrConstant(0, DL));
12216     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12217                                DAG.getIntPtrConstant(2, DL));
12218     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12219     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12220     static const int ShufMask[] = {0, 2, 4, 6};
12221     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12222   }
12223
12224   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12225     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12226     if (Subtarget->hasInt256()) {
12227       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12228
12229       SmallVector<SDValue,32> pshufbMask;
12230       for (unsigned i = 0; i < 2; ++i) {
12231         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12232         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12233         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12234         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12235         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12236         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12237         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12238         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12239         for (unsigned j = 0; j < 8; ++j)
12240           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12241       }
12242       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12243       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12244       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12245
12246       static const int ShufMask[] = {0,  2,  -1,  -1};
12247       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12248                                 &ShufMask[0]);
12249       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12250                        DAG.getIntPtrConstant(0, DL));
12251       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12252     }
12253
12254     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12255                                DAG.getIntPtrConstant(0, DL));
12256
12257     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12258                                DAG.getIntPtrConstant(4, DL));
12259
12260     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12261     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12262
12263     // The PSHUFB mask:
12264     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12265                                    -1, -1, -1, -1, -1, -1, -1, -1};
12266
12267     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12268     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12269     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12270
12271     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12272     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12273
12274     // The MOVLHPS Mask:
12275     static const int ShufMask2[] = {0, 1, 4, 5};
12276     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12277     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12278   }
12279
12280   // Handle truncation of V256 to V128 using shuffles.
12281   if (!VT.is128BitVector() || !InVT.is256BitVector())
12282     return SDValue();
12283
12284   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12285
12286   unsigned NumElems = VT.getVectorNumElements();
12287   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12288
12289   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12290   // Prepare truncation shuffle mask
12291   for (unsigned i = 0; i != NumElems; ++i)
12292     MaskVec[i] = i * 2;
12293   SDValue V = DAG.getVectorShuffle(NVT, DL,
12294                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12295                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12296   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12297                      DAG.getIntPtrConstant(0, DL));
12298 }
12299
12300 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12301                                            SelectionDAG &DAG) const {
12302   assert(!Op.getSimpleValueType().isVector());
12303
12304   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12305     /*IsSigned=*/ true, /*IsReplace=*/ false);
12306   SDValue FIST = Vals.first, StackSlot = Vals.second;
12307   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12308   if (!FIST.getNode()) return Op;
12309
12310   if (StackSlot.getNode())
12311     // Load the result.
12312     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12313                        FIST, StackSlot, MachinePointerInfo(),
12314                        false, false, false, 0);
12315
12316   // The node is the result.
12317   return FIST;
12318 }
12319
12320 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12321                                            SelectionDAG &DAG) const {
12322   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12323     /*IsSigned=*/ false, /*IsReplace=*/ false);
12324   SDValue FIST = Vals.first, StackSlot = Vals.second;
12325   assert(FIST.getNode() && "Unexpected failure");
12326
12327   if (StackSlot.getNode())
12328     // Load the result.
12329     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12330                        FIST, StackSlot, MachinePointerInfo(),
12331                        false, false, false, 0);
12332
12333   // The node is the result.
12334   return FIST;
12335 }
12336
12337 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12338   SDLoc DL(Op);
12339   MVT VT = Op.getSimpleValueType();
12340   SDValue In = Op.getOperand(0);
12341   MVT SVT = In.getSimpleValueType();
12342
12343   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12344
12345   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12346                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12347                                  In, DAG.getUNDEF(SVT)));
12348 }
12349
12350 /// The only differences between FABS and FNEG are the mask and the logic op.
12351 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12352 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12353   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12354          "Wrong opcode for lowering FABS or FNEG.");
12355
12356   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12357
12358   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12359   // into an FNABS. We'll lower the FABS after that if it is still in use.
12360   if (IsFABS)
12361     for (SDNode *User : Op->uses())
12362       if (User->getOpcode() == ISD::FNEG)
12363         return Op;
12364
12365   SDValue Op0 = Op.getOperand(0);
12366   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12367
12368   SDLoc dl(Op);
12369   MVT VT = Op.getSimpleValueType();
12370   // Assume scalar op for initialization; update for vector if needed.
12371   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12372   // generate a 16-byte vector constant and logic op even for the scalar case.
12373   // Using a 16-byte mask allows folding the load of the mask with
12374   // the logic op, so it can save (~4 bytes) on code size.
12375   MVT EltVT = VT;
12376   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12377   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12378   // decide if we should generate a 16-byte constant mask when we only need 4 or
12379   // 8 bytes for the scalar case.
12380   if (VT.isVector()) {
12381     EltVT = VT.getVectorElementType();
12382     NumElts = VT.getVectorNumElements();
12383   }
12384
12385   unsigned EltBits = EltVT.getSizeInBits();
12386   LLVMContext *Context = DAG.getContext();
12387   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12388   APInt MaskElt =
12389     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12390   Constant *C = ConstantInt::get(*Context, MaskElt);
12391   C = ConstantVector::getSplat(NumElts, C);
12392   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12393   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12394   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12395   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12396                              MachinePointerInfo::getConstantPool(),
12397                              false, false, false, Alignment);
12398
12399   if (VT.isVector()) {
12400     // For a vector, cast operands to a vector type, perform the logic op,
12401     // and cast the result back to the original value type.
12402     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12403     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12404     SDValue Operand = IsFNABS ?
12405       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12406       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12407     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12408     return DAG.getNode(ISD::BITCAST, dl, VT,
12409                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12410   }
12411
12412   // If not vector, then scalar.
12413   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12414   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12415   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12416 }
12417
12418 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12419   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12420   LLVMContext *Context = DAG.getContext();
12421   SDValue Op0 = Op.getOperand(0);
12422   SDValue Op1 = Op.getOperand(1);
12423   SDLoc dl(Op);
12424   MVT VT = Op.getSimpleValueType();
12425   MVT SrcVT = Op1.getSimpleValueType();
12426
12427   // If second operand is smaller, extend it first.
12428   if (SrcVT.bitsLT(VT)) {
12429     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12430     SrcVT = VT;
12431   }
12432   // And if it is bigger, shrink it first.
12433   if (SrcVT.bitsGT(VT)) {
12434     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12435     SrcVT = VT;
12436   }
12437
12438   // At this point the operands and the result should have the same
12439   // type, and that won't be f80 since that is not custom lowered.
12440
12441   const fltSemantics &Sem =
12442       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12443   const unsigned SizeInBits = VT.getSizeInBits();
12444
12445   SmallVector<Constant *, 4> CV(
12446       VT == MVT::f64 ? 2 : 4,
12447       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12448
12449   // First, clear all bits but the sign bit from the second operand (sign).
12450   CV[0] = ConstantFP::get(*Context,
12451                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12452   Constant *C = ConstantVector::get(CV);
12453   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12454   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12455                               MachinePointerInfo::getConstantPool(),
12456                               false, false, false, 16);
12457   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12458
12459   // Next, clear the sign bit from the first operand (magnitude).
12460   // If it's a constant, we can clear it here.
12461   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12462     APFloat APF = Op0CN->getValueAPF();
12463     // If the magnitude is a positive zero, the sign bit alone is enough.
12464     if (APF.isPosZero())
12465       return SignBit;
12466     APF.clearSign();
12467     CV[0] = ConstantFP::get(*Context, APF);
12468   } else {
12469     CV[0] = ConstantFP::get(
12470         *Context,
12471         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12472   }
12473   C = ConstantVector::get(CV);
12474   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12475   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12476                             MachinePointerInfo::getConstantPool(),
12477                             false, false, false, 16);
12478   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12479   if (!isa<ConstantFPSDNode>(Op0))
12480     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12481
12482   // OR the magnitude value with the sign bit.
12483   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12484 }
12485
12486 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12487   SDValue N0 = Op.getOperand(0);
12488   SDLoc dl(Op);
12489   MVT VT = Op.getSimpleValueType();
12490
12491   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12492   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12493                                   DAG.getConstant(1, dl, VT));
12494   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12495 }
12496
12497 // Check whether an OR'd tree is PTEST-able.
12498 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12499                                       SelectionDAG &DAG) {
12500   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12501
12502   if (!Subtarget->hasSSE41())
12503     return SDValue();
12504
12505   if (!Op->hasOneUse())
12506     return SDValue();
12507
12508   SDNode *N = Op.getNode();
12509   SDLoc DL(N);
12510
12511   SmallVector<SDValue, 8> Opnds;
12512   DenseMap<SDValue, unsigned> VecInMap;
12513   SmallVector<SDValue, 8> VecIns;
12514   EVT VT = MVT::Other;
12515
12516   // Recognize a special case where a vector is casted into wide integer to
12517   // test all 0s.
12518   Opnds.push_back(N->getOperand(0));
12519   Opnds.push_back(N->getOperand(1));
12520
12521   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12522     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12523     // BFS traverse all OR'd operands.
12524     if (I->getOpcode() == ISD::OR) {
12525       Opnds.push_back(I->getOperand(0));
12526       Opnds.push_back(I->getOperand(1));
12527       // Re-evaluate the number of nodes to be traversed.
12528       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12529       continue;
12530     }
12531
12532     // Quit if a non-EXTRACT_VECTOR_ELT
12533     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12534       return SDValue();
12535
12536     // Quit if without a constant index.
12537     SDValue Idx = I->getOperand(1);
12538     if (!isa<ConstantSDNode>(Idx))
12539       return SDValue();
12540
12541     SDValue ExtractedFromVec = I->getOperand(0);
12542     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12543     if (M == VecInMap.end()) {
12544       VT = ExtractedFromVec.getValueType();
12545       // Quit if not 128/256-bit vector.
12546       if (!VT.is128BitVector() && !VT.is256BitVector())
12547         return SDValue();
12548       // Quit if not the same type.
12549       if (VecInMap.begin() != VecInMap.end() &&
12550           VT != VecInMap.begin()->first.getValueType())
12551         return SDValue();
12552       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12553       VecIns.push_back(ExtractedFromVec);
12554     }
12555     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12556   }
12557
12558   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12559          "Not extracted from 128-/256-bit vector.");
12560
12561   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12562
12563   for (DenseMap<SDValue, unsigned>::const_iterator
12564         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12565     // Quit if not all elements are used.
12566     if (I->second != FullMask)
12567       return SDValue();
12568   }
12569
12570   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12571
12572   // Cast all vectors into TestVT for PTEST.
12573   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12574     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12575
12576   // If more than one full vectors are evaluated, OR them first before PTEST.
12577   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12578     // Each iteration will OR 2 nodes and append the result until there is only
12579     // 1 node left, i.e. the final OR'd value of all vectors.
12580     SDValue LHS = VecIns[Slot];
12581     SDValue RHS = VecIns[Slot + 1];
12582     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12583   }
12584
12585   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12586                      VecIns.back(), VecIns.back());
12587 }
12588
12589 /// \brief return true if \c Op has a use that doesn't just read flags.
12590 static bool hasNonFlagsUse(SDValue Op) {
12591   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12592        ++UI) {
12593     SDNode *User = *UI;
12594     unsigned UOpNo = UI.getOperandNo();
12595     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12596       // Look pass truncate.
12597       UOpNo = User->use_begin().getOperandNo();
12598       User = *User->use_begin();
12599     }
12600
12601     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12602         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12603       return true;
12604   }
12605   return false;
12606 }
12607
12608 /// Emit nodes that will be selected as "test Op0,Op0", or something
12609 /// equivalent.
12610 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12611                                     SelectionDAG &DAG) const {
12612   if (Op.getValueType() == MVT::i1) {
12613     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12614     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12615                        DAG.getConstant(0, dl, MVT::i8));
12616   }
12617   // CF and OF aren't always set the way we want. Determine which
12618   // of these we need.
12619   bool NeedCF = false;
12620   bool NeedOF = false;
12621   switch (X86CC) {
12622   default: break;
12623   case X86::COND_A: case X86::COND_AE:
12624   case X86::COND_B: case X86::COND_BE:
12625     NeedCF = true;
12626     break;
12627   case X86::COND_G: case X86::COND_GE:
12628   case X86::COND_L: case X86::COND_LE:
12629   case X86::COND_O: case X86::COND_NO: {
12630     // Check if we really need to set the
12631     // Overflow flag. If NoSignedWrap is present
12632     // that is not actually needed.
12633     switch (Op->getOpcode()) {
12634     case ISD::ADD:
12635     case ISD::SUB:
12636     case ISD::MUL:
12637     case ISD::SHL: {
12638       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12639       if (BinNode->Flags.hasNoSignedWrap())
12640         break;
12641     }
12642     default:
12643       NeedOF = true;
12644       break;
12645     }
12646     break;
12647   }
12648   }
12649   // See if we can use the EFLAGS value from the operand instead of
12650   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12651   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12652   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12653     // Emit a CMP with 0, which is the TEST pattern.
12654     //if (Op.getValueType() == MVT::i1)
12655     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12656     //                     DAG.getConstant(0, MVT::i1));
12657     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12658                        DAG.getConstant(0, dl, Op.getValueType()));
12659   }
12660   unsigned Opcode = 0;
12661   unsigned NumOperands = 0;
12662
12663   // Truncate operations may prevent the merge of the SETCC instruction
12664   // and the arithmetic instruction before it. Attempt to truncate the operands
12665   // of the arithmetic instruction and use a reduced bit-width instruction.
12666   bool NeedTruncation = false;
12667   SDValue ArithOp = Op;
12668   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12669     SDValue Arith = Op->getOperand(0);
12670     // Both the trunc and the arithmetic op need to have one user each.
12671     if (Arith->hasOneUse())
12672       switch (Arith.getOpcode()) {
12673         default: break;
12674         case ISD::ADD:
12675         case ISD::SUB:
12676         case ISD::AND:
12677         case ISD::OR:
12678         case ISD::XOR: {
12679           NeedTruncation = true;
12680           ArithOp = Arith;
12681         }
12682       }
12683   }
12684
12685   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12686   // which may be the result of a CAST.  We use the variable 'Op', which is the
12687   // non-casted variable when we check for possible users.
12688   switch (ArithOp.getOpcode()) {
12689   case ISD::ADD:
12690     // Due to an isel shortcoming, be conservative if this add is likely to be
12691     // selected as part of a load-modify-store instruction. When the root node
12692     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12693     // uses of other nodes in the match, such as the ADD in this case. This
12694     // leads to the ADD being left around and reselected, with the result being
12695     // two adds in the output.  Alas, even if none our users are stores, that
12696     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12697     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12698     // climbing the DAG back to the root, and it doesn't seem to be worth the
12699     // effort.
12700     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12701          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12702       if (UI->getOpcode() != ISD::CopyToReg &&
12703           UI->getOpcode() != ISD::SETCC &&
12704           UI->getOpcode() != ISD::STORE)
12705         goto default_case;
12706
12707     if (ConstantSDNode *C =
12708         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12709       // An add of one will be selected as an INC.
12710       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12711         Opcode = X86ISD::INC;
12712         NumOperands = 1;
12713         break;
12714       }
12715
12716       // An add of negative one (subtract of one) will be selected as a DEC.
12717       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12718         Opcode = X86ISD::DEC;
12719         NumOperands = 1;
12720         break;
12721       }
12722     }
12723
12724     // Otherwise use a regular EFLAGS-setting add.
12725     Opcode = X86ISD::ADD;
12726     NumOperands = 2;
12727     break;
12728   case ISD::SHL:
12729   case ISD::SRL:
12730     // If we have a constant logical shift that's only used in a comparison
12731     // against zero turn it into an equivalent AND. This allows turning it into
12732     // a TEST instruction later.
12733     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12734         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12735       EVT VT = Op.getValueType();
12736       unsigned BitWidth = VT.getSizeInBits();
12737       unsigned ShAmt = Op->getConstantOperandVal(1);
12738       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12739         break;
12740       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12741                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12742                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12743       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12744         break;
12745       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12746                                 DAG.getConstant(Mask, dl, VT));
12747       DAG.ReplaceAllUsesWith(Op, New);
12748       Op = New;
12749     }
12750     break;
12751
12752   case ISD::AND:
12753     // If the primary and result isn't used, don't bother using X86ISD::AND,
12754     // because a TEST instruction will be better.
12755     if (!hasNonFlagsUse(Op))
12756       break;
12757     // FALL THROUGH
12758   case ISD::SUB:
12759   case ISD::OR:
12760   case ISD::XOR:
12761     // Due to the ISEL shortcoming noted above, be conservative if this op is
12762     // likely to be selected as part of a load-modify-store instruction.
12763     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12764            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12765       if (UI->getOpcode() == ISD::STORE)
12766         goto default_case;
12767
12768     // Otherwise use a regular EFLAGS-setting instruction.
12769     switch (ArithOp.getOpcode()) {
12770     default: llvm_unreachable("unexpected operator!");
12771     case ISD::SUB: Opcode = X86ISD::SUB; break;
12772     case ISD::XOR: Opcode = X86ISD::XOR; break;
12773     case ISD::AND: Opcode = X86ISD::AND; break;
12774     case ISD::OR: {
12775       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12776         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12777         if (EFLAGS.getNode())
12778           return EFLAGS;
12779       }
12780       Opcode = X86ISD::OR;
12781       break;
12782     }
12783     }
12784
12785     NumOperands = 2;
12786     break;
12787   case X86ISD::ADD:
12788   case X86ISD::SUB:
12789   case X86ISD::INC:
12790   case X86ISD::DEC:
12791   case X86ISD::OR:
12792   case X86ISD::XOR:
12793   case X86ISD::AND:
12794     return SDValue(Op.getNode(), 1);
12795   default:
12796   default_case:
12797     break;
12798   }
12799
12800   // If we found that truncation is beneficial, perform the truncation and
12801   // update 'Op'.
12802   if (NeedTruncation) {
12803     EVT VT = Op.getValueType();
12804     SDValue WideVal = Op->getOperand(0);
12805     EVT WideVT = WideVal.getValueType();
12806     unsigned ConvertedOp = 0;
12807     // Use a target machine opcode to prevent further DAGCombine
12808     // optimizations that may separate the arithmetic operations
12809     // from the setcc node.
12810     switch (WideVal.getOpcode()) {
12811       default: break;
12812       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12813       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12814       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12815       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12816       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12817     }
12818
12819     if (ConvertedOp) {
12820       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12821       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12822         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12823         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12824         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12825       }
12826     }
12827   }
12828
12829   if (Opcode == 0)
12830     // Emit a CMP with 0, which is the TEST pattern.
12831     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12832                        DAG.getConstant(0, dl, Op.getValueType()));
12833
12834   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12835   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12836
12837   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12838   DAG.ReplaceAllUsesWith(Op, New);
12839   return SDValue(New.getNode(), 1);
12840 }
12841
12842 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12843 /// equivalent.
12844 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12845                                    SDLoc dl, SelectionDAG &DAG) const {
12846   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12847     if (C->getAPIntValue() == 0)
12848       return EmitTest(Op0, X86CC, dl, DAG);
12849
12850      if (Op0.getValueType() == MVT::i1)
12851        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12852   }
12853
12854   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12855        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12856     // Do the comparison at i32 if it's smaller, besides the Atom case.
12857     // This avoids subregister aliasing issues. Keep the smaller reference
12858     // if we're optimizing for size, however, as that'll allow better folding
12859     // of memory operations.
12860     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12861         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12862             Attribute::MinSize) &&
12863         !Subtarget->isAtom()) {
12864       unsigned ExtendOp =
12865           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12866       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12867       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12868     }
12869     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12870     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12871     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12872                               Op0, Op1);
12873     return SDValue(Sub.getNode(), 1);
12874   }
12875   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12876 }
12877
12878 /// Convert a comparison if required by the subtarget.
12879 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12880                                                  SelectionDAG &DAG) const {
12881   // If the subtarget does not support the FUCOMI instruction, floating-point
12882   // comparisons have to be converted.
12883   if (Subtarget->hasCMov() ||
12884       Cmp.getOpcode() != X86ISD::CMP ||
12885       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12886       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12887     return Cmp;
12888
12889   // The instruction selector will select an FUCOM instruction instead of
12890   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12891   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12892   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12893   SDLoc dl(Cmp);
12894   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12895   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12896   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12897                             DAG.getConstant(8, dl, MVT::i8));
12898   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12899   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12900 }
12901
12902 /// The minimum architected relative accuracy is 2^-12. We need one
12903 /// Newton-Raphson step to have a good float result (24 bits of precision).
12904 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12905                                             DAGCombinerInfo &DCI,
12906                                             unsigned &RefinementSteps,
12907                                             bool &UseOneConstNR) const {
12908   // FIXME: We should use instruction latency models to calculate the cost of
12909   // each potential sequence, but this is very hard to do reliably because
12910   // at least Intel's Core* chips have variable timing based on the number of
12911   // significant digits in the divisor and/or sqrt operand.
12912   if (!Subtarget->useSqrtEst())
12913     return SDValue();
12914
12915   EVT VT = Op.getValueType();
12916
12917   // SSE1 has rsqrtss and rsqrtps.
12918   // TODO: Add support for AVX512 (v16f32).
12919   // It is likely not profitable to do this for f64 because a double-precision
12920   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12921   // instructions: convert to single, rsqrtss, convert back to double, refine
12922   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12923   // along with FMA, this could be a throughput win.
12924   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12925       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12926     RefinementSteps = 1;
12927     UseOneConstNR = false;
12928     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12929   }
12930   return SDValue();
12931 }
12932
12933 /// The minimum architected relative accuracy is 2^-12. We need one
12934 /// Newton-Raphson step to have a good float result (24 bits of precision).
12935 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12936                                             DAGCombinerInfo &DCI,
12937                                             unsigned &RefinementSteps) const {
12938   // FIXME: We should use instruction latency models to calculate the cost of
12939   // each potential sequence, but this is very hard to do reliably because
12940   // at least Intel's Core* chips have variable timing based on the number of
12941   // significant digits in the divisor.
12942   if (!Subtarget->useReciprocalEst())
12943     return SDValue();
12944
12945   EVT VT = Op.getValueType();
12946
12947   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12948   // TODO: Add support for AVX512 (v16f32).
12949   // It is likely not profitable to do this for f64 because a double-precision
12950   // reciprocal estimate with refinement on x86 prior to FMA requires
12951   // 15 instructions: convert to single, rcpss, convert back to double, refine
12952   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12953   // along with FMA, this could be a throughput win.
12954   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12955       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12956     RefinementSteps = ReciprocalEstimateRefinementSteps;
12957     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12958   }
12959   return SDValue();
12960 }
12961
12962 /// If we have at least two divisions that use the same divisor, convert to
12963 /// multplication by a reciprocal. This may need to be adjusted for a given
12964 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12965 /// This is because we still need one division to calculate the reciprocal and
12966 /// then we need two multiplies by that reciprocal as replacements for the
12967 /// original divisions.
12968 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12969   return NumUsers > 1;
12970 }
12971
12972 static bool isAllOnes(SDValue V) {
12973   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12974   return C && C->isAllOnesValue();
12975 }
12976
12977 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12978 /// if it's possible.
12979 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12980                                      SDLoc dl, SelectionDAG &DAG) const {
12981   SDValue Op0 = And.getOperand(0);
12982   SDValue Op1 = And.getOperand(1);
12983   if (Op0.getOpcode() == ISD::TRUNCATE)
12984     Op0 = Op0.getOperand(0);
12985   if (Op1.getOpcode() == ISD::TRUNCATE)
12986     Op1 = Op1.getOperand(0);
12987
12988   SDValue LHS, RHS;
12989   if (Op1.getOpcode() == ISD::SHL)
12990     std::swap(Op0, Op1);
12991   if (Op0.getOpcode() == ISD::SHL) {
12992     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12993       if (And00C->getZExtValue() == 1) {
12994         // If we looked past a truncate, check that it's only truncating away
12995         // known zeros.
12996         unsigned BitWidth = Op0.getValueSizeInBits();
12997         unsigned AndBitWidth = And.getValueSizeInBits();
12998         if (BitWidth > AndBitWidth) {
12999           APInt Zeros, Ones;
13000           DAG.computeKnownBits(Op0, Zeros, Ones);
13001           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13002             return SDValue();
13003         }
13004         LHS = Op1;
13005         RHS = Op0.getOperand(1);
13006       }
13007   } else if (Op1.getOpcode() == ISD::Constant) {
13008     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13009     uint64_t AndRHSVal = AndRHS->getZExtValue();
13010     SDValue AndLHS = Op0;
13011
13012     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13013       LHS = AndLHS.getOperand(0);
13014       RHS = AndLHS.getOperand(1);
13015     }
13016
13017     // Use BT if the immediate can't be encoded in a TEST instruction.
13018     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13019       LHS = AndLHS;
13020       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13021     }
13022   }
13023
13024   if (LHS.getNode()) {
13025     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13026     // instruction.  Since the shift amount is in-range-or-undefined, we know
13027     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13028     // the encoding for the i16 version is larger than the i32 version.
13029     // Also promote i16 to i32 for performance / code size reason.
13030     if (LHS.getValueType() == MVT::i8 ||
13031         LHS.getValueType() == MVT::i16)
13032       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13033
13034     // If the operand types disagree, extend the shift amount to match.  Since
13035     // BT ignores high bits (like shifts) we can use anyextend.
13036     if (LHS.getValueType() != RHS.getValueType())
13037       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13038
13039     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13040     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13041     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13042                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13043   }
13044
13045   return SDValue();
13046 }
13047
13048 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13049 /// mask CMPs.
13050 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13051                               SDValue &Op1) {
13052   unsigned SSECC;
13053   bool Swap = false;
13054
13055   // SSE Condition code mapping:
13056   //  0 - EQ
13057   //  1 - LT
13058   //  2 - LE
13059   //  3 - UNORD
13060   //  4 - NEQ
13061   //  5 - NLT
13062   //  6 - NLE
13063   //  7 - ORD
13064   switch (SetCCOpcode) {
13065   default: llvm_unreachable("Unexpected SETCC condition");
13066   case ISD::SETOEQ:
13067   case ISD::SETEQ:  SSECC = 0; break;
13068   case ISD::SETOGT:
13069   case ISD::SETGT:  Swap = true; // Fallthrough
13070   case ISD::SETLT:
13071   case ISD::SETOLT: SSECC = 1; break;
13072   case ISD::SETOGE:
13073   case ISD::SETGE:  Swap = true; // Fallthrough
13074   case ISD::SETLE:
13075   case ISD::SETOLE: SSECC = 2; break;
13076   case ISD::SETUO:  SSECC = 3; break;
13077   case ISD::SETUNE:
13078   case ISD::SETNE:  SSECC = 4; break;
13079   case ISD::SETULE: Swap = true; // Fallthrough
13080   case ISD::SETUGE: SSECC = 5; break;
13081   case ISD::SETULT: Swap = true; // Fallthrough
13082   case ISD::SETUGT: SSECC = 6; break;
13083   case ISD::SETO:   SSECC = 7; break;
13084   case ISD::SETUEQ:
13085   case ISD::SETONE: SSECC = 8; break;
13086   }
13087   if (Swap)
13088     std::swap(Op0, Op1);
13089
13090   return SSECC;
13091 }
13092
13093 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13094 // ones, and then concatenate the result back.
13095 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13096   MVT VT = Op.getSimpleValueType();
13097
13098   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13099          "Unsupported value type for operation");
13100
13101   unsigned NumElems = VT.getVectorNumElements();
13102   SDLoc dl(Op);
13103   SDValue CC = Op.getOperand(2);
13104
13105   // Extract the LHS vectors
13106   SDValue LHS = Op.getOperand(0);
13107   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13108   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13109
13110   // Extract the RHS vectors
13111   SDValue RHS = Op.getOperand(1);
13112   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13113   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13114
13115   // Issue the operation on the smaller types and concatenate the result back
13116   MVT EltVT = VT.getVectorElementType();
13117   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13118   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13119                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13120                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13121 }
13122
13123 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13124   SDValue Op0 = Op.getOperand(0);
13125   SDValue Op1 = Op.getOperand(1);
13126   SDValue CC = Op.getOperand(2);
13127   MVT VT = Op.getSimpleValueType();
13128   SDLoc dl(Op);
13129
13130   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13131          "Unexpected type for boolean compare operation");
13132   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13133   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13134                                DAG.getConstant(-1, dl, VT));
13135   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13136                                DAG.getConstant(-1, dl, VT));
13137   switch (SetCCOpcode) {
13138   default: llvm_unreachable("Unexpected SETCC condition");
13139   case ISD::SETNE:
13140     // (x != y) -> ~(x ^ y)
13141     return DAG.getNode(ISD::XOR, dl, VT,
13142                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13143                        DAG.getConstant(-1, dl, VT));
13144   case ISD::SETEQ:
13145     // (x == y) -> (x ^ y)
13146     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13147   case ISD::SETUGT:
13148   case ISD::SETGT:
13149     // (x > y) -> (x & ~y)
13150     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13151   case ISD::SETULT:
13152   case ISD::SETLT:
13153     // (x < y) -> (~x & y)
13154     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13155   case ISD::SETULE:
13156   case ISD::SETLE:
13157     // (x <= y) -> (~x | y)
13158     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13159   case ISD::SETUGE:
13160   case ISD::SETGE:
13161     // (x >=y) -> (x | ~y)
13162     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13163   }
13164 }
13165
13166 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13167                                      const X86Subtarget *Subtarget) {
13168   SDValue Op0 = Op.getOperand(0);
13169   SDValue Op1 = Op.getOperand(1);
13170   SDValue CC = Op.getOperand(2);
13171   MVT VT = Op.getSimpleValueType();
13172   SDLoc dl(Op);
13173
13174   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13175          Op.getValueType().getScalarType() == MVT::i1 &&
13176          "Cannot set masked compare for this operation");
13177
13178   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13179   unsigned  Opc = 0;
13180   bool Unsigned = false;
13181   bool Swap = false;
13182   unsigned SSECC;
13183   switch (SetCCOpcode) {
13184   default: llvm_unreachable("Unexpected SETCC condition");
13185   case ISD::SETNE:  SSECC = 4; break;
13186   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13187   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13188   case ISD::SETLT:  Swap = true; //fall-through
13189   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13190   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13191   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13192   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13193   case ISD::SETULE: Unsigned = true; //fall-through
13194   case ISD::SETLE:  SSECC = 2; break;
13195   }
13196
13197   if (Swap)
13198     std::swap(Op0, Op1);
13199   if (Opc)
13200     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13201   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13202   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13203                      DAG.getConstant(SSECC, dl, MVT::i8));
13204 }
13205
13206 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13207 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13208 /// return an empty value.
13209 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13210 {
13211   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13212   if (!BV)
13213     return SDValue();
13214
13215   MVT VT = Op1.getSimpleValueType();
13216   MVT EVT = VT.getVectorElementType();
13217   unsigned n = VT.getVectorNumElements();
13218   SmallVector<SDValue, 8> ULTOp1;
13219
13220   for (unsigned i = 0; i < n; ++i) {
13221     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13222     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13223       return SDValue();
13224
13225     // Avoid underflow.
13226     APInt Val = Elt->getAPIntValue();
13227     if (Val == 0)
13228       return SDValue();
13229
13230     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13231   }
13232
13233   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13234 }
13235
13236 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13237                            SelectionDAG &DAG) {
13238   SDValue Op0 = Op.getOperand(0);
13239   SDValue Op1 = Op.getOperand(1);
13240   SDValue CC = Op.getOperand(2);
13241   MVT VT = Op.getSimpleValueType();
13242   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13243   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13244   SDLoc dl(Op);
13245
13246   if (isFP) {
13247 #ifndef NDEBUG
13248     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13249     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13250 #endif
13251
13252     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13253     unsigned Opc = X86ISD::CMPP;
13254     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13255       assert(VT.getVectorNumElements() <= 16);
13256       Opc = X86ISD::CMPM;
13257     }
13258     // In the two special cases we can't handle, emit two comparisons.
13259     if (SSECC == 8) {
13260       unsigned CC0, CC1;
13261       unsigned CombineOpc;
13262       if (SetCCOpcode == ISD::SETUEQ) {
13263         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13264       } else {
13265         assert(SetCCOpcode == ISD::SETONE);
13266         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13267       }
13268
13269       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13270                                  DAG.getConstant(CC0, dl, MVT::i8));
13271       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13272                                  DAG.getConstant(CC1, dl, MVT::i8));
13273       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13274     }
13275     // Handle all other FP comparisons here.
13276     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13277                        DAG.getConstant(SSECC, dl, MVT::i8));
13278   }
13279
13280   // Break 256-bit integer vector compare into smaller ones.
13281   if (VT.is256BitVector() && !Subtarget->hasInt256())
13282     return Lower256IntVSETCC(Op, DAG);
13283
13284   EVT OpVT = Op1.getValueType();
13285   if (OpVT.getVectorElementType() == MVT::i1)
13286     return LowerBoolVSETCC_AVX512(Op, DAG);
13287
13288   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13289   if (Subtarget->hasAVX512()) {
13290     if (Op1.getValueType().is512BitVector() ||
13291         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13292         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13293       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13294
13295     // In AVX-512 architecture setcc returns mask with i1 elements,
13296     // But there is no compare instruction for i8 and i16 elements in KNL.
13297     // We are not talking about 512-bit operands in this case, these
13298     // types are illegal.
13299     if (MaskResult &&
13300         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13301          OpVT.getVectorElementType().getSizeInBits() >= 8))
13302       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13303                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13304   }
13305
13306   // We are handling one of the integer comparisons here.  Since SSE only has
13307   // GT and EQ comparisons for integer, swapping operands and multiple
13308   // operations may be required for some comparisons.
13309   unsigned Opc;
13310   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13311   bool Subus = false;
13312
13313   switch (SetCCOpcode) {
13314   default: llvm_unreachable("Unexpected SETCC condition");
13315   case ISD::SETNE:  Invert = true;
13316   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13317   case ISD::SETLT:  Swap = true;
13318   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13319   case ISD::SETGE:  Swap = true;
13320   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13321                     Invert = true; break;
13322   case ISD::SETULT: Swap = true;
13323   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13324                     FlipSigns = true; break;
13325   case ISD::SETUGE: Swap = true;
13326   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13327                     FlipSigns = true; Invert = true; break;
13328   }
13329
13330   // Special case: Use min/max operations for SETULE/SETUGE
13331   MVT VET = VT.getVectorElementType();
13332   bool hasMinMax =
13333        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13334     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13335
13336   if (hasMinMax) {
13337     switch (SetCCOpcode) {
13338     default: break;
13339     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13340     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13341     }
13342
13343     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13344   }
13345
13346   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13347   if (!MinMax && hasSubus) {
13348     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13349     // Op0 u<= Op1:
13350     //   t = psubus Op0, Op1
13351     //   pcmpeq t, <0..0>
13352     switch (SetCCOpcode) {
13353     default: break;
13354     case ISD::SETULT: {
13355       // If the comparison is against a constant we can turn this into a
13356       // setule.  With psubus, setule does not require a swap.  This is
13357       // beneficial because the constant in the register is no longer
13358       // destructed as the destination so it can be hoisted out of a loop.
13359       // Only do this pre-AVX since vpcmp* is no longer destructive.
13360       if (Subtarget->hasAVX())
13361         break;
13362       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13363       if (ULEOp1.getNode()) {
13364         Op1 = ULEOp1;
13365         Subus = true; Invert = false; Swap = false;
13366       }
13367       break;
13368     }
13369     // Psubus is better than flip-sign because it requires no inversion.
13370     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13371     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13372     }
13373
13374     if (Subus) {
13375       Opc = X86ISD::SUBUS;
13376       FlipSigns = false;
13377     }
13378   }
13379
13380   if (Swap)
13381     std::swap(Op0, Op1);
13382
13383   // Check that the operation in question is available (most are plain SSE2,
13384   // but PCMPGTQ and PCMPEQQ have different requirements).
13385   if (VT == MVT::v2i64) {
13386     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13387       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13388
13389       // First cast everything to the right type.
13390       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13391       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13392
13393       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13394       // bits of the inputs before performing those operations. The lower
13395       // compare is always unsigned.
13396       SDValue SB;
13397       if (FlipSigns) {
13398         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13399       } else {
13400         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13401         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13402         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13403                          Sign, Zero, Sign, Zero);
13404       }
13405       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13406       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13407
13408       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13409       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13410       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13411
13412       // Create masks for only the low parts/high parts of the 64 bit integers.
13413       static const int MaskHi[] = { 1, 1, 3, 3 };
13414       static const int MaskLo[] = { 0, 0, 2, 2 };
13415       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13416       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13417       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13418
13419       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13420       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13421
13422       if (Invert)
13423         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13424
13425       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13426     }
13427
13428     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13429       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13430       // pcmpeqd + pshufd + pand.
13431       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13432
13433       // First cast everything to the right type.
13434       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13435       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13436
13437       // Do the compare.
13438       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13439
13440       // Make sure the lower and upper halves are both all-ones.
13441       static const int Mask[] = { 1, 0, 3, 2 };
13442       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13443       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13444
13445       if (Invert)
13446         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13447
13448       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13449     }
13450   }
13451
13452   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13453   // bits of the inputs before performing those operations.
13454   if (FlipSigns) {
13455     EVT EltVT = VT.getVectorElementType();
13456     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13457                                  VT);
13458     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13459     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13460   }
13461
13462   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13463
13464   // If the logical-not of the result is required, perform that now.
13465   if (Invert)
13466     Result = DAG.getNOT(dl, Result, VT);
13467
13468   if (MinMax)
13469     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13470
13471   if (Subus)
13472     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13473                          getZeroVector(VT, Subtarget, DAG, dl));
13474
13475   return Result;
13476 }
13477
13478 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13479
13480   MVT VT = Op.getSimpleValueType();
13481
13482   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13483
13484   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13485          && "SetCC type must be 8-bit or 1-bit integer");
13486   SDValue Op0 = Op.getOperand(0);
13487   SDValue Op1 = Op.getOperand(1);
13488   SDLoc dl(Op);
13489   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13490
13491   // Optimize to BT if possible.
13492   // Lower (X & (1 << N)) == 0 to BT(X, N).
13493   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13494   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13495   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13496       Op1.getOpcode() == ISD::Constant &&
13497       cast<ConstantSDNode>(Op1)->isNullValue() &&
13498       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13499     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13500     if (NewSetCC.getNode()) {
13501       if (VT == MVT::i1)
13502         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13503       return NewSetCC;
13504     }
13505   }
13506
13507   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13508   // these.
13509   if (Op1.getOpcode() == ISD::Constant &&
13510       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13511        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13512       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13513
13514     // If the input is a setcc, then reuse the input setcc or use a new one with
13515     // the inverted condition.
13516     if (Op0.getOpcode() == X86ISD::SETCC) {
13517       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13518       bool Invert = (CC == ISD::SETNE) ^
13519         cast<ConstantSDNode>(Op1)->isNullValue();
13520       if (!Invert)
13521         return Op0;
13522
13523       CCode = X86::GetOppositeBranchCondition(CCode);
13524       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13525                                   DAG.getConstant(CCode, dl, MVT::i8),
13526                                   Op0.getOperand(1));
13527       if (VT == MVT::i1)
13528         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13529       return SetCC;
13530     }
13531   }
13532   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13533       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13534       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13535
13536     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13537     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13538   }
13539
13540   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13541   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13542   if (X86CC == X86::COND_INVALID)
13543     return SDValue();
13544
13545   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13546   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13547   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13548                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13549   if (VT == MVT::i1)
13550     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13551   return SetCC;
13552 }
13553
13554 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13555 static bool isX86LogicalCmp(SDValue Op) {
13556   unsigned Opc = Op.getNode()->getOpcode();
13557   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13558       Opc == X86ISD::SAHF)
13559     return true;
13560   if (Op.getResNo() == 1 &&
13561       (Opc == X86ISD::ADD ||
13562        Opc == X86ISD::SUB ||
13563        Opc == X86ISD::ADC ||
13564        Opc == X86ISD::SBB ||
13565        Opc == X86ISD::SMUL ||
13566        Opc == X86ISD::UMUL ||
13567        Opc == X86ISD::INC ||
13568        Opc == X86ISD::DEC ||
13569        Opc == X86ISD::OR ||
13570        Opc == X86ISD::XOR ||
13571        Opc == X86ISD::AND))
13572     return true;
13573
13574   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13575     return true;
13576
13577   return false;
13578 }
13579
13580 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13581   if (V.getOpcode() != ISD::TRUNCATE)
13582     return false;
13583
13584   SDValue VOp0 = V.getOperand(0);
13585   unsigned InBits = VOp0.getValueSizeInBits();
13586   unsigned Bits = V.getValueSizeInBits();
13587   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13588 }
13589
13590 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13591   bool addTest = true;
13592   SDValue Cond  = Op.getOperand(0);
13593   SDValue Op1 = Op.getOperand(1);
13594   SDValue Op2 = Op.getOperand(2);
13595   SDLoc DL(Op);
13596   EVT VT = Op1.getValueType();
13597   SDValue CC;
13598
13599   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13600   // are available or VBLENDV if AVX is available.
13601   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13602   if (Cond.getOpcode() == ISD::SETCC &&
13603       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13604        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13605       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13606     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13607     int SSECC = translateX86FSETCC(
13608         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13609
13610     if (SSECC != 8) {
13611       if (Subtarget->hasAVX512()) {
13612         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13613                                   DAG.getConstant(SSECC, DL, MVT::i8));
13614         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13615       }
13616
13617       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13618                                 DAG.getConstant(SSECC, DL, MVT::i8));
13619
13620       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13621       // of 3 logic instructions for size savings and potentially speed.
13622       // Unfortunately, there is no scalar form of VBLENDV.
13623
13624       // If either operand is a constant, don't try this. We can expect to
13625       // optimize away at least one of the logic instructions later in that
13626       // case, so that sequence would be faster than a variable blend.
13627
13628       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13629       // uses XMM0 as the selection register. That may need just as many
13630       // instructions as the AND/ANDN/OR sequence due to register moves, so
13631       // don't bother.
13632
13633       if (Subtarget->hasAVX() &&
13634           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13635
13636         // Convert to vectors, do a VSELECT, and convert back to scalar.
13637         // All of the conversions should be optimized away.
13638
13639         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13640         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13641         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13642         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13643
13644         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13645         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13646
13647         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13648
13649         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13650                            VSel, DAG.getIntPtrConstant(0, DL));
13651       }
13652       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13653       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13654       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13655     }
13656   }
13657
13658     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13659       SDValue Op1Scalar;
13660       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13661         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13662       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13663         Op1Scalar = Op1.getOperand(0);
13664       SDValue Op2Scalar;
13665       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13666         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13667       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13668         Op2Scalar = Op2.getOperand(0);
13669       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13670         SDValue newSelect = DAG.getNode(ISD::SELECT, DL, 
13671                                         Op1Scalar.getValueType(),
13672                                         Cond, Op1Scalar, Op2Scalar);
13673         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13674           return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13675         SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13676         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13677                            DAG.getIntPtrConstant(0, DL));
13678     }
13679   }
13680
13681   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13682     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13683     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13684                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13685     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13686                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13687     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13688                                     Cond, Op1, Op2);
13689     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13690   }
13691
13692   if (Cond.getOpcode() == ISD::SETCC) {
13693     SDValue NewCond = LowerSETCC(Cond, DAG);
13694     if (NewCond.getNode())
13695       Cond = NewCond;
13696   }
13697
13698   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13699   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13700   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13701   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13702   if (Cond.getOpcode() == X86ISD::SETCC &&
13703       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13704       isZero(Cond.getOperand(1).getOperand(1))) {
13705     SDValue Cmp = Cond.getOperand(1);
13706
13707     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13708
13709     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13710         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13711       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13712
13713       SDValue CmpOp0 = Cmp.getOperand(0);
13714       // Apply further optimizations for special cases
13715       // (select (x != 0), -1, 0) -> neg & sbb
13716       // (select (x == 0), 0, -1) -> neg & sbb
13717       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13718         if (YC->isNullValue() &&
13719             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13720           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13721           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13722                                     DAG.getConstant(0, DL,
13723                                                     CmpOp0.getValueType()),
13724                                     CmpOp0);
13725           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13726                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13727                                     SDValue(Neg.getNode(), 1));
13728           return Res;
13729         }
13730
13731       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13732                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13733       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13734
13735       SDValue Res =   // Res = 0 or -1.
13736         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13737                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13738
13739       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13740         Res = DAG.getNOT(DL, Res, Res.getValueType());
13741
13742       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13743       if (!N2C || !N2C->isNullValue())
13744         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13745       return Res;
13746     }
13747   }
13748
13749   // Look past (and (setcc_carry (cmp ...)), 1).
13750   if (Cond.getOpcode() == ISD::AND &&
13751       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13752     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13753     if (C && C->getAPIntValue() == 1)
13754       Cond = Cond.getOperand(0);
13755   }
13756
13757   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13758   // setting operand in place of the X86ISD::SETCC.
13759   unsigned CondOpcode = Cond.getOpcode();
13760   if (CondOpcode == X86ISD::SETCC ||
13761       CondOpcode == X86ISD::SETCC_CARRY) {
13762     CC = Cond.getOperand(0);
13763
13764     SDValue Cmp = Cond.getOperand(1);
13765     unsigned Opc = Cmp.getOpcode();
13766     MVT VT = Op.getSimpleValueType();
13767
13768     bool IllegalFPCMov = false;
13769     if (VT.isFloatingPoint() && !VT.isVector() &&
13770         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13771       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13772
13773     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13774         Opc == X86ISD::BT) { // FIXME
13775       Cond = Cmp;
13776       addTest = false;
13777     }
13778   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13779              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13780              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13781               Cond.getOperand(0).getValueType() != MVT::i8)) {
13782     SDValue LHS = Cond.getOperand(0);
13783     SDValue RHS = Cond.getOperand(1);
13784     unsigned X86Opcode;
13785     unsigned X86Cond;
13786     SDVTList VTs;
13787     switch (CondOpcode) {
13788     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13789     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13790     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13791     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13792     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13793     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13794     default: llvm_unreachable("unexpected overflowing operator");
13795     }
13796     if (CondOpcode == ISD::UMULO)
13797       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13798                           MVT::i32);
13799     else
13800       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13801
13802     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13803
13804     if (CondOpcode == ISD::UMULO)
13805       Cond = X86Op.getValue(2);
13806     else
13807       Cond = X86Op.getValue(1);
13808
13809     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13810     addTest = false;
13811   }
13812
13813   if (addTest) {
13814     // Look pass the truncate if the high bits are known zero.
13815     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13816         Cond = Cond.getOperand(0);
13817
13818     // We know the result of AND is compared against zero. Try to match
13819     // it to BT.
13820     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13821       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13822       if (NewSetCC.getNode()) {
13823         CC = NewSetCC.getOperand(0);
13824         Cond = NewSetCC.getOperand(1);
13825         addTest = false;
13826       }
13827     }
13828   }
13829
13830   if (addTest) {
13831     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13832     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13833   }
13834
13835   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13836   // a <  b ?  0 : -1 -> RES = setcc_carry
13837   // a >= b ? -1 :  0 -> RES = setcc_carry
13838   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13839   if (Cond.getOpcode() == X86ISD::SUB) {
13840     Cond = ConvertCmpIfNecessary(Cond, DAG);
13841     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13842
13843     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13844         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13845       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13846                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13847                                 Cond);
13848       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13849         return DAG.getNOT(DL, Res, Res.getValueType());
13850       return Res;
13851     }
13852   }
13853
13854   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13855   // widen the cmov and push the truncate through. This avoids introducing a new
13856   // branch during isel and doesn't add any extensions.
13857   if (Op.getValueType() == MVT::i8 &&
13858       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13859     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13860     if (T1.getValueType() == T2.getValueType() &&
13861         // Blacklist CopyFromReg to avoid partial register stalls.
13862         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13863       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13864       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13865       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13866     }
13867   }
13868
13869   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13870   // condition is true.
13871   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13872   SDValue Ops[] = { Op2, Op1, CC, Cond };
13873   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13874 }
13875
13876 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13877                                        SelectionDAG &DAG) {
13878   MVT VT = Op->getSimpleValueType(0);
13879   SDValue In = Op->getOperand(0);
13880   MVT InVT = In.getSimpleValueType();
13881   MVT VTElt = VT.getVectorElementType();
13882   MVT InVTElt = InVT.getVectorElementType();
13883   SDLoc dl(Op);
13884
13885   // SKX processor
13886   if ((InVTElt == MVT::i1) &&
13887       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13888         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13889
13890        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13891         VTElt.getSizeInBits() <= 16)) ||
13892
13893        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13894         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13895
13896        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13897         VTElt.getSizeInBits() >= 32))))
13898     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13899
13900   unsigned int NumElts = VT.getVectorNumElements();
13901
13902   if (NumElts != 8 && NumElts != 16)
13903     return SDValue();
13904
13905   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13906     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13907       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13908     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13909   }
13910
13911   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13912   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13913   SDValue NegOne =
13914    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13915                    ExtVT);
13916   SDValue Zero =
13917    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13918
13919   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13920   if (VT.is512BitVector())
13921     return V;
13922   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13923 }
13924
13925 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
13926                                              const X86Subtarget *Subtarget,
13927                                              SelectionDAG &DAG) {
13928   SDValue In = Op->getOperand(0);
13929   MVT VT = Op->getSimpleValueType(0);
13930   MVT InVT = In.getSimpleValueType();
13931   assert(VT.getSizeInBits() == InVT.getSizeInBits());
13932
13933   MVT InSVT = InVT.getScalarType();
13934   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
13935
13936   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13937     return SDValue();
13938   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
13939     return SDValue();
13940
13941   SDLoc dl(Op);
13942
13943   // SSE41 targets can use the pmovsx* instructions directly.
13944   if (Subtarget->hasSSE41())
13945     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13946
13947   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
13948   SDValue Curr = In;
13949   MVT CurrVT = InVT;
13950
13951   // As SRAI is only available on i16/i32 types, we expand only up to i32
13952   // and handle i64 separately.
13953   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
13954     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
13955     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
13956     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
13957     Curr = DAG.getNode(ISD::BITCAST, dl, CurrVT, Curr);
13958   }
13959
13960   SDValue SignExt = Curr;
13961   if (CurrVT != InVT) {
13962     unsigned SignExtShift =
13963         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
13964     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13965                           DAG.getConstant(SignExtShift, dl, MVT::i8));
13966   }
13967
13968   if (CurrVT == VT)
13969     return SignExt;
13970
13971   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
13972     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13973                                DAG.getConstant(31, dl, MVT::i8));
13974     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
13975     return DAG.getNode(ISD::BITCAST, dl, VT, Ext);
13976   }
13977
13978   return SDValue();
13979 }
13980
13981 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13982                                 SelectionDAG &DAG) {
13983   MVT VT = Op->getSimpleValueType(0);
13984   SDValue In = Op->getOperand(0);
13985   MVT InVT = In.getSimpleValueType();
13986   SDLoc dl(Op);
13987
13988   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13989     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13990
13991   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13992       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13993       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13994     return SDValue();
13995
13996   if (Subtarget->hasInt256())
13997     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13998
13999   // Optimize vectors in AVX mode
14000   // Sign extend  v8i16 to v8i32 and
14001   //              v4i32 to v4i64
14002   //
14003   // Divide input vector into two parts
14004   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14005   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14006   // concat the vectors to original VT
14007
14008   unsigned NumElems = InVT.getVectorNumElements();
14009   SDValue Undef = DAG.getUNDEF(InVT);
14010
14011   SmallVector<int,8> ShufMask1(NumElems, -1);
14012   for (unsigned i = 0; i != NumElems/2; ++i)
14013     ShufMask1[i] = i;
14014
14015   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14016
14017   SmallVector<int,8> ShufMask2(NumElems, -1);
14018   for (unsigned i = 0; i != NumElems/2; ++i)
14019     ShufMask2[i] = i + NumElems/2;
14020
14021   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14022
14023   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14024                                 VT.getVectorNumElements()/2);
14025
14026   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14027   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14028
14029   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14030 }
14031
14032 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14033 // may emit an illegal shuffle but the expansion is still better than scalar
14034 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14035 // we'll emit a shuffle and a arithmetic shift.
14036 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14037 // TODO: It is possible to support ZExt by zeroing the undef values during
14038 // the shuffle phase or after the shuffle.
14039 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14040                                  SelectionDAG &DAG) {
14041   MVT RegVT = Op.getSimpleValueType();
14042   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14043   assert(RegVT.isInteger() &&
14044          "We only custom lower integer vector sext loads.");
14045
14046   // Nothing useful we can do without SSE2 shuffles.
14047   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14048
14049   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14050   SDLoc dl(Ld);
14051   EVT MemVT = Ld->getMemoryVT();
14052   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14053   unsigned RegSz = RegVT.getSizeInBits();
14054
14055   ISD::LoadExtType Ext = Ld->getExtensionType();
14056
14057   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14058          && "Only anyext and sext are currently implemented.");
14059   assert(MemVT != RegVT && "Cannot extend to the same type");
14060   assert(MemVT.isVector() && "Must load a vector from memory");
14061
14062   unsigned NumElems = RegVT.getVectorNumElements();
14063   unsigned MemSz = MemVT.getSizeInBits();
14064   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14065
14066   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14067     // The only way in which we have a legal 256-bit vector result but not the
14068     // integer 256-bit operations needed to directly lower a sextload is if we
14069     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14070     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14071     // correctly legalized. We do this late to allow the canonical form of
14072     // sextload to persist throughout the rest of the DAG combiner -- it wants
14073     // to fold together any extensions it can, and so will fuse a sign_extend
14074     // of an sextload into a sextload targeting a wider value.
14075     SDValue Load;
14076     if (MemSz == 128) {
14077       // Just switch this to a normal load.
14078       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14079                                        "it must be a legal 128-bit vector "
14080                                        "type!");
14081       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14082                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14083                   Ld->isInvariant(), Ld->getAlignment());
14084     } else {
14085       assert(MemSz < 128 &&
14086              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14087       // Do an sext load to a 128-bit vector type. We want to use the same
14088       // number of elements, but elements half as wide. This will end up being
14089       // recursively lowered by this routine, but will succeed as we definitely
14090       // have all the necessary features if we're using AVX1.
14091       EVT HalfEltVT =
14092           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14093       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14094       Load =
14095           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14096                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14097                          Ld->isNonTemporal(), Ld->isInvariant(),
14098                          Ld->getAlignment());
14099     }
14100
14101     // Replace chain users with the new chain.
14102     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14103     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14104
14105     // Finally, do a normal sign-extend to the desired register.
14106     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14107   }
14108
14109   // All sizes must be a power of two.
14110   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14111          "Non-power-of-two elements are not custom lowered!");
14112
14113   // Attempt to load the original value using scalar loads.
14114   // Find the largest scalar type that divides the total loaded size.
14115   MVT SclrLoadTy = MVT::i8;
14116   for (MVT Tp : MVT::integer_valuetypes()) {
14117     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14118       SclrLoadTy = Tp;
14119     }
14120   }
14121
14122   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14123   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14124       (64 <= MemSz))
14125     SclrLoadTy = MVT::f64;
14126
14127   // Calculate the number of scalar loads that we need to perform
14128   // in order to load our vector from memory.
14129   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14130
14131   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14132          "Can only lower sext loads with a single scalar load!");
14133
14134   unsigned loadRegZize = RegSz;
14135   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14136     loadRegZize = 128;
14137
14138   // Represent our vector as a sequence of elements which are the
14139   // largest scalar that we can load.
14140   EVT LoadUnitVecVT = EVT::getVectorVT(
14141       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14142
14143   // Represent the data using the same element type that is stored in
14144   // memory. In practice, we ''widen'' MemVT.
14145   EVT WideVecVT =
14146       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14147                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14148
14149   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14150          "Invalid vector type");
14151
14152   // We can't shuffle using an illegal type.
14153   assert(TLI.isTypeLegal(WideVecVT) &&
14154          "We only lower types that form legal widened vector types");
14155
14156   SmallVector<SDValue, 8> Chains;
14157   SDValue Ptr = Ld->getBasePtr();
14158   SDValue Increment =
14159       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14160   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14161
14162   for (unsigned i = 0; i < NumLoads; ++i) {
14163     // Perform a single load.
14164     SDValue ScalarLoad =
14165         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14166                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14167                     Ld->getAlignment());
14168     Chains.push_back(ScalarLoad.getValue(1));
14169     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14170     // another round of DAGCombining.
14171     if (i == 0)
14172       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14173     else
14174       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14175                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14176
14177     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14178   }
14179
14180   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14181
14182   // Bitcast the loaded value to a vector of the original element type, in
14183   // the size of the target vector type.
14184   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14185   unsigned SizeRatio = RegSz / MemSz;
14186
14187   if (Ext == ISD::SEXTLOAD) {
14188     // If we have SSE4.1, we can directly emit a VSEXT node.
14189     if (Subtarget->hasSSE41()) {
14190       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14191       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14192       return Sext;
14193     }
14194
14195     // Otherwise we'll shuffle the small elements in the high bits of the
14196     // larger type and perform an arithmetic shift. If the shift is not legal
14197     // it's better to scalarize.
14198     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14199            "We can't implement a sext load without an arithmetic right shift!");
14200
14201     // Redistribute the loaded elements into the different locations.
14202     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14203     for (unsigned i = 0; i != NumElems; ++i)
14204       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14205
14206     SDValue Shuff = DAG.getVectorShuffle(
14207         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14208
14209     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14210
14211     // Build the arithmetic shift.
14212     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14213                    MemVT.getVectorElementType().getSizeInBits();
14214     Shuff =
14215         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14216                     DAG.getConstant(Amt, dl, RegVT));
14217
14218     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14219     return Shuff;
14220   }
14221
14222   // Redistribute the loaded elements into the different locations.
14223   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14224   for (unsigned i = 0; i != NumElems; ++i)
14225     ShuffleVec[i * SizeRatio] = i;
14226
14227   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14228                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14229
14230   // Bitcast to the requested type.
14231   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14232   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14233   return Shuff;
14234 }
14235
14236 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14237 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14238 // from the AND / OR.
14239 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14240   Opc = Op.getOpcode();
14241   if (Opc != ISD::OR && Opc != ISD::AND)
14242     return false;
14243   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14244           Op.getOperand(0).hasOneUse() &&
14245           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14246           Op.getOperand(1).hasOneUse());
14247 }
14248
14249 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14250 // 1 and that the SETCC node has a single use.
14251 static bool isXor1OfSetCC(SDValue Op) {
14252   if (Op.getOpcode() != ISD::XOR)
14253     return false;
14254   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14255   if (N1C && N1C->getAPIntValue() == 1) {
14256     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14257       Op.getOperand(0).hasOneUse();
14258   }
14259   return false;
14260 }
14261
14262 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14263   bool addTest = true;
14264   SDValue Chain = Op.getOperand(0);
14265   SDValue Cond  = Op.getOperand(1);
14266   SDValue Dest  = Op.getOperand(2);
14267   SDLoc dl(Op);
14268   SDValue CC;
14269   bool Inverted = false;
14270
14271   if (Cond.getOpcode() == ISD::SETCC) {
14272     // Check for setcc([su]{add,sub,mul}o == 0).
14273     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14274         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14275         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14276         Cond.getOperand(0).getResNo() == 1 &&
14277         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14278          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14279          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14280          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14281          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14282          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14283       Inverted = true;
14284       Cond = Cond.getOperand(0);
14285     } else {
14286       SDValue NewCond = LowerSETCC(Cond, DAG);
14287       if (NewCond.getNode())
14288         Cond = NewCond;
14289     }
14290   }
14291 #if 0
14292   // FIXME: LowerXALUO doesn't handle these!!
14293   else if (Cond.getOpcode() == X86ISD::ADD  ||
14294            Cond.getOpcode() == X86ISD::SUB  ||
14295            Cond.getOpcode() == X86ISD::SMUL ||
14296            Cond.getOpcode() == X86ISD::UMUL)
14297     Cond = LowerXALUO(Cond, DAG);
14298 #endif
14299
14300   // Look pass (and (setcc_carry (cmp ...)), 1).
14301   if (Cond.getOpcode() == ISD::AND &&
14302       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14303     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14304     if (C && C->getAPIntValue() == 1)
14305       Cond = Cond.getOperand(0);
14306   }
14307
14308   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14309   // setting operand in place of the X86ISD::SETCC.
14310   unsigned CondOpcode = Cond.getOpcode();
14311   if (CondOpcode == X86ISD::SETCC ||
14312       CondOpcode == X86ISD::SETCC_CARRY) {
14313     CC = Cond.getOperand(0);
14314
14315     SDValue Cmp = Cond.getOperand(1);
14316     unsigned Opc = Cmp.getOpcode();
14317     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14318     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14319       Cond = Cmp;
14320       addTest = false;
14321     } else {
14322       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14323       default: break;
14324       case X86::COND_O:
14325       case X86::COND_B:
14326         // These can only come from an arithmetic instruction with overflow,
14327         // e.g. SADDO, UADDO.
14328         Cond = Cond.getNode()->getOperand(1);
14329         addTest = false;
14330         break;
14331       }
14332     }
14333   }
14334   CondOpcode = Cond.getOpcode();
14335   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14336       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14337       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14338        Cond.getOperand(0).getValueType() != MVT::i8)) {
14339     SDValue LHS = Cond.getOperand(0);
14340     SDValue RHS = Cond.getOperand(1);
14341     unsigned X86Opcode;
14342     unsigned X86Cond;
14343     SDVTList VTs;
14344     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14345     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14346     // X86ISD::INC).
14347     switch (CondOpcode) {
14348     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14349     case ISD::SADDO:
14350       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14351         if (C->isOne()) {
14352           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14353           break;
14354         }
14355       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14356     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14357     case ISD::SSUBO:
14358       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14359         if (C->isOne()) {
14360           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14361           break;
14362         }
14363       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14364     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14365     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14366     default: llvm_unreachable("unexpected overflowing operator");
14367     }
14368     if (Inverted)
14369       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14370     if (CondOpcode == ISD::UMULO)
14371       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14372                           MVT::i32);
14373     else
14374       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14375
14376     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14377
14378     if (CondOpcode == ISD::UMULO)
14379       Cond = X86Op.getValue(2);
14380     else
14381       Cond = X86Op.getValue(1);
14382
14383     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14384     addTest = false;
14385   } else {
14386     unsigned CondOpc;
14387     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14388       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14389       if (CondOpc == ISD::OR) {
14390         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14391         // two branches instead of an explicit OR instruction with a
14392         // separate test.
14393         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14394             isX86LogicalCmp(Cmp)) {
14395           CC = Cond.getOperand(0).getOperand(0);
14396           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14397                               Chain, Dest, CC, Cmp);
14398           CC = Cond.getOperand(1).getOperand(0);
14399           Cond = Cmp;
14400           addTest = false;
14401         }
14402       } else { // ISD::AND
14403         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14404         // two branches instead of an explicit AND instruction with a
14405         // separate test. However, we only do this if this block doesn't
14406         // have a fall-through edge, because this requires an explicit
14407         // jmp when the condition is false.
14408         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14409             isX86LogicalCmp(Cmp) &&
14410             Op.getNode()->hasOneUse()) {
14411           X86::CondCode CCode =
14412             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14413           CCode = X86::GetOppositeBranchCondition(CCode);
14414           CC = DAG.getConstant(CCode, dl, MVT::i8);
14415           SDNode *User = *Op.getNode()->use_begin();
14416           // Look for an unconditional branch following this conditional branch.
14417           // We need this because we need to reverse the successors in order
14418           // to implement FCMP_OEQ.
14419           if (User->getOpcode() == ISD::BR) {
14420             SDValue FalseBB = User->getOperand(1);
14421             SDNode *NewBR =
14422               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14423             assert(NewBR == User);
14424             (void)NewBR;
14425             Dest = FalseBB;
14426
14427             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14428                                 Chain, Dest, CC, Cmp);
14429             X86::CondCode CCode =
14430               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14431             CCode = X86::GetOppositeBranchCondition(CCode);
14432             CC = DAG.getConstant(CCode, dl, MVT::i8);
14433             Cond = Cmp;
14434             addTest = false;
14435           }
14436         }
14437       }
14438     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14439       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14440       // It should be transformed during dag combiner except when the condition
14441       // is set by a arithmetics with overflow node.
14442       X86::CondCode CCode =
14443         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14444       CCode = X86::GetOppositeBranchCondition(CCode);
14445       CC = DAG.getConstant(CCode, dl, MVT::i8);
14446       Cond = Cond.getOperand(0).getOperand(1);
14447       addTest = false;
14448     } else if (Cond.getOpcode() == ISD::SETCC &&
14449                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14450       // For FCMP_OEQ, we can emit
14451       // two branches instead of an explicit AND instruction with a
14452       // separate test. However, we only do this if this block doesn't
14453       // have a fall-through edge, because this requires an explicit
14454       // jmp when the condition is false.
14455       if (Op.getNode()->hasOneUse()) {
14456         SDNode *User = *Op.getNode()->use_begin();
14457         // Look for an unconditional branch following this conditional branch.
14458         // We need this because we need to reverse the successors in order
14459         // to implement FCMP_OEQ.
14460         if (User->getOpcode() == ISD::BR) {
14461           SDValue FalseBB = User->getOperand(1);
14462           SDNode *NewBR =
14463             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14464           assert(NewBR == User);
14465           (void)NewBR;
14466           Dest = FalseBB;
14467
14468           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14469                                     Cond.getOperand(0), Cond.getOperand(1));
14470           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14471           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14472           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14473                               Chain, Dest, CC, Cmp);
14474           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14475           Cond = Cmp;
14476           addTest = false;
14477         }
14478       }
14479     } else if (Cond.getOpcode() == ISD::SETCC &&
14480                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14481       // For FCMP_UNE, we can emit
14482       // two branches instead of an explicit AND instruction with a
14483       // separate test. However, we only do this if this block doesn't
14484       // have a fall-through edge, because this requires an explicit
14485       // jmp when the condition is false.
14486       if (Op.getNode()->hasOneUse()) {
14487         SDNode *User = *Op.getNode()->use_begin();
14488         // Look for an unconditional branch following this conditional branch.
14489         // We need this because we need to reverse the successors in order
14490         // to implement FCMP_UNE.
14491         if (User->getOpcode() == ISD::BR) {
14492           SDValue FalseBB = User->getOperand(1);
14493           SDNode *NewBR =
14494             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14495           assert(NewBR == User);
14496           (void)NewBR;
14497
14498           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14499                                     Cond.getOperand(0), Cond.getOperand(1));
14500           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14501           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14502           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14503                               Chain, Dest, CC, Cmp);
14504           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14505           Cond = Cmp;
14506           addTest = false;
14507           Dest = FalseBB;
14508         }
14509       }
14510     }
14511   }
14512
14513   if (addTest) {
14514     // Look pass the truncate if the high bits are known zero.
14515     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14516         Cond = Cond.getOperand(0);
14517
14518     // We know the result of AND is compared against zero. Try to match
14519     // it to BT.
14520     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14521       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14522       if (NewSetCC.getNode()) {
14523         CC = NewSetCC.getOperand(0);
14524         Cond = NewSetCC.getOperand(1);
14525         addTest = false;
14526       }
14527     }
14528   }
14529
14530   if (addTest) {
14531     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14532     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14533     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14534   }
14535   Cond = ConvertCmpIfNecessary(Cond, DAG);
14536   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14537                      Chain, Dest, CC, Cond);
14538 }
14539
14540 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14541 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14542 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14543 // that the guard pages used by the OS virtual memory manager are allocated in
14544 // correct sequence.
14545 SDValue
14546 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14547                                            SelectionDAG &DAG) const {
14548   MachineFunction &MF = DAG.getMachineFunction();
14549   bool SplitStack = MF.shouldSplitStack();
14550   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14551                SplitStack;
14552   SDLoc dl(Op);
14553
14554   if (!Lower) {
14555     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14556     SDNode* Node = Op.getNode();
14557
14558     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14559     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14560         " not tell us which reg is the stack pointer!");
14561     EVT VT = Node->getValueType(0);
14562     SDValue Tmp1 = SDValue(Node, 0);
14563     SDValue Tmp2 = SDValue(Node, 1);
14564     SDValue Tmp3 = Node->getOperand(2);
14565     SDValue Chain = Tmp1.getOperand(0);
14566
14567     // Chain the dynamic stack allocation so that it doesn't modify the stack
14568     // pointer when other instructions are using the stack.
14569     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14570         SDLoc(Node));
14571
14572     SDValue Size = Tmp2.getOperand(1);
14573     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14574     Chain = SP.getValue(1);
14575     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14576     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14577     unsigned StackAlign = TFI.getStackAlignment();
14578     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14579     if (Align > StackAlign)
14580       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14581           DAG.getConstant(-(uint64_t)Align, dl, VT));
14582     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14583
14584     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14585         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14586         SDLoc(Node));
14587
14588     SDValue Ops[2] = { Tmp1, Tmp2 };
14589     return DAG.getMergeValues(Ops, dl);
14590   }
14591
14592   // Get the inputs.
14593   SDValue Chain = Op.getOperand(0);
14594   SDValue Size  = Op.getOperand(1);
14595   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14596   EVT VT = Op.getNode()->getValueType(0);
14597
14598   bool Is64Bit = Subtarget->is64Bit();
14599   EVT SPTy = getPointerTy();
14600
14601   if (SplitStack) {
14602     MachineRegisterInfo &MRI = MF.getRegInfo();
14603
14604     if (Is64Bit) {
14605       // The 64 bit implementation of segmented stacks needs to clobber both r10
14606       // r11. This makes it impossible to use it along with nested parameters.
14607       const Function *F = MF.getFunction();
14608
14609       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14610            I != E; ++I)
14611         if (I->hasNestAttr())
14612           report_fatal_error("Cannot use segmented stacks with functions that "
14613                              "have nested arguments.");
14614     }
14615
14616     const TargetRegisterClass *AddrRegClass =
14617       getRegClassFor(getPointerTy());
14618     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14619     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14620     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14621                                 DAG.getRegister(Vreg, SPTy));
14622     SDValue Ops1[2] = { Value, Chain };
14623     return DAG.getMergeValues(Ops1, dl);
14624   } else {
14625     SDValue Flag;
14626     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14627
14628     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14629     Flag = Chain.getValue(1);
14630     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14631
14632     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14633
14634     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14635     unsigned SPReg = RegInfo->getStackRegister();
14636     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14637     Chain = SP.getValue(1);
14638
14639     if (Align) {
14640       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14641                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14642       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14643     }
14644
14645     SDValue Ops1[2] = { SP, Chain };
14646     return DAG.getMergeValues(Ops1, dl);
14647   }
14648 }
14649
14650 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14651   MachineFunction &MF = DAG.getMachineFunction();
14652   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14653
14654   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14655   SDLoc DL(Op);
14656
14657   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14658     // vastart just stores the address of the VarArgsFrameIndex slot into the
14659     // memory location argument.
14660     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14661                                    getPointerTy());
14662     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14663                         MachinePointerInfo(SV), false, false, 0);
14664   }
14665
14666   // __va_list_tag:
14667   //   gp_offset         (0 - 6 * 8)
14668   //   fp_offset         (48 - 48 + 8 * 16)
14669   //   overflow_arg_area (point to parameters coming in memory).
14670   //   reg_save_area
14671   SmallVector<SDValue, 8> MemOps;
14672   SDValue FIN = Op.getOperand(1);
14673   // Store gp_offset
14674   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14675                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14676                                                DL, MVT::i32),
14677                                FIN, MachinePointerInfo(SV), false, false, 0);
14678   MemOps.push_back(Store);
14679
14680   // Store fp_offset
14681   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14682                     FIN, DAG.getIntPtrConstant(4, DL));
14683   Store = DAG.getStore(Op.getOperand(0), DL,
14684                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14685                                        MVT::i32),
14686                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14687   MemOps.push_back(Store);
14688
14689   // Store ptr to overflow_arg_area
14690   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14691                     FIN, DAG.getIntPtrConstant(4, DL));
14692   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14693                                     getPointerTy());
14694   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14695                        MachinePointerInfo(SV, 8),
14696                        false, false, 0);
14697   MemOps.push_back(Store);
14698
14699   // Store ptr to reg_save_area.
14700   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14701                     FIN, DAG.getIntPtrConstant(8, DL));
14702   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14703                                     getPointerTy());
14704   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14705                        MachinePointerInfo(SV, 16), false, false, 0);
14706   MemOps.push_back(Store);
14707   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14708 }
14709
14710 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14711   assert(Subtarget->is64Bit() &&
14712          "LowerVAARG only handles 64-bit va_arg!");
14713   assert((Subtarget->isTargetLinux() ||
14714           Subtarget->isTargetDarwin()) &&
14715           "Unhandled target in LowerVAARG");
14716   assert(Op.getNode()->getNumOperands() == 4);
14717   SDValue Chain = Op.getOperand(0);
14718   SDValue SrcPtr = Op.getOperand(1);
14719   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14720   unsigned Align = Op.getConstantOperandVal(3);
14721   SDLoc dl(Op);
14722
14723   EVT ArgVT = Op.getNode()->getValueType(0);
14724   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14725   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14726   uint8_t ArgMode;
14727
14728   // Decide which area this value should be read from.
14729   // TODO: Implement the AMD64 ABI in its entirety. This simple
14730   // selection mechanism works only for the basic types.
14731   if (ArgVT == MVT::f80) {
14732     llvm_unreachable("va_arg for f80 not yet implemented");
14733   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14734     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14735   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14736     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14737   } else {
14738     llvm_unreachable("Unhandled argument type in LowerVAARG");
14739   }
14740
14741   if (ArgMode == 2) {
14742     // Sanity Check: Make sure using fp_offset makes sense.
14743     assert(!Subtarget->useSoftFloat() &&
14744            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14745                Attribute::NoImplicitFloat)) &&
14746            Subtarget->hasSSE1());
14747   }
14748
14749   // Insert VAARG_64 node into the DAG
14750   // VAARG_64 returns two values: Variable Argument Address, Chain
14751   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14752                        DAG.getConstant(ArgMode, dl, MVT::i8),
14753                        DAG.getConstant(Align, dl, MVT::i32)};
14754   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14755   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14756                                           VTs, InstOps, MVT::i64,
14757                                           MachinePointerInfo(SV),
14758                                           /*Align=*/0,
14759                                           /*Volatile=*/false,
14760                                           /*ReadMem=*/true,
14761                                           /*WriteMem=*/true);
14762   Chain = VAARG.getValue(1);
14763
14764   // Load the next argument and return it
14765   return DAG.getLoad(ArgVT, dl,
14766                      Chain,
14767                      VAARG,
14768                      MachinePointerInfo(),
14769                      false, false, false, 0);
14770 }
14771
14772 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14773                            SelectionDAG &DAG) {
14774   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14775   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14776   SDValue Chain = Op.getOperand(0);
14777   SDValue DstPtr = Op.getOperand(1);
14778   SDValue SrcPtr = Op.getOperand(2);
14779   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14780   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14781   SDLoc DL(Op);
14782
14783   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14784                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14785                        false, false,
14786                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14787 }
14788
14789 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14790 // amount is a constant. Takes immediate version of shift as input.
14791 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14792                                           SDValue SrcOp, uint64_t ShiftAmt,
14793                                           SelectionDAG &DAG) {
14794   MVT ElementType = VT.getVectorElementType();
14795
14796   // Fold this packed shift into its first operand if ShiftAmt is 0.
14797   if (ShiftAmt == 0)
14798     return SrcOp;
14799
14800   // Check for ShiftAmt >= element width
14801   if (ShiftAmt >= ElementType.getSizeInBits()) {
14802     if (Opc == X86ISD::VSRAI)
14803       ShiftAmt = ElementType.getSizeInBits() - 1;
14804     else
14805       return DAG.getConstant(0, dl, VT);
14806   }
14807
14808   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14809          && "Unknown target vector shift-by-constant node");
14810
14811   // Fold this packed vector shift into a build vector if SrcOp is a
14812   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14813   if (VT == SrcOp.getSimpleValueType() &&
14814       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14815     SmallVector<SDValue, 8> Elts;
14816     unsigned NumElts = SrcOp->getNumOperands();
14817     ConstantSDNode *ND;
14818
14819     switch(Opc) {
14820     default: llvm_unreachable(nullptr);
14821     case X86ISD::VSHLI:
14822       for (unsigned i=0; i!=NumElts; ++i) {
14823         SDValue CurrentOp = SrcOp->getOperand(i);
14824         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14825           Elts.push_back(CurrentOp);
14826           continue;
14827         }
14828         ND = cast<ConstantSDNode>(CurrentOp);
14829         const APInt &C = ND->getAPIntValue();
14830         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14831       }
14832       break;
14833     case X86ISD::VSRLI:
14834       for (unsigned i=0; i!=NumElts; ++i) {
14835         SDValue CurrentOp = SrcOp->getOperand(i);
14836         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14837           Elts.push_back(CurrentOp);
14838           continue;
14839         }
14840         ND = cast<ConstantSDNode>(CurrentOp);
14841         const APInt &C = ND->getAPIntValue();
14842         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14843       }
14844       break;
14845     case X86ISD::VSRAI:
14846       for (unsigned i=0; i!=NumElts; ++i) {
14847         SDValue CurrentOp = SrcOp->getOperand(i);
14848         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14849           Elts.push_back(CurrentOp);
14850           continue;
14851         }
14852         ND = cast<ConstantSDNode>(CurrentOp);
14853         const APInt &C = ND->getAPIntValue();
14854         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14855       }
14856       break;
14857     }
14858
14859     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14860   }
14861
14862   return DAG.getNode(Opc, dl, VT, SrcOp,
14863                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14864 }
14865
14866 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14867 // may or may not be a constant. Takes immediate version of shift as input.
14868 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14869                                    SDValue SrcOp, SDValue ShAmt,
14870                                    SelectionDAG &DAG) {
14871   MVT SVT = ShAmt.getSimpleValueType();
14872   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14873
14874   // Catch shift-by-constant.
14875   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14876     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14877                                       CShAmt->getZExtValue(), DAG);
14878
14879   // Change opcode to non-immediate version
14880   switch (Opc) {
14881     default: llvm_unreachable("Unknown target vector shift node");
14882     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14883     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14884     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14885   }
14886
14887   const X86Subtarget &Subtarget =
14888       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14889   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14890       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14891     // Let the shuffle legalizer expand this shift amount node.
14892     SDValue Op0 = ShAmt.getOperand(0);
14893     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14894     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14895   } else {
14896     // Need to build a vector containing shift amount.
14897     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14898     SmallVector<SDValue, 4> ShOps;
14899     ShOps.push_back(ShAmt);
14900     if (SVT == MVT::i32) {
14901       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14902       ShOps.push_back(DAG.getUNDEF(SVT));
14903     }
14904     ShOps.push_back(DAG.getUNDEF(SVT));
14905
14906     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14907     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14908   }
14909
14910   // The return type has to be a 128-bit type with the same element
14911   // type as the input type.
14912   MVT EltVT = VT.getVectorElementType();
14913   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14914
14915   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14916   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14917 }
14918
14919 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14920 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14921 /// necessary casting for \p Mask when lowering masking intrinsics.
14922 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14923                                     SDValue PreservedSrc,
14924                                     const X86Subtarget *Subtarget,
14925                                     SelectionDAG &DAG) {
14926     EVT VT = Op.getValueType();
14927     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14928                                   MVT::i1, VT.getVectorNumElements());
14929     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14930                                      Mask.getValueType().getSizeInBits());
14931     SDLoc dl(Op);
14932
14933     assert(MaskVT.isSimple() && "invalid mask type");
14934
14935     if (isAllOnes(Mask))
14936       return Op;
14937
14938     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14939     // are extracted by EXTRACT_SUBVECTOR.
14940     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14941                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14942                               DAG.getIntPtrConstant(0, dl));
14943
14944     switch (Op.getOpcode()) {
14945       default: break;
14946       case X86ISD::PCMPEQM:
14947       case X86ISD::PCMPGTM:
14948       case X86ISD::CMPM:
14949       case X86ISD::CMPMU:
14950         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14951     }
14952     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14953       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14954     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14955 }
14956
14957 /// \brief Creates an SDNode for a predicated scalar operation.
14958 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14959 /// The mask is comming as MVT::i8 and it should be truncated
14960 /// to MVT::i1 while lowering masking intrinsics.
14961 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14962 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14963 /// a scalar instruction.
14964 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14965                                     SDValue PreservedSrc,
14966                                     const X86Subtarget *Subtarget,
14967                                     SelectionDAG &DAG) {
14968     if (isAllOnes(Mask))
14969       return Op;
14970
14971     EVT VT = Op.getValueType();
14972     SDLoc dl(Op);
14973     // The mask should be of type MVT::i1
14974     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14975
14976     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14977       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14978     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14979 }
14980
14981 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14982                                        SelectionDAG &DAG) {
14983   SDLoc dl(Op);
14984   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14985   EVT VT = Op.getValueType();
14986   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14987   if (IntrData) {
14988     switch(IntrData->Type) {
14989     case INTR_TYPE_1OP:
14990       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14991     case INTR_TYPE_2OP:
14992       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14993         Op.getOperand(2));
14994     case INTR_TYPE_3OP:
14995       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14996         Op.getOperand(2), Op.getOperand(3));
14997     case INTR_TYPE_1OP_MASK_RM: {
14998       SDValue Src = Op.getOperand(1);
14999       SDValue Src0 = Op.getOperand(2);
15000       SDValue Mask = Op.getOperand(3);
15001       SDValue RoundingMode = Op.getOperand(4);
15002       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15003                                               RoundingMode),
15004                                   Mask, Src0, Subtarget, DAG);
15005     }
15006     case INTR_TYPE_SCALAR_MASK_RM: {
15007       SDValue Src1 = Op.getOperand(1);
15008       SDValue Src2 = Op.getOperand(2);
15009       SDValue Src0 = Op.getOperand(3);
15010       SDValue Mask = Op.getOperand(4);
15011       // There are 2 kinds of intrinsics in this group:
15012       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15013       // (2) With rounding mode and sae - 7 operands.
15014       if (Op.getNumOperands() == 6) {
15015         SDValue Sae  = Op.getOperand(5);
15016         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15017         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15018                                                 Sae),
15019                                     Mask, Src0, Subtarget, DAG);
15020       }
15021       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15022       SDValue RoundingMode  = Op.getOperand(5);
15023       SDValue Sae  = Op.getOperand(6);
15024       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15025                                               RoundingMode, Sae),
15026                                   Mask, Src0, Subtarget, DAG);
15027     }
15028     case INTR_TYPE_2OP_MASK: {
15029       SDValue Src1 = Op.getOperand(1);
15030       SDValue Src2 = Op.getOperand(2);
15031       SDValue PassThru = Op.getOperand(3);
15032       SDValue Mask = Op.getOperand(4);
15033       // We specify 2 possible opcodes for intrinsics with rounding modes.
15034       // First, we check if the intrinsic may have non-default rounding mode,
15035       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15036       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15037       if (IntrWithRoundingModeOpcode != 0) {
15038         SDValue Rnd = Op.getOperand(5);
15039         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15040         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15041           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15042                                       dl, Op.getValueType(),
15043                                       Src1, Src2, Rnd),
15044                                       Mask, PassThru, Subtarget, DAG);
15045         }
15046       }
15047       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15048                                               Src1,Src2),
15049                                   Mask, PassThru, Subtarget, DAG);
15050     }
15051     case FMA_OP_MASK: {
15052       SDValue Src1 = Op.getOperand(1);
15053       SDValue Src2 = Op.getOperand(2);
15054       SDValue Src3 = Op.getOperand(3);
15055       SDValue Mask = Op.getOperand(4);
15056       // We specify 2 possible opcodes for intrinsics with rounding modes.
15057       // First, we check if the intrinsic may have non-default rounding mode,
15058       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15059       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15060       if (IntrWithRoundingModeOpcode != 0) {
15061         SDValue Rnd = Op.getOperand(5);
15062         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15063             X86::STATIC_ROUNDING::CUR_DIRECTION)
15064           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15065                                                   dl, Op.getValueType(),
15066                                                   Src1, Src2, Src3, Rnd),
15067                                       Mask, Src1, Subtarget, DAG);
15068       }
15069       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15070                                               dl, Op.getValueType(),
15071                                               Src1, Src2, Src3),
15072                                   Mask, Src1, Subtarget, DAG);
15073     }
15074     case CMP_MASK:
15075     case CMP_MASK_CC: {
15076       // Comparison intrinsics with masks.
15077       // Example of transformation:
15078       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15079       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15080       // (i8 (bitcast
15081       //   (v8i1 (insert_subvector undef,
15082       //           (v2i1 (and (PCMPEQM %a, %b),
15083       //                      (extract_subvector
15084       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15085       EVT VT = Op.getOperand(1).getValueType();
15086       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15087                                     VT.getVectorNumElements());
15088       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15089       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15090                                        Mask.getValueType().getSizeInBits());
15091       SDValue Cmp;
15092       if (IntrData->Type == CMP_MASK_CC) {
15093         SDValue CC = Op.getOperand(3);
15094         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15095         // We specify 2 possible opcodes for intrinsics with rounding modes.
15096         // First, we check if the intrinsic may have non-default rounding mode,
15097         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15098         if (IntrData->Opc1 != 0) {
15099           SDValue Rnd = Op.getOperand(5);
15100           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15101               X86::STATIC_ROUNDING::CUR_DIRECTION)
15102             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15103                               Op.getOperand(2), CC, Rnd);
15104         }
15105         //default rounding mode
15106         if(!Cmp.getNode())
15107             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15108                               Op.getOperand(2), CC);
15109
15110       } else {
15111         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15112         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15113                           Op.getOperand(2));
15114       }
15115       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15116                                              DAG.getTargetConstant(0, dl,
15117                                                                    MaskVT),
15118                                              Subtarget, DAG);
15119       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15120                                 DAG.getUNDEF(BitcastVT), CmpMask,
15121                                 DAG.getIntPtrConstant(0, dl));
15122       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15123     }
15124     case COMI: { // Comparison intrinsics
15125       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15126       SDValue LHS = Op.getOperand(1);
15127       SDValue RHS = Op.getOperand(2);
15128       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15129       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15130       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15131       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15132                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15133       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15134     }
15135     case VSHIFT:
15136       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15137                                  Op.getOperand(1), Op.getOperand(2), DAG);
15138     case VSHIFT_MASK:
15139       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15140                                                       Op.getSimpleValueType(),
15141                                                       Op.getOperand(1),
15142                                                       Op.getOperand(2), DAG),
15143                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15144                                   DAG);
15145     case COMPRESS_EXPAND_IN_REG: {
15146       SDValue Mask = Op.getOperand(3);
15147       SDValue DataToCompress = Op.getOperand(1);
15148       SDValue PassThru = Op.getOperand(2);
15149       if (isAllOnes(Mask)) // return data as is
15150         return Op.getOperand(1);
15151       EVT VT = Op.getValueType();
15152       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15153                                     VT.getVectorNumElements());
15154       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15155                                        Mask.getValueType().getSizeInBits());
15156       SDLoc dl(Op);
15157       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15158                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15159                                   DAG.getIntPtrConstant(0, dl));
15160
15161       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15162                          PassThru);
15163     }
15164     case BLEND: {
15165       SDValue Mask = Op.getOperand(3);
15166       EVT VT = Op.getValueType();
15167       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15168                                     VT.getVectorNumElements());
15169       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15170                                        Mask.getValueType().getSizeInBits());
15171       SDLoc dl(Op);
15172       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15173                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15174                                   DAG.getIntPtrConstant(0, dl));
15175       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15176                          Op.getOperand(2));
15177     }
15178     default:
15179       break;
15180     }
15181   }
15182
15183   switch (IntNo) {
15184   default: return SDValue();    // Don't custom lower most intrinsics.
15185
15186   case Intrinsic::x86_avx2_permd:
15187   case Intrinsic::x86_avx2_permps:
15188     // Operands intentionally swapped. Mask is last operand to intrinsic,
15189     // but second operand for node/instruction.
15190     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15191                        Op.getOperand(2), Op.getOperand(1));
15192
15193   case Intrinsic::x86_avx512_mask_valign_q_512:
15194   case Intrinsic::x86_avx512_mask_valign_d_512:
15195     // Vector source operands are swapped.
15196     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15197                                             Op.getValueType(), Op.getOperand(2),
15198                                             Op.getOperand(1),
15199                                             Op.getOperand(3)),
15200                                 Op.getOperand(5), Op.getOperand(4),
15201                                 Subtarget, DAG);
15202
15203   // ptest and testp intrinsics. The intrinsic these come from are designed to
15204   // return an integer value, not just an instruction so lower it to the ptest
15205   // or testp pattern and a setcc for the result.
15206   case Intrinsic::x86_sse41_ptestz:
15207   case Intrinsic::x86_sse41_ptestc:
15208   case Intrinsic::x86_sse41_ptestnzc:
15209   case Intrinsic::x86_avx_ptestz_256:
15210   case Intrinsic::x86_avx_ptestc_256:
15211   case Intrinsic::x86_avx_ptestnzc_256:
15212   case Intrinsic::x86_avx_vtestz_ps:
15213   case Intrinsic::x86_avx_vtestc_ps:
15214   case Intrinsic::x86_avx_vtestnzc_ps:
15215   case Intrinsic::x86_avx_vtestz_pd:
15216   case Intrinsic::x86_avx_vtestc_pd:
15217   case Intrinsic::x86_avx_vtestnzc_pd:
15218   case Intrinsic::x86_avx_vtestz_ps_256:
15219   case Intrinsic::x86_avx_vtestc_ps_256:
15220   case Intrinsic::x86_avx_vtestnzc_ps_256:
15221   case Intrinsic::x86_avx_vtestz_pd_256:
15222   case Intrinsic::x86_avx_vtestc_pd_256:
15223   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15224     bool IsTestPacked = false;
15225     unsigned X86CC;
15226     switch (IntNo) {
15227     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15228     case Intrinsic::x86_avx_vtestz_ps:
15229     case Intrinsic::x86_avx_vtestz_pd:
15230     case Intrinsic::x86_avx_vtestz_ps_256:
15231     case Intrinsic::x86_avx_vtestz_pd_256:
15232       IsTestPacked = true; // Fallthrough
15233     case Intrinsic::x86_sse41_ptestz:
15234     case Intrinsic::x86_avx_ptestz_256:
15235       // ZF = 1
15236       X86CC = X86::COND_E;
15237       break;
15238     case Intrinsic::x86_avx_vtestc_ps:
15239     case Intrinsic::x86_avx_vtestc_pd:
15240     case Intrinsic::x86_avx_vtestc_ps_256:
15241     case Intrinsic::x86_avx_vtestc_pd_256:
15242       IsTestPacked = true; // Fallthrough
15243     case Intrinsic::x86_sse41_ptestc:
15244     case Intrinsic::x86_avx_ptestc_256:
15245       // CF = 1
15246       X86CC = X86::COND_B;
15247       break;
15248     case Intrinsic::x86_avx_vtestnzc_ps:
15249     case Intrinsic::x86_avx_vtestnzc_pd:
15250     case Intrinsic::x86_avx_vtestnzc_ps_256:
15251     case Intrinsic::x86_avx_vtestnzc_pd_256:
15252       IsTestPacked = true; // Fallthrough
15253     case Intrinsic::x86_sse41_ptestnzc:
15254     case Intrinsic::x86_avx_ptestnzc_256:
15255       // ZF and CF = 0
15256       X86CC = X86::COND_A;
15257       break;
15258     }
15259
15260     SDValue LHS = Op.getOperand(1);
15261     SDValue RHS = Op.getOperand(2);
15262     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15263     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15264     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15265     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15266     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15267   }
15268   case Intrinsic::x86_avx512_kortestz_w:
15269   case Intrinsic::x86_avx512_kortestc_w: {
15270     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15271     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15272     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15273     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15274     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15275     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15276     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15277   }
15278
15279   case Intrinsic::x86_sse42_pcmpistria128:
15280   case Intrinsic::x86_sse42_pcmpestria128:
15281   case Intrinsic::x86_sse42_pcmpistric128:
15282   case Intrinsic::x86_sse42_pcmpestric128:
15283   case Intrinsic::x86_sse42_pcmpistrio128:
15284   case Intrinsic::x86_sse42_pcmpestrio128:
15285   case Intrinsic::x86_sse42_pcmpistris128:
15286   case Intrinsic::x86_sse42_pcmpestris128:
15287   case Intrinsic::x86_sse42_pcmpistriz128:
15288   case Intrinsic::x86_sse42_pcmpestriz128: {
15289     unsigned Opcode;
15290     unsigned X86CC;
15291     switch (IntNo) {
15292     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15293     case Intrinsic::x86_sse42_pcmpistria128:
15294       Opcode = X86ISD::PCMPISTRI;
15295       X86CC = X86::COND_A;
15296       break;
15297     case Intrinsic::x86_sse42_pcmpestria128:
15298       Opcode = X86ISD::PCMPESTRI;
15299       X86CC = X86::COND_A;
15300       break;
15301     case Intrinsic::x86_sse42_pcmpistric128:
15302       Opcode = X86ISD::PCMPISTRI;
15303       X86CC = X86::COND_B;
15304       break;
15305     case Intrinsic::x86_sse42_pcmpestric128:
15306       Opcode = X86ISD::PCMPESTRI;
15307       X86CC = X86::COND_B;
15308       break;
15309     case Intrinsic::x86_sse42_pcmpistrio128:
15310       Opcode = X86ISD::PCMPISTRI;
15311       X86CC = X86::COND_O;
15312       break;
15313     case Intrinsic::x86_sse42_pcmpestrio128:
15314       Opcode = X86ISD::PCMPESTRI;
15315       X86CC = X86::COND_O;
15316       break;
15317     case Intrinsic::x86_sse42_pcmpistris128:
15318       Opcode = X86ISD::PCMPISTRI;
15319       X86CC = X86::COND_S;
15320       break;
15321     case Intrinsic::x86_sse42_pcmpestris128:
15322       Opcode = X86ISD::PCMPESTRI;
15323       X86CC = X86::COND_S;
15324       break;
15325     case Intrinsic::x86_sse42_pcmpistriz128:
15326       Opcode = X86ISD::PCMPISTRI;
15327       X86CC = X86::COND_E;
15328       break;
15329     case Intrinsic::x86_sse42_pcmpestriz128:
15330       Opcode = X86ISD::PCMPESTRI;
15331       X86CC = X86::COND_E;
15332       break;
15333     }
15334     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15335     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15336     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15337     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15338                                 DAG.getConstant(X86CC, dl, MVT::i8),
15339                                 SDValue(PCMP.getNode(), 1));
15340     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15341   }
15342
15343   case Intrinsic::x86_sse42_pcmpistri128:
15344   case Intrinsic::x86_sse42_pcmpestri128: {
15345     unsigned Opcode;
15346     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15347       Opcode = X86ISD::PCMPISTRI;
15348     else
15349       Opcode = X86ISD::PCMPESTRI;
15350
15351     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15352     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15353     return DAG.getNode(Opcode, dl, VTs, NewOps);
15354   }
15355
15356   case Intrinsic::x86_seh_lsda: {
15357     // Compute the symbol for the LSDA. We know it'll get emitted later.
15358     MachineFunction &MF = DAG.getMachineFunction();
15359     SDValue Op1 = Op.getOperand(1);
15360     Op1->dump();
15361     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15362     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15363         GlobalValue::getRealLinkageName(Fn->getName()));
15364     StringRef Name = LSDASym->getName();
15365     assert(Name.data()[Name.size()] == '\0' && "not null terminated");
15366
15367     // Generate a simple absolute symbol reference. This intrinsic is only
15368     // supported on 32-bit Windows, which isn't PIC.
15369     SDValue Result =
15370         DAG.getTargetExternalSymbol(Name.data(), VT, X86II::MO_NOPREFIX);
15371     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15372   }
15373   }
15374 }
15375
15376 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15377                               SDValue Src, SDValue Mask, SDValue Base,
15378                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15379                               const X86Subtarget * Subtarget) {
15380   SDLoc dl(Op);
15381   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15382   assert(C && "Invalid scale type");
15383   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15384   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15385                              Index.getSimpleValueType().getVectorNumElements());
15386   SDValue MaskInReg;
15387   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15388   if (MaskC)
15389     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15390   else
15391     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15392   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15393   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15394   SDValue Segment = DAG.getRegister(0, MVT::i32);
15395   if (Src.getOpcode() == ISD::UNDEF)
15396     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15397   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15398   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15399   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15400   return DAG.getMergeValues(RetOps, dl);
15401 }
15402
15403 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15404                                SDValue Src, SDValue Mask, SDValue Base,
15405                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15406   SDLoc dl(Op);
15407   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15408   assert(C && "Invalid scale type");
15409   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15410   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15411   SDValue Segment = DAG.getRegister(0, MVT::i32);
15412   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15413                              Index.getSimpleValueType().getVectorNumElements());
15414   SDValue MaskInReg;
15415   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15416   if (MaskC)
15417     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15418   else
15419     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15420   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15421   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15422   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15423   return SDValue(Res, 1);
15424 }
15425
15426 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15427                                SDValue Mask, SDValue Base, SDValue Index,
15428                                SDValue ScaleOp, SDValue Chain) {
15429   SDLoc dl(Op);
15430   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15431   assert(C && "Invalid scale type");
15432   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15433   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15434   SDValue Segment = DAG.getRegister(0, MVT::i32);
15435   EVT MaskVT =
15436     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15437   SDValue MaskInReg;
15438   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15439   if (MaskC)
15440     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15441   else
15442     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15443   //SDVTList VTs = DAG.getVTList(MVT::Other);
15444   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15445   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15446   return SDValue(Res, 0);
15447 }
15448
15449 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15450 // read performance monitor counters (x86_rdpmc).
15451 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15452                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15453                               SmallVectorImpl<SDValue> &Results) {
15454   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15455   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15456   SDValue LO, HI;
15457
15458   // The ECX register is used to select the index of the performance counter
15459   // to read.
15460   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15461                                    N->getOperand(2));
15462   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15463
15464   // Reads the content of a 64-bit performance counter and returns it in the
15465   // registers EDX:EAX.
15466   if (Subtarget->is64Bit()) {
15467     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15468     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15469                             LO.getValue(2));
15470   } else {
15471     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15472     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15473                             LO.getValue(2));
15474   }
15475   Chain = HI.getValue(1);
15476
15477   if (Subtarget->is64Bit()) {
15478     // The EAX register is loaded with the low-order 32 bits. The EDX register
15479     // is loaded with the supported high-order bits of the counter.
15480     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15481                               DAG.getConstant(32, DL, MVT::i8));
15482     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15483     Results.push_back(Chain);
15484     return;
15485   }
15486
15487   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15488   SDValue Ops[] = { LO, HI };
15489   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15490   Results.push_back(Pair);
15491   Results.push_back(Chain);
15492 }
15493
15494 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15495 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15496 // also used to custom lower READCYCLECOUNTER nodes.
15497 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15498                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15499                               SmallVectorImpl<SDValue> &Results) {
15500   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15501   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15502   SDValue LO, HI;
15503
15504   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15505   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15506   // and the EAX register is loaded with the low-order 32 bits.
15507   if (Subtarget->is64Bit()) {
15508     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15509     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15510                             LO.getValue(2));
15511   } else {
15512     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15513     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15514                             LO.getValue(2));
15515   }
15516   SDValue Chain = HI.getValue(1);
15517
15518   if (Opcode == X86ISD::RDTSCP_DAG) {
15519     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15520
15521     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15522     // the ECX register. Add 'ecx' explicitly to the chain.
15523     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15524                                      HI.getValue(2));
15525     // Explicitly store the content of ECX at the location passed in input
15526     // to the 'rdtscp' intrinsic.
15527     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15528                          MachinePointerInfo(), false, false, 0);
15529   }
15530
15531   if (Subtarget->is64Bit()) {
15532     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15533     // the EAX register is loaded with the low-order 32 bits.
15534     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15535                               DAG.getConstant(32, DL, MVT::i8));
15536     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15537     Results.push_back(Chain);
15538     return;
15539   }
15540
15541   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15542   SDValue Ops[] = { LO, HI };
15543   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15544   Results.push_back(Pair);
15545   Results.push_back(Chain);
15546 }
15547
15548 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15549                                      SelectionDAG &DAG) {
15550   SmallVector<SDValue, 2> Results;
15551   SDLoc DL(Op);
15552   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15553                           Results);
15554   return DAG.getMergeValues(Results, DL);
15555 }
15556
15557
15558 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15559                                       SelectionDAG &DAG) {
15560   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15561
15562   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15563   if (!IntrData)
15564     return SDValue();
15565
15566   SDLoc dl(Op);
15567   switch(IntrData->Type) {
15568   default:
15569     llvm_unreachable("Unknown Intrinsic Type");
15570     break;
15571   case RDSEED:
15572   case RDRAND: {
15573     // Emit the node with the right value type.
15574     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15575     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15576
15577     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15578     // Otherwise return the value from Rand, which is always 0, casted to i32.
15579     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15580                       DAG.getConstant(1, dl, Op->getValueType(1)),
15581                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15582                       SDValue(Result.getNode(), 1) };
15583     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15584                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15585                                   Ops);
15586
15587     // Return { result, isValid, chain }.
15588     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15589                        SDValue(Result.getNode(), 2));
15590   }
15591   case GATHER: {
15592   //gather(v1, mask, index, base, scale);
15593     SDValue Chain = Op.getOperand(0);
15594     SDValue Src   = Op.getOperand(2);
15595     SDValue Base  = Op.getOperand(3);
15596     SDValue Index = Op.getOperand(4);
15597     SDValue Mask  = Op.getOperand(5);
15598     SDValue Scale = Op.getOperand(6);
15599     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15600                          Chain, Subtarget);
15601   }
15602   case SCATTER: {
15603   //scatter(base, mask, index, v1, scale);
15604     SDValue Chain = Op.getOperand(0);
15605     SDValue Base  = Op.getOperand(2);
15606     SDValue Mask  = Op.getOperand(3);
15607     SDValue Index = Op.getOperand(4);
15608     SDValue Src   = Op.getOperand(5);
15609     SDValue Scale = Op.getOperand(6);
15610     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15611                           Scale, Chain);
15612   }
15613   case PREFETCH: {
15614     SDValue Hint = Op.getOperand(6);
15615     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15616     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15617     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15618     SDValue Chain = Op.getOperand(0);
15619     SDValue Mask  = Op.getOperand(2);
15620     SDValue Index = Op.getOperand(3);
15621     SDValue Base  = Op.getOperand(4);
15622     SDValue Scale = Op.getOperand(5);
15623     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15624   }
15625   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15626   case RDTSC: {
15627     SmallVector<SDValue, 2> Results;
15628     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15629                             Results);
15630     return DAG.getMergeValues(Results, dl);
15631   }
15632   // Read Performance Monitoring Counters.
15633   case RDPMC: {
15634     SmallVector<SDValue, 2> Results;
15635     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15636     return DAG.getMergeValues(Results, dl);
15637   }
15638   // XTEST intrinsics.
15639   case XTEST: {
15640     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15641     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15642     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15643                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15644                                 InTrans);
15645     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15646     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15647                        Ret, SDValue(InTrans.getNode(), 1));
15648   }
15649   // ADC/ADCX/SBB
15650   case ADX: {
15651     SmallVector<SDValue, 2> Results;
15652     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15653     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15654     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15655                                 DAG.getConstant(-1, dl, MVT::i8));
15656     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15657                               Op.getOperand(4), GenCF.getValue(1));
15658     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15659                                  Op.getOperand(5), MachinePointerInfo(),
15660                                  false, false, 0);
15661     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15662                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15663                                 Res.getValue(1));
15664     Results.push_back(SetCC);
15665     Results.push_back(Store);
15666     return DAG.getMergeValues(Results, dl);
15667   }
15668   case COMPRESS_TO_MEM: {
15669     SDLoc dl(Op);
15670     SDValue Mask = Op.getOperand(4);
15671     SDValue DataToCompress = Op.getOperand(3);
15672     SDValue Addr = Op.getOperand(2);
15673     SDValue Chain = Op.getOperand(0);
15674
15675     if (isAllOnes(Mask)) // return just a store
15676       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15677                           MachinePointerInfo(), false, false, 0);
15678
15679     EVT VT = DataToCompress.getValueType();
15680     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15681                                   VT.getVectorNumElements());
15682     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15683                                      Mask.getValueType().getSizeInBits());
15684     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15685                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15686                                 DAG.getIntPtrConstant(0, dl));
15687
15688     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15689                                       DataToCompress, DAG.getUNDEF(VT));
15690     return DAG.getStore(Chain, dl, Compressed, Addr,
15691                         MachinePointerInfo(), false, false, 0);
15692   }
15693   case EXPAND_FROM_MEM: {
15694     SDLoc dl(Op);
15695     SDValue Mask = Op.getOperand(4);
15696     SDValue PathThru = Op.getOperand(3);
15697     SDValue Addr = Op.getOperand(2);
15698     SDValue Chain = Op.getOperand(0);
15699     EVT VT = Op.getValueType();
15700
15701     if (isAllOnes(Mask)) // return just a load
15702       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15703                          false, 0);
15704     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15705                                   VT.getVectorNumElements());
15706     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15707                                      Mask.getValueType().getSizeInBits());
15708     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15709                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15710                                 DAG.getIntPtrConstant(0, dl));
15711
15712     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15713                                    false, false, false, 0);
15714
15715     SDValue Results[] = {
15716         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15717         Chain};
15718     return DAG.getMergeValues(Results, dl);
15719   }
15720   }
15721 }
15722
15723 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15724                                            SelectionDAG &DAG) const {
15725   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15726   MFI->setReturnAddressIsTaken(true);
15727
15728   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15729     return SDValue();
15730
15731   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15732   SDLoc dl(Op);
15733   EVT PtrVT = getPointerTy();
15734
15735   if (Depth > 0) {
15736     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15737     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15738     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15739     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15740                        DAG.getNode(ISD::ADD, dl, PtrVT,
15741                                    FrameAddr, Offset),
15742                        MachinePointerInfo(), false, false, false, 0);
15743   }
15744
15745   // Just load the return address.
15746   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15747   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15748                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15749 }
15750
15751 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15752   MachineFunction &MF = DAG.getMachineFunction();
15753   MachineFrameInfo *MFI = MF.getFrameInfo();
15754   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15755   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15756   EVT VT = Op.getValueType();
15757
15758   MFI->setFrameAddressIsTaken(true);
15759
15760   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15761     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15762     // is not possible to crawl up the stack without looking at the unwind codes
15763     // simultaneously.
15764     int FrameAddrIndex = FuncInfo->getFAIndex();
15765     if (!FrameAddrIndex) {
15766       // Set up a frame object for the return address.
15767       unsigned SlotSize = RegInfo->getSlotSize();
15768       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15769           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15770       FuncInfo->setFAIndex(FrameAddrIndex);
15771     }
15772     return DAG.getFrameIndex(FrameAddrIndex, VT);
15773   }
15774
15775   unsigned FrameReg =
15776       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15777   SDLoc dl(Op);  // FIXME probably not meaningful
15778   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15779   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15780           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15781          "Invalid Frame Register!");
15782   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15783   while (Depth--)
15784     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15785                             MachinePointerInfo(),
15786                             false, false, false, 0);
15787   return FrameAddr;
15788 }
15789
15790 // FIXME? Maybe this could be a TableGen attribute on some registers and
15791 // this table could be generated automatically from RegInfo.
15792 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15793                                               EVT VT) const {
15794   unsigned Reg = StringSwitch<unsigned>(RegName)
15795                        .Case("esp", X86::ESP)
15796                        .Case("rsp", X86::RSP)
15797                        .Default(0);
15798   if (Reg)
15799     return Reg;
15800   report_fatal_error("Invalid register name global variable");
15801 }
15802
15803 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15804                                                      SelectionDAG &DAG) const {
15805   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15806   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15807 }
15808
15809 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15810   SDValue Chain     = Op.getOperand(0);
15811   SDValue Offset    = Op.getOperand(1);
15812   SDValue Handler   = Op.getOperand(2);
15813   SDLoc dl      (Op);
15814
15815   EVT PtrVT = getPointerTy();
15816   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15817   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15818   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15819           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15820          "Invalid Frame Register!");
15821   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15822   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15823
15824   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15825                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15826                                                        dl));
15827   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15828   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15829                        false, false, 0);
15830   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15831
15832   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15833                      DAG.getRegister(StoreAddrReg, PtrVT));
15834 }
15835
15836 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15837                                                SelectionDAG &DAG) const {
15838   SDLoc DL(Op);
15839   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15840                      DAG.getVTList(MVT::i32, MVT::Other),
15841                      Op.getOperand(0), Op.getOperand(1));
15842 }
15843
15844 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15845                                                 SelectionDAG &DAG) const {
15846   SDLoc DL(Op);
15847   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15848                      Op.getOperand(0), Op.getOperand(1));
15849 }
15850
15851 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15852   return Op.getOperand(0);
15853 }
15854
15855 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15856                                                 SelectionDAG &DAG) const {
15857   SDValue Root = Op.getOperand(0);
15858   SDValue Trmp = Op.getOperand(1); // trampoline
15859   SDValue FPtr = Op.getOperand(2); // nested function
15860   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15861   SDLoc dl (Op);
15862
15863   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15864   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15865
15866   if (Subtarget->is64Bit()) {
15867     SDValue OutChains[6];
15868
15869     // Large code-model.
15870     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15871     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15872
15873     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15874     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15875
15876     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15877
15878     // Load the pointer to the nested function into R11.
15879     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15880     SDValue Addr = Trmp;
15881     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15882                                 Addr, MachinePointerInfo(TrmpAddr),
15883                                 false, false, 0);
15884
15885     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15886                        DAG.getConstant(2, dl, MVT::i64));
15887     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15888                                 MachinePointerInfo(TrmpAddr, 2),
15889                                 false, false, 2);
15890
15891     // Load the 'nest' parameter value into R10.
15892     // R10 is specified in X86CallingConv.td
15893     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15894     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15895                        DAG.getConstant(10, dl, MVT::i64));
15896     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15897                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15898                                 false, false, 0);
15899
15900     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15901                        DAG.getConstant(12, dl, MVT::i64));
15902     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15903                                 MachinePointerInfo(TrmpAddr, 12),
15904                                 false, false, 2);
15905
15906     // Jump to the nested function.
15907     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15908     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15909                        DAG.getConstant(20, dl, MVT::i64));
15910     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15911                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15912                                 false, false, 0);
15913
15914     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15915     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15916                        DAG.getConstant(22, dl, MVT::i64));
15917     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15918                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15919                                 false, false, 0);
15920
15921     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15922   } else {
15923     const Function *Func =
15924       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15925     CallingConv::ID CC = Func->getCallingConv();
15926     unsigned NestReg;
15927
15928     switch (CC) {
15929     default:
15930       llvm_unreachable("Unsupported calling convention");
15931     case CallingConv::C:
15932     case CallingConv::X86_StdCall: {
15933       // Pass 'nest' parameter in ECX.
15934       // Must be kept in sync with X86CallingConv.td
15935       NestReg = X86::ECX;
15936
15937       // Check that ECX wasn't needed by an 'inreg' parameter.
15938       FunctionType *FTy = Func->getFunctionType();
15939       const AttributeSet &Attrs = Func->getAttributes();
15940
15941       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15942         unsigned InRegCount = 0;
15943         unsigned Idx = 1;
15944
15945         for (FunctionType::param_iterator I = FTy->param_begin(),
15946              E = FTy->param_end(); I != E; ++I, ++Idx)
15947           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15948             // FIXME: should only count parameters that are lowered to integers.
15949             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15950
15951         if (InRegCount > 2) {
15952           report_fatal_error("Nest register in use - reduce number of inreg"
15953                              " parameters!");
15954         }
15955       }
15956       break;
15957     }
15958     case CallingConv::X86_FastCall:
15959     case CallingConv::X86_ThisCall:
15960     case CallingConv::Fast:
15961       // Pass 'nest' parameter in EAX.
15962       // Must be kept in sync with X86CallingConv.td
15963       NestReg = X86::EAX;
15964       break;
15965     }
15966
15967     SDValue OutChains[4];
15968     SDValue Addr, Disp;
15969
15970     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15971                        DAG.getConstant(10, dl, MVT::i32));
15972     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15973
15974     // This is storing the opcode for MOV32ri.
15975     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15976     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15977     OutChains[0] = DAG.getStore(Root, dl,
15978                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15979                                 Trmp, MachinePointerInfo(TrmpAddr),
15980                                 false, false, 0);
15981
15982     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15983                        DAG.getConstant(1, dl, MVT::i32));
15984     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15985                                 MachinePointerInfo(TrmpAddr, 1),
15986                                 false, false, 1);
15987
15988     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15989     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15990                        DAG.getConstant(5, dl, MVT::i32));
15991     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15992                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15993                                 false, false, 1);
15994
15995     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15996                        DAG.getConstant(6, dl, MVT::i32));
15997     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15998                                 MachinePointerInfo(TrmpAddr, 6),
15999                                 false, false, 1);
16000
16001     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16002   }
16003 }
16004
16005 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16006                                             SelectionDAG &DAG) const {
16007   /*
16008    The rounding mode is in bits 11:10 of FPSR, and has the following
16009    settings:
16010      00 Round to nearest
16011      01 Round to -inf
16012      10 Round to +inf
16013      11 Round to 0
16014
16015   FLT_ROUNDS, on the other hand, expects the following:
16016     -1 Undefined
16017      0 Round to 0
16018      1 Round to nearest
16019      2 Round to +inf
16020      3 Round to -inf
16021
16022   To perform the conversion, we do:
16023     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16024   */
16025
16026   MachineFunction &MF = DAG.getMachineFunction();
16027   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16028   unsigned StackAlignment = TFI.getStackAlignment();
16029   MVT VT = Op.getSimpleValueType();
16030   SDLoc DL(Op);
16031
16032   // Save FP Control Word to stack slot
16033   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16034   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16035
16036   MachineMemOperand *MMO =
16037    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16038                            MachineMemOperand::MOStore, 2, 2);
16039
16040   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16041   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16042                                           DAG.getVTList(MVT::Other),
16043                                           Ops, MVT::i16, MMO);
16044
16045   // Load FP Control Word from stack slot
16046   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16047                             MachinePointerInfo(), false, false, false, 0);
16048
16049   // Transform as necessary
16050   SDValue CWD1 =
16051     DAG.getNode(ISD::SRL, DL, MVT::i16,
16052                 DAG.getNode(ISD::AND, DL, MVT::i16,
16053                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16054                 DAG.getConstant(11, DL, MVT::i8));
16055   SDValue CWD2 =
16056     DAG.getNode(ISD::SRL, DL, MVT::i16,
16057                 DAG.getNode(ISD::AND, DL, MVT::i16,
16058                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16059                 DAG.getConstant(9, DL, MVT::i8));
16060
16061   SDValue RetVal =
16062     DAG.getNode(ISD::AND, DL, MVT::i16,
16063                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16064                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16065                             DAG.getConstant(1, DL, MVT::i16)),
16066                 DAG.getConstant(3, DL, MVT::i16));
16067
16068   return DAG.getNode((VT.getSizeInBits() < 16 ?
16069                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16070 }
16071
16072 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16073   MVT VT = Op.getSimpleValueType();
16074   EVT OpVT = VT;
16075   unsigned NumBits = VT.getSizeInBits();
16076   SDLoc dl(Op);
16077
16078   Op = Op.getOperand(0);
16079   if (VT == MVT::i8) {
16080     // Zero extend to i32 since there is not an i8 bsr.
16081     OpVT = MVT::i32;
16082     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16083   }
16084
16085   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16086   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16087   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16088
16089   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16090   SDValue Ops[] = {
16091     Op,
16092     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16093     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16094     Op.getValue(1)
16095   };
16096   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16097
16098   // Finally xor with NumBits-1.
16099   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16100                    DAG.getConstant(NumBits - 1, dl, OpVT));
16101
16102   if (VT == MVT::i8)
16103     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16104   return Op;
16105 }
16106
16107 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16108   MVT VT = Op.getSimpleValueType();
16109   EVT OpVT = VT;
16110   unsigned NumBits = VT.getSizeInBits();
16111   SDLoc dl(Op);
16112
16113   Op = Op.getOperand(0);
16114   if (VT == MVT::i8) {
16115     // Zero extend to i32 since there is not an i8 bsr.
16116     OpVT = MVT::i32;
16117     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16118   }
16119
16120   // Issue a bsr (scan bits in reverse).
16121   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16122   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16123
16124   // And xor with NumBits-1.
16125   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16126                    DAG.getConstant(NumBits - 1, dl, OpVT));
16127
16128   if (VT == MVT::i8)
16129     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16130   return Op;
16131 }
16132
16133 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16134   MVT VT = Op.getSimpleValueType();
16135   unsigned NumBits = VT.getSizeInBits();
16136   SDLoc dl(Op);
16137   Op = Op.getOperand(0);
16138
16139   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16140   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16141   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16142
16143   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16144   SDValue Ops[] = {
16145     Op,
16146     DAG.getConstant(NumBits, dl, VT),
16147     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16148     Op.getValue(1)
16149   };
16150   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16151 }
16152
16153 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16154 // ones, and then concatenate the result back.
16155 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16156   MVT VT = Op.getSimpleValueType();
16157
16158   assert(VT.is256BitVector() && VT.isInteger() &&
16159          "Unsupported value type for operation");
16160
16161   unsigned NumElems = VT.getVectorNumElements();
16162   SDLoc dl(Op);
16163
16164   // Extract the LHS vectors
16165   SDValue LHS = Op.getOperand(0);
16166   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16167   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16168
16169   // Extract the RHS vectors
16170   SDValue RHS = Op.getOperand(1);
16171   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16172   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16173
16174   MVT EltVT = VT.getVectorElementType();
16175   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16176
16177   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16178                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16179                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16180 }
16181
16182 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16183   assert(Op.getSimpleValueType().is256BitVector() &&
16184          Op.getSimpleValueType().isInteger() &&
16185          "Only handle AVX 256-bit vector integer operation");
16186   return Lower256IntArith(Op, DAG);
16187 }
16188
16189 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16190   assert(Op.getSimpleValueType().is256BitVector() &&
16191          Op.getSimpleValueType().isInteger() &&
16192          "Only handle AVX 256-bit vector integer operation");
16193   return Lower256IntArith(Op, DAG);
16194 }
16195
16196 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16197                         SelectionDAG &DAG) {
16198   SDLoc dl(Op);
16199   MVT VT = Op.getSimpleValueType();
16200
16201   // Decompose 256-bit ops into smaller 128-bit ops.
16202   if (VT.is256BitVector() && !Subtarget->hasInt256())
16203     return Lower256IntArith(Op, DAG);
16204
16205   SDValue A = Op.getOperand(0);
16206   SDValue B = Op.getOperand(1);
16207
16208   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16209   // pairs, multiply and truncate.
16210   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16211     if (Subtarget->hasInt256()) {
16212       if (VT == MVT::v32i8) {
16213         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16214         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16215         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16216         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16217         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16218         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16219         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16220         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16221                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16222                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16223       }
16224
16225       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16226       return DAG.getNode(
16227           ISD::TRUNCATE, dl, VT,
16228           DAG.getNode(ISD::MUL, dl, ExVT,
16229                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16230                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16231     }
16232
16233     assert(VT == MVT::v16i8 &&
16234            "Pre-AVX2 support only supports v16i8 multiplication");
16235     MVT ExVT = MVT::v8i16;
16236
16237     // Extract the lo parts and sign extend to i16
16238     SDValue ALo, BLo;
16239     if (Subtarget->hasSSE41()) {
16240       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16241       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16242     } else {
16243       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16244                               -1, 4, -1, 5, -1, 6, -1, 7};
16245       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16246       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16247       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16248       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16249       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16250       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16251     }
16252
16253     // Extract the hi parts and sign extend to i16
16254     SDValue AHi, BHi;
16255     if (Subtarget->hasSSE41()) {
16256       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16257                               -1, -1, -1, -1, -1, -1, -1, -1};
16258       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16259       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16260       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16261       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16262     } else {
16263       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16264                               -1, 12, -1, 13, -1, 14, -1, 15};
16265       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16266       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16267       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16268       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16269       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16270       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16271     }
16272
16273     // Multiply, mask the lower 8bits of the lo/hi results and pack
16274     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16275     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16276     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16277     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16278     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16279   }
16280
16281   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16282   if (VT == MVT::v4i32) {
16283     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16284            "Should not custom lower when pmuldq is available!");
16285
16286     // Extract the odd parts.
16287     static const int UnpackMask[] = { 1, -1, 3, -1 };
16288     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16289     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16290
16291     // Multiply the even parts.
16292     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16293     // Now multiply odd parts.
16294     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16295
16296     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16297     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16298
16299     // Merge the two vectors back together with a shuffle. This expands into 2
16300     // shuffles.
16301     static const int ShufMask[] = { 0, 4, 2, 6 };
16302     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16303   }
16304
16305   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16306          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16307
16308   //  Ahi = psrlqi(a, 32);
16309   //  Bhi = psrlqi(b, 32);
16310   //
16311   //  AloBlo = pmuludq(a, b);
16312   //  AloBhi = pmuludq(a, Bhi);
16313   //  AhiBlo = pmuludq(Ahi, b);
16314
16315   //  AloBhi = psllqi(AloBhi, 32);
16316   //  AhiBlo = psllqi(AhiBlo, 32);
16317   //  return AloBlo + AloBhi + AhiBlo;
16318
16319   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16320   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16321
16322   // Bit cast to 32-bit vectors for MULUDQ
16323   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16324                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16325   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16326   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16327   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16328   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16329
16330   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16331   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16332   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16333
16334   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16335   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16336
16337   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16338   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16339 }
16340
16341 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16342   assert(Subtarget->isTargetWin64() && "Unexpected target");
16343   EVT VT = Op.getValueType();
16344   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16345          "Unexpected return type for lowering");
16346
16347   RTLIB::Libcall LC;
16348   bool isSigned;
16349   switch (Op->getOpcode()) {
16350   default: llvm_unreachable("Unexpected request for libcall!");
16351   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16352   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16353   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16354   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16355   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16356   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16357   }
16358
16359   SDLoc dl(Op);
16360   SDValue InChain = DAG.getEntryNode();
16361
16362   TargetLowering::ArgListTy Args;
16363   TargetLowering::ArgListEntry Entry;
16364   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16365     EVT ArgVT = Op->getOperand(i).getValueType();
16366     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16367            "Unexpected argument type for lowering");
16368     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16369     Entry.Node = StackPtr;
16370     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16371                            false, false, 16);
16372     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16373     Entry.Ty = PointerType::get(ArgTy,0);
16374     Entry.isSExt = false;
16375     Entry.isZExt = false;
16376     Args.push_back(Entry);
16377   }
16378
16379   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16380                                          getPointerTy());
16381
16382   TargetLowering::CallLoweringInfo CLI(DAG);
16383   CLI.setDebugLoc(dl).setChain(InChain)
16384     .setCallee(getLibcallCallingConv(LC),
16385                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16386                Callee, std::move(Args), 0)
16387     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16388
16389   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16390   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16391 }
16392
16393 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16394                              SelectionDAG &DAG) {
16395   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16396   EVT VT = Op0.getValueType();
16397   SDLoc dl(Op);
16398
16399   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16400          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16401
16402   // PMULxD operations multiply each even value (starting at 0) of LHS with
16403   // the related value of RHS and produce a widen result.
16404   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16405   // => <2 x i64> <ae|cg>
16406   //
16407   // In other word, to have all the results, we need to perform two PMULxD:
16408   // 1. one with the even values.
16409   // 2. one with the odd values.
16410   // To achieve #2, with need to place the odd values at an even position.
16411   //
16412   // Place the odd value at an even position (basically, shift all values 1
16413   // step to the left):
16414   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16415   // <a|b|c|d> => <b|undef|d|undef>
16416   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16417   // <e|f|g|h> => <f|undef|h|undef>
16418   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16419
16420   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16421   // ints.
16422   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16423   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16424   unsigned Opcode =
16425       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16426   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16427   // => <2 x i64> <ae|cg>
16428   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16429                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16430   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16431   // => <2 x i64> <bf|dh>
16432   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16433                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16434
16435   // Shuffle it back into the right order.
16436   SDValue Highs, Lows;
16437   if (VT == MVT::v8i32) {
16438     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16439     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16440     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16441     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16442   } else {
16443     const int HighMask[] = {1, 5, 3, 7};
16444     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16445     const int LowMask[] = {0, 4, 2, 6};
16446     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16447   }
16448
16449   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16450   // unsigned multiply.
16451   if (IsSigned && !Subtarget->hasSSE41()) {
16452     SDValue ShAmt =
16453         DAG.getConstant(31, dl,
16454                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16455     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16456                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16457     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16458                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16459
16460     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16461     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16462   }
16463
16464   // The first result of MUL_LOHI is actually the low value, followed by the
16465   // high value.
16466   SDValue Ops[] = {Lows, Highs};
16467   return DAG.getMergeValues(Ops, dl);
16468 }
16469
16470 // Return true if the requred (according to Opcode) shift-imm form is natively
16471 // supported by the Subtarget
16472 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16473                                         unsigned Opcode) {
16474   if (VT.getScalarSizeInBits() < 16)
16475     return false;
16476  
16477   if (VT.is512BitVector() &&
16478       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16479     return true;
16480
16481   bool LShift = VT.is128BitVector() || 
16482     (VT.is256BitVector() && Subtarget->hasInt256());
16483
16484   bool AShift = LShift && (Subtarget->hasVLX() ||
16485     (VT != MVT::v2i64 && VT != MVT::v4i64));
16486   return (Opcode == ISD::SRA) ? AShift : LShift;
16487 }
16488
16489 // The shift amount is a variable, but it is the same for all vector lanes.
16490 // These instrcutions are defined together with shift-immediate.
16491 static 
16492 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16493                                       unsigned Opcode) {
16494   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16495 }
16496
16497 // Return true if the requred (according to Opcode) variable-shift form is
16498 // natively supported by the Subtarget
16499 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16500                                     unsigned Opcode) {
16501
16502   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16503     return false;
16504
16505   // vXi16 supported only on AVX-512, BWI
16506   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16507     return false;
16508
16509   if (VT.is512BitVector() || Subtarget->hasVLX())
16510     return true;
16511
16512   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16513   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16514   return (Opcode == ISD::SRA) ? AShift : LShift;
16515 }
16516
16517 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16518                                          const X86Subtarget *Subtarget) {
16519   MVT VT = Op.getSimpleValueType();
16520   SDLoc dl(Op);
16521   SDValue R = Op.getOperand(0);
16522   SDValue Amt = Op.getOperand(1);
16523
16524   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16525     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16526
16527   // Optimize shl/srl/sra with constant shift amount.
16528   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16529     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16530       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16531
16532       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16533         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16534
16535       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16536         unsigned NumElts = VT.getVectorNumElements();
16537         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16538
16539         if (Op.getOpcode() == ISD::SHL) {
16540           // Make a large shift.
16541           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16542                                                    R, ShiftAmt, DAG);
16543           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16544           // Zero out the rightmost bits.
16545           SmallVector<SDValue, 32> V(
16546               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16547           return DAG.getNode(ISD::AND, dl, VT, SHL,
16548                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16549         }
16550         if (Op.getOpcode() == ISD::SRL) {
16551           // Make a large shift.
16552           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16553                                                    R, ShiftAmt, DAG);
16554           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16555           // Zero out the leftmost bits.
16556           SmallVector<SDValue, 32> V(
16557               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16558           return DAG.getNode(ISD::AND, dl, VT, SRL,
16559                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16560         }
16561         if (Op.getOpcode() == ISD::SRA) {
16562           if (ShiftAmt == 7) {
16563             // R s>> 7  ===  R s< 0
16564             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16565             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16566           }
16567
16568           // R s>> a === ((R u>> a) ^ m) - m
16569           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16570           SmallVector<SDValue, 32> V(NumElts,
16571                                      DAG.getConstant(128 >> ShiftAmt, dl,
16572                                                      MVT::i8));
16573           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16574           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16575           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16576           return Res;
16577         }
16578         llvm_unreachable("Unknown shift opcode.");
16579       }
16580     }
16581   }
16582
16583   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16584   if (!Subtarget->is64Bit() &&
16585       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16586       Amt.getOpcode() == ISD::BITCAST &&
16587       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16588     Amt = Amt.getOperand(0);
16589     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16590                      VT.getVectorNumElements();
16591     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16592     uint64_t ShiftAmt = 0;
16593     for (unsigned i = 0; i != Ratio; ++i) {
16594       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16595       if (!C)
16596         return SDValue();
16597       // 6 == Log2(64)
16598       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16599     }
16600     // Check remaining shift amounts.
16601     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16602       uint64_t ShAmt = 0;
16603       for (unsigned j = 0; j != Ratio; ++j) {
16604         ConstantSDNode *C =
16605           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16606         if (!C)
16607           return SDValue();
16608         // 6 == Log2(64)
16609         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16610       }
16611       if (ShAmt != ShiftAmt)
16612         return SDValue();
16613     }
16614     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16615   }
16616
16617   return SDValue();
16618 }
16619
16620 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16621                                         const X86Subtarget* Subtarget) {
16622   MVT VT = Op.getSimpleValueType();
16623   SDLoc dl(Op);
16624   SDValue R = Op.getOperand(0);
16625   SDValue Amt = Op.getOperand(1);
16626
16627   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16628     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16629
16630   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16631     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16632
16633   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16634     SDValue BaseShAmt;
16635     EVT EltVT = VT.getVectorElementType();
16636
16637     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16638       // Check if this build_vector node is doing a splat.
16639       // If so, then set BaseShAmt equal to the splat value.
16640       BaseShAmt = BV->getSplatValue();
16641       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16642         BaseShAmt = SDValue();
16643     } else {
16644       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16645         Amt = Amt.getOperand(0);
16646
16647       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16648       if (SVN && SVN->isSplat()) {
16649         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16650         SDValue InVec = Amt.getOperand(0);
16651         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16652           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16653                  "Unexpected shuffle index found!");
16654           BaseShAmt = InVec.getOperand(SplatIdx);
16655         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16656            if (ConstantSDNode *C =
16657                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16658              if (C->getZExtValue() == SplatIdx)
16659                BaseShAmt = InVec.getOperand(1);
16660            }
16661         }
16662
16663         if (!BaseShAmt)
16664           // Avoid introducing an extract element from a shuffle.
16665           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16666                                   DAG.getIntPtrConstant(SplatIdx, dl));
16667       }
16668     }
16669
16670     if (BaseShAmt.getNode()) {
16671       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16672       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16673         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16674       else if (EltVT.bitsLT(MVT::i32))
16675         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16676
16677       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16678     }
16679   }
16680
16681   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16682   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16683       Amt.getOpcode() == ISD::BITCAST &&
16684       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16685     Amt = Amt.getOperand(0);
16686     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16687                      VT.getVectorNumElements();
16688     std::vector<SDValue> Vals(Ratio);
16689     for (unsigned i = 0; i != Ratio; ++i)
16690       Vals[i] = Amt.getOperand(i);
16691     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16692       for (unsigned j = 0; j != Ratio; ++j)
16693         if (Vals[j] != Amt.getOperand(i + j))
16694           return SDValue();
16695     }
16696     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16697   }
16698   return SDValue();
16699 }
16700
16701 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16702                           SelectionDAG &DAG) {
16703   MVT VT = Op.getSimpleValueType();
16704   SDLoc dl(Op);
16705   SDValue R = Op.getOperand(0);
16706   SDValue Amt = Op.getOperand(1);
16707
16708   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16709   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16710
16711   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16712     return V;
16713
16714   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16715       return V;
16716
16717   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16718     return Op;
16719
16720   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16721   // shifts per-lane and then shuffle the partial results back together.
16722   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16723     // Splat the shift amounts so the scalar shifts above will catch it.
16724     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16725     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16726     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16727     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16728     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16729   }
16730
16731   // If possible, lower this packed shift into a vector multiply instead of
16732   // expanding it into a sequence of scalar shifts.
16733   // Do this only if the vector shift count is a constant build_vector.
16734   if (Op.getOpcode() == ISD::SHL &&
16735       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16736        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16737       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16738     SmallVector<SDValue, 8> Elts;
16739     EVT SVT = VT.getScalarType();
16740     unsigned SVTBits = SVT.getSizeInBits();
16741     const APInt &One = APInt(SVTBits, 1);
16742     unsigned NumElems = VT.getVectorNumElements();
16743
16744     for (unsigned i=0; i !=NumElems; ++i) {
16745       SDValue Op = Amt->getOperand(i);
16746       if (Op->getOpcode() == ISD::UNDEF) {
16747         Elts.push_back(Op);
16748         continue;
16749       }
16750
16751       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16752       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16753       uint64_t ShAmt = C.getZExtValue();
16754       if (ShAmt >= SVTBits) {
16755         Elts.push_back(DAG.getUNDEF(SVT));
16756         continue;
16757       }
16758       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16759     }
16760     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16761     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16762   }
16763
16764   // Lower SHL with variable shift amount.
16765   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16766     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16767
16768     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16769                      DAG.getConstant(0x3f800000U, dl, VT));
16770     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16771     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16772     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16773   }
16774
16775   // If possible, lower this shift as a sequence of two shifts by
16776   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16777   // Example:
16778   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16779   //
16780   // Could be rewritten as:
16781   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16782   //
16783   // The advantage is that the two shifts from the example would be
16784   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16785   // the vector shift into four scalar shifts plus four pairs of vector
16786   // insert/extract.
16787   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16788       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16789     unsigned TargetOpcode = X86ISD::MOVSS;
16790     bool CanBeSimplified;
16791     // The splat value for the first packed shift (the 'X' from the example).
16792     SDValue Amt1 = Amt->getOperand(0);
16793     // The splat value for the second packed shift (the 'Y' from the example).
16794     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16795                                         Amt->getOperand(2);
16796
16797     // See if it is possible to replace this node with a sequence of
16798     // two shifts followed by a MOVSS/MOVSD
16799     if (VT == MVT::v4i32) {
16800       // Check if it is legal to use a MOVSS.
16801       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16802                         Amt2 == Amt->getOperand(3);
16803       if (!CanBeSimplified) {
16804         // Otherwise, check if we can still simplify this node using a MOVSD.
16805         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16806                           Amt->getOperand(2) == Amt->getOperand(3);
16807         TargetOpcode = X86ISD::MOVSD;
16808         Amt2 = Amt->getOperand(2);
16809       }
16810     } else {
16811       // Do similar checks for the case where the machine value type
16812       // is MVT::v8i16.
16813       CanBeSimplified = Amt1 == Amt->getOperand(1);
16814       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16815         CanBeSimplified = Amt2 == Amt->getOperand(i);
16816
16817       if (!CanBeSimplified) {
16818         TargetOpcode = X86ISD::MOVSD;
16819         CanBeSimplified = true;
16820         Amt2 = Amt->getOperand(4);
16821         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16822           CanBeSimplified = Amt1 == Amt->getOperand(i);
16823         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16824           CanBeSimplified = Amt2 == Amt->getOperand(j);
16825       }
16826     }
16827
16828     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16829         isa<ConstantSDNode>(Amt2)) {
16830       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16831       EVT CastVT = MVT::v4i32;
16832       SDValue Splat1 =
16833         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16834       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16835       SDValue Splat2 =
16836         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16837       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16838       if (TargetOpcode == X86ISD::MOVSD)
16839         CastVT = MVT::v2i64;
16840       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16841       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16842       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16843                                             BitCast1, DAG);
16844       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16845     }
16846   }
16847
16848   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16849     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16850     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16851
16852     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16853     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16854     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16855
16856     // r = VSELECT(r, shl(r, 4), a);
16857     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16858     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16859
16860     // a += a
16861     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16862     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16863     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16864
16865     // r = VSELECT(r, shl(r, 2), a);
16866     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16867     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16868
16869     // a += a
16870     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16871     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16872     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16873
16874     // return VSELECT(r, r+r, a);
16875     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16876                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16877     return R;
16878   }
16879
16880   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16881   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16882   // solution better.
16883   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16884     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16885     unsigned ExtOpc =
16886         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16887     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16888     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16889     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16890                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16891   }
16892
16893   // Decompose 256-bit shifts into smaller 128-bit shifts.
16894   if (VT.is256BitVector()) {
16895     unsigned NumElems = VT.getVectorNumElements();
16896     MVT EltVT = VT.getVectorElementType();
16897     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16898
16899     // Extract the two vectors
16900     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16901     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16902
16903     // Recreate the shift amount vectors
16904     SDValue Amt1, Amt2;
16905     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16906       // Constant shift amount
16907       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16908       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16909       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16910
16911       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16912       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16913     } else {
16914       // Variable shift amount
16915       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16916       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16917     }
16918
16919     // Issue new vector shifts for the smaller types
16920     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16921     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16922
16923     // Concatenate the result back
16924     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16925   }
16926
16927   return SDValue();
16928 }
16929
16930 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16931   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16932   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16933   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16934   // has only one use.
16935   SDNode *N = Op.getNode();
16936   SDValue LHS = N->getOperand(0);
16937   SDValue RHS = N->getOperand(1);
16938   unsigned BaseOp = 0;
16939   unsigned Cond = 0;
16940   SDLoc DL(Op);
16941   switch (Op.getOpcode()) {
16942   default: llvm_unreachable("Unknown ovf instruction!");
16943   case ISD::SADDO:
16944     // A subtract of one will be selected as a INC. Note that INC doesn't
16945     // set CF, so we can't do this for UADDO.
16946     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16947       if (C->isOne()) {
16948         BaseOp = X86ISD::INC;
16949         Cond = X86::COND_O;
16950         break;
16951       }
16952     BaseOp = X86ISD::ADD;
16953     Cond = X86::COND_O;
16954     break;
16955   case ISD::UADDO:
16956     BaseOp = X86ISD::ADD;
16957     Cond = X86::COND_B;
16958     break;
16959   case ISD::SSUBO:
16960     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16961     // set CF, so we can't do this for USUBO.
16962     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16963       if (C->isOne()) {
16964         BaseOp = X86ISD::DEC;
16965         Cond = X86::COND_O;
16966         break;
16967       }
16968     BaseOp = X86ISD::SUB;
16969     Cond = X86::COND_O;
16970     break;
16971   case ISD::USUBO:
16972     BaseOp = X86ISD::SUB;
16973     Cond = X86::COND_B;
16974     break;
16975   case ISD::SMULO:
16976     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16977     Cond = X86::COND_O;
16978     break;
16979   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16980     if (N->getValueType(0) == MVT::i8) {
16981       BaseOp = X86ISD::UMUL8;
16982       Cond = X86::COND_O;
16983       break;
16984     }
16985     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16986                                  MVT::i32);
16987     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16988
16989     SDValue SetCC =
16990       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16991                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16992                   SDValue(Sum.getNode(), 2));
16993
16994     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16995   }
16996   }
16997
16998   // Also sets EFLAGS.
16999   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17000   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17001
17002   SDValue SetCC =
17003     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17004                 DAG.getConstant(Cond, DL, MVT::i32),
17005                 SDValue(Sum.getNode(), 1));
17006
17007   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17008 }
17009
17010 /// Returns true if the operand type is exactly twice the native width, and
17011 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17012 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17013 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17014 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17015   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17016
17017   if (OpWidth == 64)
17018     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17019   else if (OpWidth == 128)
17020     return Subtarget->hasCmpxchg16b();
17021   else
17022     return false;
17023 }
17024
17025 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17026   return needsCmpXchgNb(SI->getValueOperand()->getType());
17027 }
17028
17029 // Note: this turns large loads into lock cmpxchg8b/16b.
17030 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17031 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17032   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17033   return needsCmpXchgNb(PTy->getElementType());
17034 }
17035
17036 TargetLoweringBase::AtomicRMWExpansionKind
17037 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17038   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17039   const Type *MemType = AI->getType();
17040
17041   // If the operand is too big, we must see if cmpxchg8/16b is available
17042   // and default to library calls otherwise.
17043   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17044     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17045                                    : AtomicRMWExpansionKind::None;
17046   }
17047
17048   AtomicRMWInst::BinOp Op = AI->getOperation();
17049   switch (Op) {
17050   default:
17051     llvm_unreachable("Unknown atomic operation");
17052   case AtomicRMWInst::Xchg:
17053   case AtomicRMWInst::Add:
17054   case AtomicRMWInst::Sub:
17055     // It's better to use xadd, xsub or xchg for these in all cases.
17056     return AtomicRMWExpansionKind::None;
17057   case AtomicRMWInst::Or:
17058   case AtomicRMWInst::And:
17059   case AtomicRMWInst::Xor:
17060     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17061     // prefix to a normal instruction for these operations.
17062     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17063                             : AtomicRMWExpansionKind::None;
17064   case AtomicRMWInst::Nand:
17065   case AtomicRMWInst::Max:
17066   case AtomicRMWInst::Min:
17067   case AtomicRMWInst::UMax:
17068   case AtomicRMWInst::UMin:
17069     // These always require a non-trivial set of data operations on x86. We must
17070     // use a cmpxchg loop.
17071     return AtomicRMWExpansionKind::CmpXChg;
17072   }
17073 }
17074
17075 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17076   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17077   // no-sse2). There isn't any reason to disable it if the target processor
17078   // supports it.
17079   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17080 }
17081
17082 LoadInst *
17083 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17084   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17085   const Type *MemType = AI->getType();
17086   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17087   // there is no benefit in turning such RMWs into loads, and it is actually
17088   // harmful as it introduces a mfence.
17089   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17090     return nullptr;
17091
17092   auto Builder = IRBuilder<>(AI);
17093   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17094   auto SynchScope = AI->getSynchScope();
17095   // We must restrict the ordering to avoid generating loads with Release or
17096   // ReleaseAcquire orderings.
17097   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17098   auto Ptr = AI->getPointerOperand();
17099
17100   // Before the load we need a fence. Here is an example lifted from
17101   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17102   // is required:
17103   // Thread 0:
17104   //   x.store(1, relaxed);
17105   //   r1 = y.fetch_add(0, release);
17106   // Thread 1:
17107   //   y.fetch_add(42, acquire);
17108   //   r2 = x.load(relaxed);
17109   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17110   // lowered to just a load without a fence. A mfence flushes the store buffer,
17111   // making the optimization clearly correct.
17112   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17113   // otherwise, we might be able to be more agressive on relaxed idempotent
17114   // rmw. In practice, they do not look useful, so we don't try to be
17115   // especially clever.
17116   if (SynchScope == SingleThread)
17117     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17118     // the IR level, so we must wrap it in an intrinsic.
17119     return nullptr;
17120
17121   if (!hasMFENCE(*Subtarget))
17122     // FIXME: it might make sense to use a locked operation here but on a
17123     // different cache-line to prevent cache-line bouncing. In practice it
17124     // is probably a small win, and x86 processors without mfence are rare
17125     // enough that we do not bother.
17126     return nullptr;
17127
17128   Function *MFence =
17129       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17130   Builder.CreateCall(MFence, {});
17131
17132   // Finally we can emit the atomic load.
17133   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17134           AI->getType()->getPrimitiveSizeInBits());
17135   Loaded->setAtomic(Order, SynchScope);
17136   AI->replaceAllUsesWith(Loaded);
17137   AI->eraseFromParent();
17138   return Loaded;
17139 }
17140
17141 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17142                                  SelectionDAG &DAG) {
17143   SDLoc dl(Op);
17144   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17145     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17146   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17147     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17148
17149   // The only fence that needs an instruction is a sequentially-consistent
17150   // cross-thread fence.
17151   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17152     if (hasMFENCE(*Subtarget))
17153       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17154
17155     SDValue Chain = Op.getOperand(0);
17156     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17157     SDValue Ops[] = {
17158       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17159       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17160       DAG.getRegister(0, MVT::i32),            // Index
17161       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17162       DAG.getRegister(0, MVT::i32),            // Segment.
17163       Zero,
17164       Chain
17165     };
17166     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17167     return SDValue(Res, 0);
17168   }
17169
17170   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17171   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17172 }
17173
17174 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17175                              SelectionDAG &DAG) {
17176   MVT T = Op.getSimpleValueType();
17177   SDLoc DL(Op);
17178   unsigned Reg = 0;
17179   unsigned size = 0;
17180   switch(T.SimpleTy) {
17181   default: llvm_unreachable("Invalid value type!");
17182   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17183   case MVT::i16: Reg = X86::AX;  size = 2; break;
17184   case MVT::i32: Reg = X86::EAX; size = 4; break;
17185   case MVT::i64:
17186     assert(Subtarget->is64Bit() && "Node not type legal!");
17187     Reg = X86::RAX; size = 8;
17188     break;
17189   }
17190   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17191                                   Op.getOperand(2), SDValue());
17192   SDValue Ops[] = { cpIn.getValue(0),
17193                     Op.getOperand(1),
17194                     Op.getOperand(3),
17195                     DAG.getTargetConstant(size, DL, MVT::i8),
17196                     cpIn.getValue(1) };
17197   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17198   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17199   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17200                                            Ops, T, MMO);
17201
17202   SDValue cpOut =
17203     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17204   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17205                                       MVT::i32, cpOut.getValue(2));
17206   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17207                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17208                                 EFLAGS);
17209
17210   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17211   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17212   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17213   return SDValue();
17214 }
17215
17216 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17217                             SelectionDAG &DAG) {
17218   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17219   MVT DstVT = Op.getSimpleValueType();
17220
17221   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17222     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17223     if (DstVT != MVT::f64)
17224       // This conversion needs to be expanded.
17225       return SDValue();
17226
17227     SDValue InVec = Op->getOperand(0);
17228     SDLoc dl(Op);
17229     unsigned NumElts = SrcVT.getVectorNumElements();
17230     EVT SVT = SrcVT.getVectorElementType();
17231
17232     // Widen the vector in input in the case of MVT::v2i32.
17233     // Example: from MVT::v2i32 to MVT::v4i32.
17234     SmallVector<SDValue, 16> Elts;
17235     for (unsigned i = 0, e = NumElts; i != e; ++i)
17236       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17237                                  DAG.getIntPtrConstant(i, dl)));
17238
17239     // Explicitly mark the extra elements as Undef.
17240     Elts.append(NumElts, DAG.getUNDEF(SVT));
17241
17242     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17243     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17244     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17245     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17246                        DAG.getIntPtrConstant(0, dl));
17247   }
17248
17249   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17250          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17251   assert((DstVT == MVT::i64 ||
17252           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17253          "Unexpected custom BITCAST");
17254   // i64 <=> MMX conversions are Legal.
17255   if (SrcVT==MVT::i64 && DstVT.isVector())
17256     return Op;
17257   if (DstVT==MVT::i64 && SrcVT.isVector())
17258     return Op;
17259   // MMX <=> MMX conversions are Legal.
17260   if (SrcVT.isVector() && DstVT.isVector())
17261     return Op;
17262   // All other conversions need to be expanded.
17263   return SDValue();
17264 }
17265
17266 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17267                           SelectionDAG &DAG) {
17268   SDNode *Node = Op.getNode();
17269   SDLoc dl(Node);
17270
17271   Op = Op.getOperand(0);
17272   EVT VT = Op.getValueType();
17273   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17274          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17275
17276   unsigned NumElts = VT.getVectorNumElements();
17277   EVT EltVT = VT.getVectorElementType();
17278   unsigned Len = EltVT.getSizeInBits();
17279
17280   // This is the vectorized version of the "best" algorithm from
17281   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17282   // with a minor tweak to use a series of adds + shifts instead of vector
17283   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17284   //
17285   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17286   //  v8i32 => Always profitable
17287   //
17288   // FIXME: There a couple of possible improvements:
17289   //
17290   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17291   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17292   //
17293   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17294          "CTPOP not implemented for this vector element type.");
17295
17296   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17297   // extra legalization.
17298   bool NeedsBitcast = EltVT == MVT::i32;
17299   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17300
17301   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17302                                   EltVT);
17303   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17304                                   EltVT);
17305   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17306                                   EltVT);
17307
17308   // v = v - ((v >> 1) & 0x55555555...)
17309   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17310   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17311   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17312   if (NeedsBitcast)
17313     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17314
17315   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17316   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17317   if (NeedsBitcast)
17318     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17319
17320   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17321   if (VT != And.getValueType())
17322     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17323   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17324
17325   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17326   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17327   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17328   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17329   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17330
17331   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17332   if (NeedsBitcast) {
17333     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17334     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17335     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17336   }
17337
17338   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17339   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17340   if (VT != AndRHS.getValueType()) {
17341     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17342     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17343   }
17344   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17345
17346   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17347   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17348   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17349   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17350   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17351
17352   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17353   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17354   if (NeedsBitcast) {
17355     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17356     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17357   }
17358   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17359   if (VT != And.getValueType())
17360     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17361
17362   // The algorithm mentioned above uses:
17363   //    v = (v * 0x01010101...) >> (Len - 8)
17364   //
17365   // Change it to use vector adds + vector shifts which yield faster results on
17366   // Haswell than using vector integer multiplication.
17367   //
17368   // For i32 elements:
17369   //    v = v + (v >> 8)
17370   //    v = v + (v >> 16)
17371   //
17372   // For i64 elements:
17373   //    v = v + (v >> 8)
17374   //    v = v + (v >> 16)
17375   //    v = v + (v >> 32)
17376   //
17377   Add = And;
17378   SmallVector<SDValue, 8> Csts;
17379   for (unsigned i = 8; i <= Len/2; i *= 2) {
17380     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17381     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17382     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17383     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17384     Csts.clear();
17385   }
17386
17387   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17388   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17389                                   EltVT);
17390   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17391   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17392   if (NeedsBitcast) {
17393     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17394     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17395   }
17396   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17397   if (VT != And.getValueType())
17398     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17399
17400   return And;
17401 }
17402
17403 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17404   SDNode *Node = Op.getNode();
17405   SDLoc dl(Node);
17406   EVT T = Node->getValueType(0);
17407   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17408                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17409   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17410                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17411                        Node->getOperand(0),
17412                        Node->getOperand(1), negOp,
17413                        cast<AtomicSDNode>(Node)->getMemOperand(),
17414                        cast<AtomicSDNode>(Node)->getOrdering(),
17415                        cast<AtomicSDNode>(Node)->getSynchScope());
17416 }
17417
17418 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17419   SDNode *Node = Op.getNode();
17420   SDLoc dl(Node);
17421   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17422
17423   // Convert seq_cst store -> xchg
17424   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17425   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17426   //        (The only way to get a 16-byte store is cmpxchg16b)
17427   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17428   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17429       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17430     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17431                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17432                                  Node->getOperand(0),
17433                                  Node->getOperand(1), Node->getOperand(2),
17434                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17435                                  cast<AtomicSDNode>(Node)->getOrdering(),
17436                                  cast<AtomicSDNode>(Node)->getSynchScope());
17437     return Swap.getValue(1);
17438   }
17439   // Other atomic stores have a simple pattern.
17440   return Op;
17441 }
17442
17443 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17444   EVT VT = Op.getNode()->getSimpleValueType(0);
17445
17446   // Let legalize expand this if it isn't a legal type yet.
17447   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17448     return SDValue();
17449
17450   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17451
17452   unsigned Opc;
17453   bool ExtraOp = false;
17454   switch (Op.getOpcode()) {
17455   default: llvm_unreachable("Invalid code");
17456   case ISD::ADDC: Opc = X86ISD::ADD; break;
17457   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17458   case ISD::SUBC: Opc = X86ISD::SUB; break;
17459   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17460   }
17461
17462   if (!ExtraOp)
17463     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17464                        Op.getOperand(1));
17465   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17466                      Op.getOperand(1), Op.getOperand(2));
17467 }
17468
17469 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17470                             SelectionDAG &DAG) {
17471   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17472
17473   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17474   // which returns the values as { float, float } (in XMM0) or
17475   // { double, double } (which is returned in XMM0, XMM1).
17476   SDLoc dl(Op);
17477   SDValue Arg = Op.getOperand(0);
17478   EVT ArgVT = Arg.getValueType();
17479   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17480
17481   TargetLowering::ArgListTy Args;
17482   TargetLowering::ArgListEntry Entry;
17483
17484   Entry.Node = Arg;
17485   Entry.Ty = ArgTy;
17486   Entry.isSExt = false;
17487   Entry.isZExt = false;
17488   Args.push_back(Entry);
17489
17490   bool isF64 = ArgVT == MVT::f64;
17491   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17492   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17493   // the results are returned via SRet in memory.
17494   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17495   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17496   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17497
17498   Type *RetTy = isF64
17499     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17500     : (Type*)VectorType::get(ArgTy, 4);
17501
17502   TargetLowering::CallLoweringInfo CLI(DAG);
17503   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17504     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17505
17506   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17507
17508   if (isF64)
17509     // Returned in xmm0 and xmm1.
17510     return CallResult.first;
17511
17512   // Returned in bits 0:31 and 32:64 xmm0.
17513   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17514                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17515   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17516                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17517   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17518   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17519 }
17520
17521 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17522                              SelectionDAG &DAG) {
17523   assert(Subtarget->hasAVX512() &&
17524          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17525
17526   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17527   EVT VT = N->getValue().getValueType();
17528   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17529   SDLoc dl(Op);
17530
17531   // X86 scatter kills mask register, so its type should be added to
17532   // the list of return values
17533   if (N->getNumValues() == 1) {
17534     SDValue Index = N->getIndex();
17535     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17536         !Index.getValueType().is512BitVector())
17537       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17538
17539     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17540     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17541                       N->getOperand(3), Index };
17542
17543     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17544     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17545     return SDValue(NewScatter.getNode(), 0);
17546   }
17547   return Op;
17548 }
17549
17550 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17551                             SelectionDAG &DAG) {
17552   assert(Subtarget->hasAVX512() &&
17553          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17554
17555   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17556   EVT VT = Op.getValueType();
17557   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17558   SDLoc dl(Op);
17559
17560   SDValue Index = N->getIndex();
17561   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17562       !Index.getValueType().is512BitVector()) {
17563     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17564     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17565                       N->getOperand(3), Index };
17566     DAG.UpdateNodeOperands(N, Ops);
17567   }
17568   return Op;
17569 }
17570
17571 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17572                                                     SelectionDAG &DAG) const {
17573   // TODO: Eventually, the lowering of these nodes should be informed by or
17574   // deferred to the GC strategy for the function in which they appear. For
17575   // now, however, they must be lowered to something. Since they are logically
17576   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17577   // require special handling for these nodes), lower them as literal NOOPs for
17578   // the time being.
17579   SmallVector<SDValue, 2> Ops;
17580
17581   Ops.push_back(Op.getOperand(0));
17582   if (Op->getGluedNode())
17583     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17584
17585   SDLoc OpDL(Op);
17586   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17587   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17588
17589   return NOOP;
17590 }
17591
17592 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17593                                                   SelectionDAG &DAG) const {
17594   // TODO: Eventually, the lowering of these nodes should be informed by or
17595   // deferred to the GC strategy for the function in which they appear. For
17596   // now, however, they must be lowered to something. Since they are logically
17597   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17598   // require special handling for these nodes), lower them as literal NOOPs for
17599   // the time being.
17600   SmallVector<SDValue, 2> Ops;
17601
17602   Ops.push_back(Op.getOperand(0));
17603   if (Op->getGluedNode())
17604     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17605
17606   SDLoc OpDL(Op);
17607   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17608   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17609
17610   return NOOP;
17611 }
17612
17613 /// LowerOperation - Provide custom lowering hooks for some operations.
17614 ///
17615 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17616   switch (Op.getOpcode()) {
17617   default: llvm_unreachable("Should not custom lower this!");
17618   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17619   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17620     return LowerCMP_SWAP(Op, Subtarget, DAG);
17621   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17622   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17623   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17624   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17625   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17626   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17627   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17628   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17629   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17630   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17631   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17632   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17633   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17634   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17635   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17636   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17637   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17638   case ISD::SHL_PARTS:
17639   case ISD::SRA_PARTS:
17640   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17641   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17642   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17643   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17644   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17645   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17646   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17647   case ISD::SIGN_EXTEND_VECTOR_INREG:
17648     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
17649   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17650   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17651   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17652   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17653   case ISD::FABS:
17654   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17655   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17656   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17657   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17658   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17659   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17660   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17661   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17662   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17663   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17664   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17665   case ISD::INTRINSIC_VOID:
17666   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17667   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17668   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17669   case ISD::FRAME_TO_ARGS_OFFSET:
17670                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17671   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17672   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17673   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17674   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17675   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17676   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17677   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17678   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17679   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17680   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17681   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17682   case ISD::UMUL_LOHI:
17683   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17684   case ISD::SRA:
17685   case ISD::SRL:
17686   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17687   case ISD::SADDO:
17688   case ISD::UADDO:
17689   case ISD::SSUBO:
17690   case ISD::USUBO:
17691   case ISD::SMULO:
17692   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17693   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17694   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17695   case ISD::ADDC:
17696   case ISD::ADDE:
17697   case ISD::SUBC:
17698   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17699   case ISD::ADD:                return LowerADD(Op, DAG);
17700   case ISD::SUB:                return LowerSUB(Op, DAG);
17701   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17702   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17703   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17704   case ISD::GC_TRANSITION_START:
17705                                 return LowerGC_TRANSITION_START(Op, DAG);
17706   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17707   }
17708 }
17709
17710 /// ReplaceNodeResults - Replace a node with an illegal result type
17711 /// with a new node built out of custom code.
17712 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17713                                            SmallVectorImpl<SDValue>&Results,
17714                                            SelectionDAG &DAG) const {
17715   SDLoc dl(N);
17716   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17717   switch (N->getOpcode()) {
17718   default:
17719     llvm_unreachable("Do not know how to custom type legalize this operation!");
17720   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17721   case X86ISD::FMINC:
17722   case X86ISD::FMIN:
17723   case X86ISD::FMAXC:
17724   case X86ISD::FMAX: {
17725     EVT VT = N->getValueType(0);
17726     if (VT != MVT::v2f32)
17727       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17728     SDValue UNDEF = DAG.getUNDEF(VT);
17729     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17730                               N->getOperand(0), UNDEF);
17731     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17732                               N->getOperand(1), UNDEF);
17733     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17734     return;
17735   }
17736   case ISD::SIGN_EXTEND_INREG:
17737   case ISD::ADDC:
17738   case ISD::ADDE:
17739   case ISD::SUBC:
17740   case ISD::SUBE:
17741     // We don't want to expand or promote these.
17742     return;
17743   case ISD::SDIV:
17744   case ISD::UDIV:
17745   case ISD::SREM:
17746   case ISD::UREM:
17747   case ISD::SDIVREM:
17748   case ISD::UDIVREM: {
17749     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17750     Results.push_back(V);
17751     return;
17752   }
17753   case ISD::FP_TO_SINT:
17754     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17755     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17756     if (N->getOperand(0).getValueType() == MVT::f16)
17757       break;
17758     // fallthrough
17759   case ISD::FP_TO_UINT: {
17760     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17761
17762     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17763       return;
17764
17765     std::pair<SDValue,SDValue> Vals =
17766         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17767     SDValue FIST = Vals.first, StackSlot = Vals.second;
17768     if (FIST.getNode()) {
17769       EVT VT = N->getValueType(0);
17770       // Return a load from the stack slot.
17771       if (StackSlot.getNode())
17772         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17773                                       MachinePointerInfo(),
17774                                       false, false, false, 0));
17775       else
17776         Results.push_back(FIST);
17777     }
17778     return;
17779   }
17780   case ISD::UINT_TO_FP: {
17781     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17782     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17783         N->getValueType(0) != MVT::v2f32)
17784       return;
17785     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17786                                  N->getOperand(0));
17787     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17788                                      MVT::f64);
17789     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17790     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17791                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17792     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17793     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17794     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17795     return;
17796   }
17797   case ISD::FP_ROUND: {
17798     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17799         return;
17800     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17801     Results.push_back(V);
17802     return;
17803   }
17804   case ISD::FP_EXTEND: {
17805     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17806     // No other ValueType for FP_EXTEND should reach this point.
17807     assert(N->getValueType(0) == MVT::v2f32 &&
17808            "Do not know how to legalize this Node");
17809     return;
17810   }
17811   case ISD::INTRINSIC_W_CHAIN: {
17812     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17813     switch (IntNo) {
17814     default : llvm_unreachable("Do not know how to custom type "
17815                                "legalize this intrinsic operation!");
17816     case Intrinsic::x86_rdtsc:
17817       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17818                                      Results);
17819     case Intrinsic::x86_rdtscp:
17820       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17821                                      Results);
17822     case Intrinsic::x86_rdpmc:
17823       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17824     }
17825   }
17826   case ISD::READCYCLECOUNTER: {
17827     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17828                                    Results);
17829   }
17830   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17831     EVT T = N->getValueType(0);
17832     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17833     bool Regs64bit = T == MVT::i128;
17834     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17835     SDValue cpInL, cpInH;
17836     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17837                         DAG.getConstant(0, dl, HalfT));
17838     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17839                         DAG.getConstant(1, dl, HalfT));
17840     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17841                              Regs64bit ? X86::RAX : X86::EAX,
17842                              cpInL, SDValue());
17843     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17844                              Regs64bit ? X86::RDX : X86::EDX,
17845                              cpInH, cpInL.getValue(1));
17846     SDValue swapInL, swapInH;
17847     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17848                           DAG.getConstant(0, dl, HalfT));
17849     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17850                           DAG.getConstant(1, dl, HalfT));
17851     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17852                                Regs64bit ? X86::RBX : X86::EBX,
17853                                swapInL, cpInH.getValue(1));
17854     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17855                                Regs64bit ? X86::RCX : X86::ECX,
17856                                swapInH, swapInL.getValue(1));
17857     SDValue Ops[] = { swapInH.getValue(0),
17858                       N->getOperand(1),
17859                       swapInH.getValue(1) };
17860     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17861     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17862     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17863                                   X86ISD::LCMPXCHG8_DAG;
17864     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17865     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17866                                         Regs64bit ? X86::RAX : X86::EAX,
17867                                         HalfT, Result.getValue(1));
17868     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17869                                         Regs64bit ? X86::RDX : X86::EDX,
17870                                         HalfT, cpOutL.getValue(2));
17871     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17872
17873     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17874                                         MVT::i32, cpOutH.getValue(2));
17875     SDValue Success =
17876         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17877                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17878     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17879
17880     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17881     Results.push_back(Success);
17882     Results.push_back(EFLAGS.getValue(1));
17883     return;
17884   }
17885   case ISD::ATOMIC_SWAP:
17886   case ISD::ATOMIC_LOAD_ADD:
17887   case ISD::ATOMIC_LOAD_SUB:
17888   case ISD::ATOMIC_LOAD_AND:
17889   case ISD::ATOMIC_LOAD_OR:
17890   case ISD::ATOMIC_LOAD_XOR:
17891   case ISD::ATOMIC_LOAD_NAND:
17892   case ISD::ATOMIC_LOAD_MIN:
17893   case ISD::ATOMIC_LOAD_MAX:
17894   case ISD::ATOMIC_LOAD_UMIN:
17895   case ISD::ATOMIC_LOAD_UMAX:
17896   case ISD::ATOMIC_LOAD: {
17897     // Delegate to generic TypeLegalization. Situations we can really handle
17898     // should have already been dealt with by AtomicExpandPass.cpp.
17899     break;
17900   }
17901   case ISD::BITCAST: {
17902     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17903     EVT DstVT = N->getValueType(0);
17904     EVT SrcVT = N->getOperand(0)->getValueType(0);
17905
17906     if (SrcVT != MVT::f64 ||
17907         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17908       return;
17909
17910     unsigned NumElts = DstVT.getVectorNumElements();
17911     EVT SVT = DstVT.getVectorElementType();
17912     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17913     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17914                                    MVT::v2f64, N->getOperand(0));
17915     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17916
17917     if (ExperimentalVectorWideningLegalization) {
17918       // If we are legalizing vectors by widening, we already have the desired
17919       // legal vector type, just return it.
17920       Results.push_back(ToVecInt);
17921       return;
17922     }
17923
17924     SmallVector<SDValue, 8> Elts;
17925     for (unsigned i = 0, e = NumElts; i != e; ++i)
17926       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17927                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17928
17929     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17930   }
17931   }
17932 }
17933
17934 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17935   switch ((X86ISD::NodeType)Opcode) {
17936   case X86ISD::FIRST_NUMBER:       break;
17937   case X86ISD::BSF:                return "X86ISD::BSF";
17938   case X86ISD::BSR:                return "X86ISD::BSR";
17939   case X86ISD::SHLD:               return "X86ISD::SHLD";
17940   case X86ISD::SHRD:               return "X86ISD::SHRD";
17941   case X86ISD::FAND:               return "X86ISD::FAND";
17942   case X86ISD::FANDN:              return "X86ISD::FANDN";
17943   case X86ISD::FOR:                return "X86ISD::FOR";
17944   case X86ISD::FXOR:               return "X86ISD::FXOR";
17945   case X86ISD::FSRL:               return "X86ISD::FSRL";
17946   case X86ISD::FILD:               return "X86ISD::FILD";
17947   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17948   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17949   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17950   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17951   case X86ISD::FLD:                return "X86ISD::FLD";
17952   case X86ISD::FST:                return "X86ISD::FST";
17953   case X86ISD::CALL:               return "X86ISD::CALL";
17954   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17955   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17956   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17957   case X86ISD::BT:                 return "X86ISD::BT";
17958   case X86ISD::CMP:                return "X86ISD::CMP";
17959   case X86ISD::COMI:               return "X86ISD::COMI";
17960   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17961   case X86ISD::CMPM:               return "X86ISD::CMPM";
17962   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17963   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17964   case X86ISD::SETCC:              return "X86ISD::SETCC";
17965   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17966   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17967   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17968   case X86ISD::CMOV:               return "X86ISD::CMOV";
17969   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17970   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17971   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17972   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17973   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17974   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17975   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17976   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17977   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17978   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17979   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17980   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17981   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17982   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17983   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17984   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17985   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17986   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17987   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17988   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17989   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17990   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17991   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17992   case X86ISD::HADD:               return "X86ISD::HADD";
17993   case X86ISD::HSUB:               return "X86ISD::HSUB";
17994   case X86ISD::FHADD:              return "X86ISD::FHADD";
17995   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17996   case X86ISD::UMAX:               return "X86ISD::UMAX";
17997   case X86ISD::UMIN:               return "X86ISD::UMIN";
17998   case X86ISD::SMAX:               return "X86ISD::SMAX";
17999   case X86ISD::SMIN:               return "X86ISD::SMIN";
18000   case X86ISD::FMAX:               return "X86ISD::FMAX";
18001   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18002   case X86ISD::FMIN:               return "X86ISD::FMIN";
18003   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18004   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18005   case X86ISD::FMINC:              return "X86ISD::FMINC";
18006   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18007   case X86ISD::FRCP:               return "X86ISD::FRCP";
18008   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18009   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18010   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18011   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18012   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18013   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18014   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18015   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18016   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18017   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18018   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18019   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18020   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18021   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18022   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18023   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18024   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18025   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18026   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18027   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18028   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18029   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18030   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18031   case X86ISD::VSHL:               return "X86ISD::VSHL";
18032   case X86ISD::VSRL:               return "X86ISD::VSRL";
18033   case X86ISD::VSRA:               return "X86ISD::VSRA";
18034   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18035   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18036   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18037   case X86ISD::CMPP:               return "X86ISD::CMPP";
18038   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18039   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18040   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18041   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18042   case X86ISD::ADD:                return "X86ISD::ADD";
18043   case X86ISD::SUB:                return "X86ISD::SUB";
18044   case X86ISD::ADC:                return "X86ISD::ADC";
18045   case X86ISD::SBB:                return "X86ISD::SBB";
18046   case X86ISD::SMUL:               return "X86ISD::SMUL";
18047   case X86ISD::UMUL:               return "X86ISD::UMUL";
18048   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18049   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18050   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18051   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18052   case X86ISD::INC:                return "X86ISD::INC";
18053   case X86ISD::DEC:                return "X86ISD::DEC";
18054   case X86ISD::OR:                 return "X86ISD::OR";
18055   case X86ISD::XOR:                return "X86ISD::XOR";
18056   case X86ISD::AND:                return "X86ISD::AND";
18057   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18058   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18059   case X86ISD::PTEST:              return "X86ISD::PTEST";
18060   case X86ISD::TESTP:              return "X86ISD::TESTP";
18061   case X86ISD::TESTM:              return "X86ISD::TESTM";
18062   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18063   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18064   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18065   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18066   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18067   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18068   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18069   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18070   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18071   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18072   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18073   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18074   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18075   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18076   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18077   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18078   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18079   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18080   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18081   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18082   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18083   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18084   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18085   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18086   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18087   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18088   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18089   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18090   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18091   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18092   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18093   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18094   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18095   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18096   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18097   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18098   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18099   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18100   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18101   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18102   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18103   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18104   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18105   case X86ISD::SAHF:               return "X86ISD::SAHF";
18106   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18107   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18108   case X86ISD::FMADD:              return "X86ISD::FMADD";
18109   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18110   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18111   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18112   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18113   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18114   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18115   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18116   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18117   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18118   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18119   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18120   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18121   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18122   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18123   case X86ISD::XTEST:              return "X86ISD::XTEST";
18124   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18125   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18126   case X86ISD::SELECT:             return "X86ISD::SELECT";
18127   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18128   case X86ISD::RCP28:              return "X86ISD::RCP28";
18129   case X86ISD::EXP2:               return "X86ISD::EXP2";
18130   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18131   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18132   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18133   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18134   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18135   case X86ISD::ADDS:               return "X86ISD::ADDS";
18136   case X86ISD::SUBS:               return "X86ISD::SUBS";
18137   }
18138   return nullptr;
18139 }
18140
18141 // isLegalAddressingMode - Return true if the addressing mode represented
18142 // by AM is legal for this target, for a load/store of the specified type.
18143 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18144                                               Type *Ty) const {
18145   // X86 supports extremely general addressing modes.
18146   CodeModel::Model M = getTargetMachine().getCodeModel();
18147   Reloc::Model R = getTargetMachine().getRelocationModel();
18148
18149   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18150   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18151     return false;
18152
18153   if (AM.BaseGV) {
18154     unsigned GVFlags =
18155       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18156
18157     // If a reference to this global requires an extra load, we can't fold it.
18158     if (isGlobalStubReference(GVFlags))
18159       return false;
18160
18161     // If BaseGV requires a register for the PIC base, we cannot also have a
18162     // BaseReg specified.
18163     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18164       return false;
18165
18166     // If lower 4G is not available, then we must use rip-relative addressing.
18167     if ((M != CodeModel::Small || R != Reloc::Static) &&
18168         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18169       return false;
18170   }
18171
18172   switch (AM.Scale) {
18173   case 0:
18174   case 1:
18175   case 2:
18176   case 4:
18177   case 8:
18178     // These scales always work.
18179     break;
18180   case 3:
18181   case 5:
18182   case 9:
18183     // These scales are formed with basereg+scalereg.  Only accept if there is
18184     // no basereg yet.
18185     if (AM.HasBaseReg)
18186       return false;
18187     break;
18188   default:  // Other stuff never works.
18189     return false;
18190   }
18191
18192   return true;
18193 }
18194
18195 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18196   unsigned Bits = Ty->getScalarSizeInBits();
18197
18198   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18199   // particularly cheaper than those without.
18200   if (Bits == 8)
18201     return false;
18202
18203   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18204   // variable shifts just as cheap as scalar ones.
18205   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18206     return false;
18207
18208   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18209   // fully general vector.
18210   return true;
18211 }
18212
18213 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18214   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18215     return false;
18216   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18217   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18218   return NumBits1 > NumBits2;
18219 }
18220
18221 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18222   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18223     return false;
18224
18225   if (!isTypeLegal(EVT::getEVT(Ty1)))
18226     return false;
18227
18228   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18229
18230   // Assuming the caller doesn't have a zeroext or signext return parameter,
18231   // truncation all the way down to i1 is valid.
18232   return true;
18233 }
18234
18235 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18236   return isInt<32>(Imm);
18237 }
18238
18239 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18240   // Can also use sub to handle negated immediates.
18241   return isInt<32>(Imm);
18242 }
18243
18244 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18245   if (!VT1.isInteger() || !VT2.isInteger())
18246     return false;
18247   unsigned NumBits1 = VT1.getSizeInBits();
18248   unsigned NumBits2 = VT2.getSizeInBits();
18249   return NumBits1 > NumBits2;
18250 }
18251
18252 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18253   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18254   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18255 }
18256
18257 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18258   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18259   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18260 }
18261
18262 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18263   EVT VT1 = Val.getValueType();
18264   if (isZExtFree(VT1, VT2))
18265     return true;
18266
18267   if (Val.getOpcode() != ISD::LOAD)
18268     return false;
18269
18270   if (!VT1.isSimple() || !VT1.isInteger() ||
18271       !VT2.isSimple() || !VT2.isInteger())
18272     return false;
18273
18274   switch (VT1.getSimpleVT().SimpleTy) {
18275   default: break;
18276   case MVT::i8:
18277   case MVT::i16:
18278   case MVT::i32:
18279     // X86 has 8, 16, and 32-bit zero-extending loads.
18280     return true;
18281   }
18282
18283   return false;
18284 }
18285
18286 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18287
18288 bool
18289 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18290   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18291     return false;
18292
18293   VT = VT.getScalarType();
18294
18295   if (!VT.isSimple())
18296     return false;
18297
18298   switch (VT.getSimpleVT().SimpleTy) {
18299   case MVT::f32:
18300   case MVT::f64:
18301     return true;
18302   default:
18303     break;
18304   }
18305
18306   return false;
18307 }
18308
18309 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18310   // i16 instructions are longer (0x66 prefix) and potentially slower.
18311   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18312 }
18313
18314 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18315 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18316 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18317 /// are assumed to be legal.
18318 bool
18319 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18320                                       EVT VT) const {
18321   if (!VT.isSimple())
18322     return false;
18323
18324   // Not for i1 vectors
18325   if (VT.getScalarType() == MVT::i1)
18326     return false;
18327
18328   // Very little shuffling can be done for 64-bit vectors right now.
18329   if (VT.getSizeInBits() == 64)
18330     return false;
18331
18332   // We only care that the types being shuffled are legal. The lowering can
18333   // handle any possible shuffle mask that results.
18334   return isTypeLegal(VT.getSimpleVT());
18335 }
18336
18337 bool
18338 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18339                                           EVT VT) const {
18340   // Just delegate to the generic legality, clear masks aren't special.
18341   return isShuffleMaskLegal(Mask, VT);
18342 }
18343
18344 //===----------------------------------------------------------------------===//
18345 //                           X86 Scheduler Hooks
18346 //===----------------------------------------------------------------------===//
18347
18348 /// Utility function to emit xbegin specifying the start of an RTM region.
18349 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18350                                      const TargetInstrInfo *TII) {
18351   DebugLoc DL = MI->getDebugLoc();
18352
18353   const BasicBlock *BB = MBB->getBasicBlock();
18354   MachineFunction::iterator I = MBB;
18355   ++I;
18356
18357   // For the v = xbegin(), we generate
18358   //
18359   // thisMBB:
18360   //  xbegin sinkMBB
18361   //
18362   // mainMBB:
18363   //  eax = -1
18364   //
18365   // sinkMBB:
18366   //  v = eax
18367
18368   MachineBasicBlock *thisMBB = MBB;
18369   MachineFunction *MF = MBB->getParent();
18370   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18371   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18372   MF->insert(I, mainMBB);
18373   MF->insert(I, sinkMBB);
18374
18375   // Transfer the remainder of BB and its successor edges to sinkMBB.
18376   sinkMBB->splice(sinkMBB->begin(), MBB,
18377                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18378   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18379
18380   // thisMBB:
18381   //  xbegin sinkMBB
18382   //  # fallthrough to mainMBB
18383   //  # abortion to sinkMBB
18384   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18385   thisMBB->addSuccessor(mainMBB);
18386   thisMBB->addSuccessor(sinkMBB);
18387
18388   // mainMBB:
18389   //  EAX = -1
18390   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18391   mainMBB->addSuccessor(sinkMBB);
18392
18393   // sinkMBB:
18394   // EAX is live into the sinkMBB
18395   sinkMBB->addLiveIn(X86::EAX);
18396   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18397           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18398     .addReg(X86::EAX);
18399
18400   MI->eraseFromParent();
18401   return sinkMBB;
18402 }
18403
18404 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18405 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18406 // in the .td file.
18407 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18408                                        const TargetInstrInfo *TII) {
18409   unsigned Opc;
18410   switch (MI->getOpcode()) {
18411   default: llvm_unreachable("illegal opcode!");
18412   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18413   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18414   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18415   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18416   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18417   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18418   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18419   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18420   }
18421
18422   DebugLoc dl = MI->getDebugLoc();
18423   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18424
18425   unsigned NumArgs = MI->getNumOperands();
18426   for (unsigned i = 1; i < NumArgs; ++i) {
18427     MachineOperand &Op = MI->getOperand(i);
18428     if (!(Op.isReg() && Op.isImplicit()))
18429       MIB.addOperand(Op);
18430   }
18431   if (MI->hasOneMemOperand())
18432     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18433
18434   BuildMI(*BB, MI, dl,
18435     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18436     .addReg(X86::XMM0);
18437
18438   MI->eraseFromParent();
18439   return BB;
18440 }
18441
18442 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18443 // defs in an instruction pattern
18444 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18445                                        const TargetInstrInfo *TII) {
18446   unsigned Opc;
18447   switch (MI->getOpcode()) {
18448   default: llvm_unreachable("illegal opcode!");
18449   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18450   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18451   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18452   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18453   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18454   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18455   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18456   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18457   }
18458
18459   DebugLoc dl = MI->getDebugLoc();
18460   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18461
18462   unsigned NumArgs = MI->getNumOperands(); // remove the results
18463   for (unsigned i = 1; i < NumArgs; ++i) {
18464     MachineOperand &Op = MI->getOperand(i);
18465     if (!(Op.isReg() && Op.isImplicit()))
18466       MIB.addOperand(Op);
18467   }
18468   if (MI->hasOneMemOperand())
18469     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18470
18471   BuildMI(*BB, MI, dl,
18472     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18473     .addReg(X86::ECX);
18474
18475   MI->eraseFromParent();
18476   return BB;
18477 }
18478
18479 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18480                                       const X86Subtarget *Subtarget) {
18481   DebugLoc dl = MI->getDebugLoc();
18482   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18483   // Address into RAX/EAX, other two args into ECX, EDX.
18484   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18485   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18486   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18487   for (int i = 0; i < X86::AddrNumOperands; ++i)
18488     MIB.addOperand(MI->getOperand(i));
18489
18490   unsigned ValOps = X86::AddrNumOperands;
18491   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18492     .addReg(MI->getOperand(ValOps).getReg());
18493   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18494     .addReg(MI->getOperand(ValOps+1).getReg());
18495
18496   // The instruction doesn't actually take any operands though.
18497   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18498
18499   MI->eraseFromParent(); // The pseudo is gone now.
18500   return BB;
18501 }
18502
18503 MachineBasicBlock *
18504 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18505                                                  MachineBasicBlock *MBB) const {
18506   // Emit va_arg instruction on X86-64.
18507
18508   // Operands to this pseudo-instruction:
18509   // 0  ) Output        : destination address (reg)
18510   // 1-5) Input         : va_list address (addr, i64mem)
18511   // 6  ) ArgSize       : Size (in bytes) of vararg type
18512   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18513   // 8  ) Align         : Alignment of type
18514   // 9  ) EFLAGS (implicit-def)
18515
18516   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18517   static_assert(X86::AddrNumOperands == 5,
18518                 "VAARG_64 assumes 5 address operands");
18519
18520   unsigned DestReg = MI->getOperand(0).getReg();
18521   MachineOperand &Base = MI->getOperand(1);
18522   MachineOperand &Scale = MI->getOperand(2);
18523   MachineOperand &Index = MI->getOperand(3);
18524   MachineOperand &Disp = MI->getOperand(4);
18525   MachineOperand &Segment = MI->getOperand(5);
18526   unsigned ArgSize = MI->getOperand(6).getImm();
18527   unsigned ArgMode = MI->getOperand(7).getImm();
18528   unsigned Align = MI->getOperand(8).getImm();
18529
18530   // Memory Reference
18531   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18532   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18533   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18534
18535   // Machine Information
18536   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18537   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18538   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18539   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18540   DebugLoc DL = MI->getDebugLoc();
18541
18542   // struct va_list {
18543   //   i32   gp_offset
18544   //   i32   fp_offset
18545   //   i64   overflow_area (address)
18546   //   i64   reg_save_area (address)
18547   // }
18548   // sizeof(va_list) = 24
18549   // alignment(va_list) = 8
18550
18551   unsigned TotalNumIntRegs = 6;
18552   unsigned TotalNumXMMRegs = 8;
18553   bool UseGPOffset = (ArgMode == 1);
18554   bool UseFPOffset = (ArgMode == 2);
18555   unsigned MaxOffset = TotalNumIntRegs * 8 +
18556                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18557
18558   /* Align ArgSize to a multiple of 8 */
18559   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18560   bool NeedsAlign = (Align > 8);
18561
18562   MachineBasicBlock *thisMBB = MBB;
18563   MachineBasicBlock *overflowMBB;
18564   MachineBasicBlock *offsetMBB;
18565   MachineBasicBlock *endMBB;
18566
18567   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18568   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18569   unsigned OffsetReg = 0;
18570
18571   if (!UseGPOffset && !UseFPOffset) {
18572     // If we only pull from the overflow region, we don't create a branch.
18573     // We don't need to alter control flow.
18574     OffsetDestReg = 0; // unused
18575     OverflowDestReg = DestReg;
18576
18577     offsetMBB = nullptr;
18578     overflowMBB = thisMBB;
18579     endMBB = thisMBB;
18580   } else {
18581     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18582     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18583     // If not, pull from overflow_area. (branch to overflowMBB)
18584     //
18585     //       thisMBB
18586     //         |     .
18587     //         |        .
18588     //     offsetMBB   overflowMBB
18589     //         |        .
18590     //         |     .
18591     //        endMBB
18592
18593     // Registers for the PHI in endMBB
18594     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18595     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18596
18597     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18598     MachineFunction *MF = MBB->getParent();
18599     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18600     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18601     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18602
18603     MachineFunction::iterator MBBIter = MBB;
18604     ++MBBIter;
18605
18606     // Insert the new basic blocks
18607     MF->insert(MBBIter, offsetMBB);
18608     MF->insert(MBBIter, overflowMBB);
18609     MF->insert(MBBIter, endMBB);
18610
18611     // Transfer the remainder of MBB and its successor edges to endMBB.
18612     endMBB->splice(endMBB->begin(), thisMBB,
18613                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18614     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18615
18616     // Make offsetMBB and overflowMBB successors of thisMBB
18617     thisMBB->addSuccessor(offsetMBB);
18618     thisMBB->addSuccessor(overflowMBB);
18619
18620     // endMBB is a successor of both offsetMBB and overflowMBB
18621     offsetMBB->addSuccessor(endMBB);
18622     overflowMBB->addSuccessor(endMBB);
18623
18624     // Load the offset value into a register
18625     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18626     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18627       .addOperand(Base)
18628       .addOperand(Scale)
18629       .addOperand(Index)
18630       .addDisp(Disp, UseFPOffset ? 4 : 0)
18631       .addOperand(Segment)
18632       .setMemRefs(MMOBegin, MMOEnd);
18633
18634     // Check if there is enough room left to pull this argument.
18635     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18636       .addReg(OffsetReg)
18637       .addImm(MaxOffset + 8 - ArgSizeA8);
18638
18639     // Branch to "overflowMBB" if offset >= max
18640     // Fall through to "offsetMBB" otherwise
18641     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18642       .addMBB(overflowMBB);
18643   }
18644
18645   // In offsetMBB, emit code to use the reg_save_area.
18646   if (offsetMBB) {
18647     assert(OffsetReg != 0);
18648
18649     // Read the reg_save_area address.
18650     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18651     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18652       .addOperand(Base)
18653       .addOperand(Scale)
18654       .addOperand(Index)
18655       .addDisp(Disp, 16)
18656       .addOperand(Segment)
18657       .setMemRefs(MMOBegin, MMOEnd);
18658
18659     // Zero-extend the offset
18660     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18661       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18662         .addImm(0)
18663         .addReg(OffsetReg)
18664         .addImm(X86::sub_32bit);
18665
18666     // Add the offset to the reg_save_area to get the final address.
18667     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18668       .addReg(OffsetReg64)
18669       .addReg(RegSaveReg);
18670
18671     // Compute the offset for the next argument
18672     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18673     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18674       .addReg(OffsetReg)
18675       .addImm(UseFPOffset ? 16 : 8);
18676
18677     // Store it back into the va_list.
18678     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18679       .addOperand(Base)
18680       .addOperand(Scale)
18681       .addOperand(Index)
18682       .addDisp(Disp, UseFPOffset ? 4 : 0)
18683       .addOperand(Segment)
18684       .addReg(NextOffsetReg)
18685       .setMemRefs(MMOBegin, MMOEnd);
18686
18687     // Jump to endMBB
18688     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18689       .addMBB(endMBB);
18690   }
18691
18692   //
18693   // Emit code to use overflow area
18694   //
18695
18696   // Load the overflow_area address into a register.
18697   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18698   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18699     .addOperand(Base)
18700     .addOperand(Scale)
18701     .addOperand(Index)
18702     .addDisp(Disp, 8)
18703     .addOperand(Segment)
18704     .setMemRefs(MMOBegin, MMOEnd);
18705
18706   // If we need to align it, do so. Otherwise, just copy the address
18707   // to OverflowDestReg.
18708   if (NeedsAlign) {
18709     // Align the overflow address
18710     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18711     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18712
18713     // aligned_addr = (addr + (align-1)) & ~(align-1)
18714     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18715       .addReg(OverflowAddrReg)
18716       .addImm(Align-1);
18717
18718     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18719       .addReg(TmpReg)
18720       .addImm(~(uint64_t)(Align-1));
18721   } else {
18722     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18723       .addReg(OverflowAddrReg);
18724   }
18725
18726   // Compute the next overflow address after this argument.
18727   // (the overflow address should be kept 8-byte aligned)
18728   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18729   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18730     .addReg(OverflowDestReg)
18731     .addImm(ArgSizeA8);
18732
18733   // Store the new overflow address.
18734   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18735     .addOperand(Base)
18736     .addOperand(Scale)
18737     .addOperand(Index)
18738     .addDisp(Disp, 8)
18739     .addOperand(Segment)
18740     .addReg(NextAddrReg)
18741     .setMemRefs(MMOBegin, MMOEnd);
18742
18743   // If we branched, emit the PHI to the front of endMBB.
18744   if (offsetMBB) {
18745     BuildMI(*endMBB, endMBB->begin(), DL,
18746             TII->get(X86::PHI), DestReg)
18747       .addReg(OffsetDestReg).addMBB(offsetMBB)
18748       .addReg(OverflowDestReg).addMBB(overflowMBB);
18749   }
18750
18751   // Erase the pseudo instruction
18752   MI->eraseFromParent();
18753
18754   return endMBB;
18755 }
18756
18757 MachineBasicBlock *
18758 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18759                                                  MachineInstr *MI,
18760                                                  MachineBasicBlock *MBB) const {
18761   // Emit code to save XMM registers to the stack. The ABI says that the
18762   // number of registers to save is given in %al, so it's theoretically
18763   // possible to do an indirect jump trick to avoid saving all of them,
18764   // however this code takes a simpler approach and just executes all
18765   // of the stores if %al is non-zero. It's less code, and it's probably
18766   // easier on the hardware branch predictor, and stores aren't all that
18767   // expensive anyway.
18768
18769   // Create the new basic blocks. One block contains all the XMM stores,
18770   // and one block is the final destination regardless of whether any
18771   // stores were performed.
18772   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18773   MachineFunction *F = MBB->getParent();
18774   MachineFunction::iterator MBBIter = MBB;
18775   ++MBBIter;
18776   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18777   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18778   F->insert(MBBIter, XMMSaveMBB);
18779   F->insert(MBBIter, EndMBB);
18780
18781   // Transfer the remainder of MBB and its successor edges to EndMBB.
18782   EndMBB->splice(EndMBB->begin(), MBB,
18783                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18784   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18785
18786   // The original block will now fall through to the XMM save block.
18787   MBB->addSuccessor(XMMSaveMBB);
18788   // The XMMSaveMBB will fall through to the end block.
18789   XMMSaveMBB->addSuccessor(EndMBB);
18790
18791   // Now add the instructions.
18792   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18793   DebugLoc DL = MI->getDebugLoc();
18794
18795   unsigned CountReg = MI->getOperand(0).getReg();
18796   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18797   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18798
18799   if (!Subtarget->isTargetWin64()) {
18800     // If %al is 0, branch around the XMM save block.
18801     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18802     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18803     MBB->addSuccessor(EndMBB);
18804   }
18805
18806   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18807   // that was just emitted, but clearly shouldn't be "saved".
18808   assert((MI->getNumOperands() <= 3 ||
18809           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18810           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18811          && "Expected last argument to be EFLAGS");
18812   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18813   // In the XMM save block, save all the XMM argument registers.
18814   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18815     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18816     MachineMemOperand *MMO =
18817       F->getMachineMemOperand(
18818           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18819         MachineMemOperand::MOStore,
18820         /*Size=*/16, /*Align=*/16);
18821     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18822       .addFrameIndex(RegSaveFrameIndex)
18823       .addImm(/*Scale=*/1)
18824       .addReg(/*IndexReg=*/0)
18825       .addImm(/*Disp=*/Offset)
18826       .addReg(/*Segment=*/0)
18827       .addReg(MI->getOperand(i).getReg())
18828       .addMemOperand(MMO);
18829   }
18830
18831   MI->eraseFromParent();   // The pseudo instruction is gone now.
18832
18833   return EndMBB;
18834 }
18835
18836 // The EFLAGS operand of SelectItr might be missing a kill marker
18837 // because there were multiple uses of EFLAGS, and ISel didn't know
18838 // which to mark. Figure out whether SelectItr should have had a
18839 // kill marker, and set it if it should. Returns the correct kill
18840 // marker value.
18841 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18842                                      MachineBasicBlock* BB,
18843                                      const TargetRegisterInfo* TRI) {
18844   // Scan forward through BB for a use/def of EFLAGS.
18845   MachineBasicBlock::iterator miI(std::next(SelectItr));
18846   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18847     const MachineInstr& mi = *miI;
18848     if (mi.readsRegister(X86::EFLAGS))
18849       return false;
18850     if (mi.definesRegister(X86::EFLAGS))
18851       break; // Should have kill-flag - update below.
18852   }
18853
18854   // If we hit the end of the block, check whether EFLAGS is live into a
18855   // successor.
18856   if (miI == BB->end()) {
18857     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18858                                           sEnd = BB->succ_end();
18859          sItr != sEnd; ++sItr) {
18860       MachineBasicBlock* succ = *sItr;
18861       if (succ->isLiveIn(X86::EFLAGS))
18862         return false;
18863     }
18864   }
18865
18866   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18867   // out. SelectMI should have a kill flag on EFLAGS.
18868   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18869   return true;
18870 }
18871
18872 MachineBasicBlock *
18873 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18874                                      MachineBasicBlock *BB) const {
18875   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18876   DebugLoc DL = MI->getDebugLoc();
18877
18878   // To "insert" a SELECT_CC instruction, we actually have to insert the
18879   // diamond control-flow pattern.  The incoming instruction knows the
18880   // destination vreg to set, the condition code register to branch on, the
18881   // true/false values to select between, and a branch opcode to use.
18882   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18883   MachineFunction::iterator It = BB;
18884   ++It;
18885
18886   //  thisMBB:
18887   //  ...
18888   //   TrueVal = ...
18889   //   cmpTY ccX, r1, r2
18890   //   bCC copy1MBB
18891   //   fallthrough --> copy0MBB
18892   MachineBasicBlock *thisMBB = BB;
18893   MachineFunction *F = BB->getParent();
18894
18895   // We also lower double CMOVs:
18896   //   (CMOV (CMOV F, T, cc1), T, cc2)
18897   // to two successives branches.  For that, we look for another CMOV as the
18898   // following instruction.
18899   //
18900   // Without this, we would add a PHI between the two jumps, which ends up
18901   // creating a few copies all around. For instance, for
18902   //
18903   //    (sitofp (zext (fcmp une)))
18904   //
18905   // we would generate:
18906   //
18907   //         ucomiss %xmm1, %xmm0
18908   //         movss  <1.0f>, %xmm0
18909   //         movaps  %xmm0, %xmm1
18910   //         jne     .LBB5_2
18911   //         xorps   %xmm1, %xmm1
18912   // .LBB5_2:
18913   //         jp      .LBB5_4
18914   //         movaps  %xmm1, %xmm0
18915   // .LBB5_4:
18916   //         retq
18917   //
18918   // because this custom-inserter would have generated:
18919   //
18920   //   A
18921   //   | \
18922   //   |  B
18923   //   | /
18924   //   C
18925   //   | \
18926   //   |  D
18927   //   | /
18928   //   E
18929   //
18930   // A: X = ...; Y = ...
18931   // B: empty
18932   // C: Z = PHI [X, A], [Y, B]
18933   // D: empty
18934   // E: PHI [X, C], [Z, D]
18935   //
18936   // If we lower both CMOVs in a single step, we can instead generate:
18937   //
18938   //   A
18939   //   | \
18940   //   |  C
18941   //   | /|
18942   //   |/ |
18943   //   |  |
18944   //   |  D
18945   //   | /
18946   //   E
18947   //
18948   // A: X = ...; Y = ...
18949   // D: empty
18950   // E: PHI [X, A], [X, C], [Y, D]
18951   //
18952   // Which, in our sitofp/fcmp example, gives us something like:
18953   //
18954   //         ucomiss %xmm1, %xmm0
18955   //         movss  <1.0f>, %xmm0
18956   //         jne     .LBB5_4
18957   //         jp      .LBB5_4
18958   //         xorps   %xmm0, %xmm0
18959   // .LBB5_4:
18960   //         retq
18961   //
18962   MachineInstr *NextCMOV = nullptr;
18963   MachineBasicBlock::iterator NextMIIt =
18964       std::next(MachineBasicBlock::iterator(MI));
18965   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18966       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18967       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18968     NextCMOV = &*NextMIIt;
18969
18970   MachineBasicBlock *jcc1MBB = nullptr;
18971
18972   // If we have a double CMOV, we lower it to two successive branches to
18973   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18974   if (NextCMOV) {
18975     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18976     F->insert(It, jcc1MBB);
18977     jcc1MBB->addLiveIn(X86::EFLAGS);
18978   }
18979
18980   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18981   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18982   F->insert(It, copy0MBB);
18983   F->insert(It, sinkMBB);
18984
18985   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18986   // live into the sink and copy blocks.
18987   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18988
18989   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18990   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18991       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18992     copy0MBB->addLiveIn(X86::EFLAGS);
18993     sinkMBB->addLiveIn(X86::EFLAGS);
18994   }
18995
18996   // Transfer the remainder of BB and its successor edges to sinkMBB.
18997   sinkMBB->splice(sinkMBB->begin(), BB,
18998                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18999   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19000
19001   // Add the true and fallthrough blocks as its successors.
19002   if (NextCMOV) {
19003     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19004     BB->addSuccessor(jcc1MBB);
19005
19006     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19007     // jump to the sinkMBB.
19008     jcc1MBB->addSuccessor(copy0MBB);
19009     jcc1MBB->addSuccessor(sinkMBB);
19010   } else {
19011     BB->addSuccessor(copy0MBB);
19012   }
19013
19014   // The true block target of the first (or only) branch is always sinkMBB.
19015   BB->addSuccessor(sinkMBB);
19016
19017   // Create the conditional branch instruction.
19018   unsigned Opc =
19019     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19020   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19021
19022   if (NextCMOV) {
19023     unsigned Opc2 = X86::GetCondBranchFromCond(
19024         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19025     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19026   }
19027
19028   //  copy0MBB:
19029   //   %FalseValue = ...
19030   //   # fallthrough to sinkMBB
19031   copy0MBB->addSuccessor(sinkMBB);
19032
19033   //  sinkMBB:
19034   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19035   //  ...
19036   MachineInstrBuilder MIB =
19037       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19038               MI->getOperand(0).getReg())
19039           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19040           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19041
19042   // If we have a double CMOV, the second Jcc provides the same incoming
19043   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19044   if (NextCMOV) {
19045     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19046     // Copy the PHI result to the register defined by the second CMOV.
19047     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19048             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19049         .addReg(MI->getOperand(0).getReg());
19050     NextCMOV->eraseFromParent();
19051   }
19052
19053   MI->eraseFromParent();   // The pseudo instruction is gone now.
19054   return sinkMBB;
19055 }
19056
19057 MachineBasicBlock *
19058 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19059                                         MachineBasicBlock *BB) const {
19060   MachineFunction *MF = BB->getParent();
19061   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19062   DebugLoc DL = MI->getDebugLoc();
19063   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19064
19065   assert(MF->shouldSplitStack());
19066
19067   const bool Is64Bit = Subtarget->is64Bit();
19068   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19069
19070   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19071   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19072
19073   // BB:
19074   //  ... [Till the alloca]
19075   // If stacklet is not large enough, jump to mallocMBB
19076   //
19077   // bumpMBB:
19078   //  Allocate by subtracting from RSP
19079   //  Jump to continueMBB
19080   //
19081   // mallocMBB:
19082   //  Allocate by call to runtime
19083   //
19084   // continueMBB:
19085   //  ...
19086   //  [rest of original BB]
19087   //
19088
19089   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19090   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19091   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19092
19093   MachineRegisterInfo &MRI = MF->getRegInfo();
19094   const TargetRegisterClass *AddrRegClass =
19095     getRegClassFor(getPointerTy());
19096
19097   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19098     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19099     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19100     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19101     sizeVReg = MI->getOperand(1).getReg(),
19102     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19103
19104   MachineFunction::iterator MBBIter = BB;
19105   ++MBBIter;
19106
19107   MF->insert(MBBIter, bumpMBB);
19108   MF->insert(MBBIter, mallocMBB);
19109   MF->insert(MBBIter, continueMBB);
19110
19111   continueMBB->splice(continueMBB->begin(), BB,
19112                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19113   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19114
19115   // Add code to the main basic block to check if the stack limit has been hit,
19116   // and if so, jump to mallocMBB otherwise to bumpMBB.
19117   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19118   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19119     .addReg(tmpSPVReg).addReg(sizeVReg);
19120   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19121     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19122     .addReg(SPLimitVReg);
19123   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19124
19125   // bumpMBB simply decreases the stack pointer, since we know the current
19126   // stacklet has enough space.
19127   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19128     .addReg(SPLimitVReg);
19129   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19130     .addReg(SPLimitVReg);
19131   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19132
19133   // Calls into a routine in libgcc to allocate more space from the heap.
19134   const uint32_t *RegMask =
19135       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19136   if (IsLP64) {
19137     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19138       .addReg(sizeVReg);
19139     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19140       .addExternalSymbol("__morestack_allocate_stack_space")
19141       .addRegMask(RegMask)
19142       .addReg(X86::RDI, RegState::Implicit)
19143       .addReg(X86::RAX, RegState::ImplicitDefine);
19144   } else if (Is64Bit) {
19145     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19146       .addReg(sizeVReg);
19147     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19148       .addExternalSymbol("__morestack_allocate_stack_space")
19149       .addRegMask(RegMask)
19150       .addReg(X86::EDI, RegState::Implicit)
19151       .addReg(X86::EAX, RegState::ImplicitDefine);
19152   } else {
19153     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19154       .addImm(12);
19155     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19156     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19157       .addExternalSymbol("__morestack_allocate_stack_space")
19158       .addRegMask(RegMask)
19159       .addReg(X86::EAX, RegState::ImplicitDefine);
19160   }
19161
19162   if (!Is64Bit)
19163     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19164       .addImm(16);
19165
19166   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19167     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19168   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19169
19170   // Set up the CFG correctly.
19171   BB->addSuccessor(bumpMBB);
19172   BB->addSuccessor(mallocMBB);
19173   mallocMBB->addSuccessor(continueMBB);
19174   bumpMBB->addSuccessor(continueMBB);
19175
19176   // Take care of the PHI nodes.
19177   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19178           MI->getOperand(0).getReg())
19179     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19180     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19181
19182   // Delete the original pseudo instruction.
19183   MI->eraseFromParent();
19184
19185   // And we're done.
19186   return continueMBB;
19187 }
19188
19189 MachineBasicBlock *
19190 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19191                                         MachineBasicBlock *BB) const {
19192   DebugLoc DL = MI->getDebugLoc();
19193
19194   assert(!Subtarget->isTargetMachO());
19195
19196   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19197
19198   MI->eraseFromParent();   // The pseudo instruction is gone now.
19199   return BB;
19200 }
19201
19202 MachineBasicBlock *
19203 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19204                                       MachineBasicBlock *BB) const {
19205   // This is pretty easy.  We're taking the value that we received from
19206   // our load from the relocation, sticking it in either RDI (x86-64)
19207   // or EAX and doing an indirect call.  The return value will then
19208   // be in the normal return register.
19209   MachineFunction *F = BB->getParent();
19210   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19211   DebugLoc DL = MI->getDebugLoc();
19212
19213   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19214   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19215
19216   // Get a register mask for the lowered call.
19217   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19218   // proper register mask.
19219   const uint32_t *RegMask =
19220       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19221   if (Subtarget->is64Bit()) {
19222     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19223                                       TII->get(X86::MOV64rm), X86::RDI)
19224     .addReg(X86::RIP)
19225     .addImm(0).addReg(0)
19226     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19227                       MI->getOperand(3).getTargetFlags())
19228     .addReg(0);
19229     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19230     addDirectMem(MIB, X86::RDI);
19231     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19232   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19233     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19234                                       TII->get(X86::MOV32rm), X86::EAX)
19235     .addReg(0)
19236     .addImm(0).addReg(0)
19237     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19238                       MI->getOperand(3).getTargetFlags())
19239     .addReg(0);
19240     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19241     addDirectMem(MIB, X86::EAX);
19242     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19243   } else {
19244     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19245                                       TII->get(X86::MOV32rm), X86::EAX)
19246     .addReg(TII->getGlobalBaseReg(F))
19247     .addImm(0).addReg(0)
19248     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19249                       MI->getOperand(3).getTargetFlags())
19250     .addReg(0);
19251     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19252     addDirectMem(MIB, X86::EAX);
19253     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19254   }
19255
19256   MI->eraseFromParent(); // The pseudo instruction is gone now.
19257   return BB;
19258 }
19259
19260 MachineBasicBlock *
19261 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19262                                     MachineBasicBlock *MBB) const {
19263   DebugLoc DL = MI->getDebugLoc();
19264   MachineFunction *MF = MBB->getParent();
19265   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19266   MachineRegisterInfo &MRI = MF->getRegInfo();
19267
19268   const BasicBlock *BB = MBB->getBasicBlock();
19269   MachineFunction::iterator I = MBB;
19270   ++I;
19271
19272   // Memory Reference
19273   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19274   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19275
19276   unsigned DstReg;
19277   unsigned MemOpndSlot = 0;
19278
19279   unsigned CurOp = 0;
19280
19281   DstReg = MI->getOperand(CurOp++).getReg();
19282   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19283   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19284   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19285   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19286
19287   MemOpndSlot = CurOp;
19288
19289   MVT PVT = getPointerTy();
19290   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19291          "Invalid Pointer Size!");
19292
19293   // For v = setjmp(buf), we generate
19294   //
19295   // thisMBB:
19296   //  buf[LabelOffset] = restoreMBB
19297   //  SjLjSetup restoreMBB
19298   //
19299   // mainMBB:
19300   //  v_main = 0
19301   //
19302   // sinkMBB:
19303   //  v = phi(main, restore)
19304   //
19305   // restoreMBB:
19306   //  if base pointer being used, load it from frame
19307   //  v_restore = 1
19308
19309   MachineBasicBlock *thisMBB = MBB;
19310   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19311   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19312   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19313   MF->insert(I, mainMBB);
19314   MF->insert(I, sinkMBB);
19315   MF->push_back(restoreMBB);
19316
19317   MachineInstrBuilder MIB;
19318
19319   // Transfer the remainder of BB and its successor edges to sinkMBB.
19320   sinkMBB->splice(sinkMBB->begin(), MBB,
19321                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19322   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19323
19324   // thisMBB:
19325   unsigned PtrStoreOpc = 0;
19326   unsigned LabelReg = 0;
19327   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19328   Reloc::Model RM = MF->getTarget().getRelocationModel();
19329   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19330                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19331
19332   // Prepare IP either in reg or imm.
19333   if (!UseImmLabel) {
19334     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19335     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19336     LabelReg = MRI.createVirtualRegister(PtrRC);
19337     if (Subtarget->is64Bit()) {
19338       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19339               .addReg(X86::RIP)
19340               .addImm(0)
19341               .addReg(0)
19342               .addMBB(restoreMBB)
19343               .addReg(0);
19344     } else {
19345       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19346       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19347               .addReg(XII->getGlobalBaseReg(MF))
19348               .addImm(0)
19349               .addReg(0)
19350               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19351               .addReg(0);
19352     }
19353   } else
19354     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19355   // Store IP
19356   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19357   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19358     if (i == X86::AddrDisp)
19359       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19360     else
19361       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19362   }
19363   if (!UseImmLabel)
19364     MIB.addReg(LabelReg);
19365   else
19366     MIB.addMBB(restoreMBB);
19367   MIB.setMemRefs(MMOBegin, MMOEnd);
19368   // Setup
19369   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19370           .addMBB(restoreMBB);
19371
19372   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19373   MIB.addRegMask(RegInfo->getNoPreservedMask());
19374   thisMBB->addSuccessor(mainMBB);
19375   thisMBB->addSuccessor(restoreMBB);
19376
19377   // mainMBB:
19378   //  EAX = 0
19379   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19380   mainMBB->addSuccessor(sinkMBB);
19381
19382   // sinkMBB:
19383   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19384           TII->get(X86::PHI), DstReg)
19385     .addReg(mainDstReg).addMBB(mainMBB)
19386     .addReg(restoreDstReg).addMBB(restoreMBB);
19387
19388   // restoreMBB:
19389   if (RegInfo->hasBasePointer(*MF)) {
19390     const bool Uses64BitFramePtr =
19391         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19392     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19393     X86FI->setRestoreBasePointer(MF);
19394     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19395     unsigned BasePtr = RegInfo->getBaseRegister();
19396     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19397     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19398                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19399       .setMIFlag(MachineInstr::FrameSetup);
19400   }
19401   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19402   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19403   restoreMBB->addSuccessor(sinkMBB);
19404
19405   MI->eraseFromParent();
19406   return sinkMBB;
19407 }
19408
19409 MachineBasicBlock *
19410 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19411                                      MachineBasicBlock *MBB) const {
19412   DebugLoc DL = MI->getDebugLoc();
19413   MachineFunction *MF = MBB->getParent();
19414   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19415   MachineRegisterInfo &MRI = MF->getRegInfo();
19416
19417   // Memory Reference
19418   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19419   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19420
19421   MVT PVT = getPointerTy();
19422   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19423          "Invalid Pointer Size!");
19424
19425   const TargetRegisterClass *RC =
19426     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19427   unsigned Tmp = MRI.createVirtualRegister(RC);
19428   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19429   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19430   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19431   unsigned SP = RegInfo->getStackRegister();
19432
19433   MachineInstrBuilder MIB;
19434
19435   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19436   const int64_t SPOffset = 2 * PVT.getStoreSize();
19437
19438   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19439   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19440
19441   // Reload FP
19442   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19443   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19444     MIB.addOperand(MI->getOperand(i));
19445   MIB.setMemRefs(MMOBegin, MMOEnd);
19446   // Reload IP
19447   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19448   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19449     if (i == X86::AddrDisp)
19450       MIB.addDisp(MI->getOperand(i), LabelOffset);
19451     else
19452       MIB.addOperand(MI->getOperand(i));
19453   }
19454   MIB.setMemRefs(MMOBegin, MMOEnd);
19455   // Reload SP
19456   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19457   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19458     if (i == X86::AddrDisp)
19459       MIB.addDisp(MI->getOperand(i), SPOffset);
19460     else
19461       MIB.addOperand(MI->getOperand(i));
19462   }
19463   MIB.setMemRefs(MMOBegin, MMOEnd);
19464   // Jump
19465   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19466
19467   MI->eraseFromParent();
19468   return MBB;
19469 }
19470
19471 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19472 // accumulator loops. Writing back to the accumulator allows the coalescer
19473 // to remove extra copies in the loop.
19474 MachineBasicBlock *
19475 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19476                                  MachineBasicBlock *MBB) const {
19477   MachineOperand &AddendOp = MI->getOperand(3);
19478
19479   // Bail out early if the addend isn't a register - we can't switch these.
19480   if (!AddendOp.isReg())
19481     return MBB;
19482
19483   MachineFunction &MF = *MBB->getParent();
19484   MachineRegisterInfo &MRI = MF.getRegInfo();
19485
19486   // Check whether the addend is defined by a PHI:
19487   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19488   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19489   if (!AddendDef.isPHI())
19490     return MBB;
19491
19492   // Look for the following pattern:
19493   // loop:
19494   //   %addend = phi [%entry, 0], [%loop, %result]
19495   //   ...
19496   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19497
19498   // Replace with:
19499   //   loop:
19500   //   %addend = phi [%entry, 0], [%loop, %result]
19501   //   ...
19502   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19503
19504   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19505     assert(AddendDef.getOperand(i).isReg());
19506     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19507     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19508     if (&PHISrcInst == MI) {
19509       // Found a matching instruction.
19510       unsigned NewFMAOpc = 0;
19511       switch (MI->getOpcode()) {
19512         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19513         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19514         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19515         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19516         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19517         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19518         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19519         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19520         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19521         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19522         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19523         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19524         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19525         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19526         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19527         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19528         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19529         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19530         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19531         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19532
19533         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19534         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19535         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19536         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19537         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19538         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19539         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19540         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19541         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19542         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19543         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19544         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19545         default: llvm_unreachable("Unrecognized FMA variant.");
19546       }
19547
19548       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19549       MachineInstrBuilder MIB =
19550         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19551         .addOperand(MI->getOperand(0))
19552         .addOperand(MI->getOperand(3))
19553         .addOperand(MI->getOperand(2))
19554         .addOperand(MI->getOperand(1));
19555       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19556       MI->eraseFromParent();
19557     }
19558   }
19559
19560   return MBB;
19561 }
19562
19563 MachineBasicBlock *
19564 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19565                                                MachineBasicBlock *BB) const {
19566   switch (MI->getOpcode()) {
19567   default: llvm_unreachable("Unexpected instr type to insert");
19568   case X86::TAILJMPd64:
19569   case X86::TAILJMPr64:
19570   case X86::TAILJMPm64:
19571   case X86::TAILJMPd64_REX:
19572   case X86::TAILJMPr64_REX:
19573   case X86::TAILJMPm64_REX:
19574     llvm_unreachable("TAILJMP64 would not be touched here.");
19575   case X86::TCRETURNdi64:
19576   case X86::TCRETURNri64:
19577   case X86::TCRETURNmi64:
19578     return BB;
19579   case X86::WIN_ALLOCA:
19580     return EmitLoweredWinAlloca(MI, BB);
19581   case X86::SEG_ALLOCA_32:
19582   case X86::SEG_ALLOCA_64:
19583     return EmitLoweredSegAlloca(MI, BB);
19584   case X86::TLSCall_32:
19585   case X86::TLSCall_64:
19586     return EmitLoweredTLSCall(MI, BB);
19587   case X86::CMOV_GR8:
19588   case X86::CMOV_FR32:
19589   case X86::CMOV_FR64:
19590   case X86::CMOV_V4F32:
19591   case X86::CMOV_V2F64:
19592   case X86::CMOV_V2I64:
19593   case X86::CMOV_V8F32:
19594   case X86::CMOV_V4F64:
19595   case X86::CMOV_V4I64:
19596   case X86::CMOV_V16F32:
19597   case X86::CMOV_V8F64:
19598   case X86::CMOV_V8I64:
19599   case X86::CMOV_GR16:
19600   case X86::CMOV_GR32:
19601   case X86::CMOV_RFP32:
19602   case X86::CMOV_RFP64:
19603   case X86::CMOV_RFP80:
19604   case X86::CMOV_V8I1:
19605   case X86::CMOV_V16I1:
19606   case X86::CMOV_V32I1:
19607   case X86::CMOV_V64I1:
19608     return EmitLoweredSelect(MI, BB);
19609
19610   case X86::FP32_TO_INT16_IN_MEM:
19611   case X86::FP32_TO_INT32_IN_MEM:
19612   case X86::FP32_TO_INT64_IN_MEM:
19613   case X86::FP64_TO_INT16_IN_MEM:
19614   case X86::FP64_TO_INT32_IN_MEM:
19615   case X86::FP64_TO_INT64_IN_MEM:
19616   case X86::FP80_TO_INT16_IN_MEM:
19617   case X86::FP80_TO_INT32_IN_MEM:
19618   case X86::FP80_TO_INT64_IN_MEM: {
19619     MachineFunction *F = BB->getParent();
19620     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19621     DebugLoc DL = MI->getDebugLoc();
19622
19623     // Change the floating point control register to use "round towards zero"
19624     // mode when truncating to an integer value.
19625     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19626     addFrameReference(BuildMI(*BB, MI, DL,
19627                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19628
19629     // Load the old value of the high byte of the control word...
19630     unsigned OldCW =
19631       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19632     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19633                       CWFrameIdx);
19634
19635     // Set the high part to be round to zero...
19636     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19637       .addImm(0xC7F);
19638
19639     // Reload the modified control word now...
19640     addFrameReference(BuildMI(*BB, MI, DL,
19641                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19642
19643     // Restore the memory image of control word to original value
19644     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19645       .addReg(OldCW);
19646
19647     // Get the X86 opcode to use.
19648     unsigned Opc;
19649     switch (MI->getOpcode()) {
19650     default: llvm_unreachable("illegal opcode!");
19651     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19652     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19653     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19654     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19655     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19656     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19657     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19658     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19659     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19660     }
19661
19662     X86AddressMode AM;
19663     MachineOperand &Op = MI->getOperand(0);
19664     if (Op.isReg()) {
19665       AM.BaseType = X86AddressMode::RegBase;
19666       AM.Base.Reg = Op.getReg();
19667     } else {
19668       AM.BaseType = X86AddressMode::FrameIndexBase;
19669       AM.Base.FrameIndex = Op.getIndex();
19670     }
19671     Op = MI->getOperand(1);
19672     if (Op.isImm())
19673       AM.Scale = Op.getImm();
19674     Op = MI->getOperand(2);
19675     if (Op.isImm())
19676       AM.IndexReg = Op.getImm();
19677     Op = MI->getOperand(3);
19678     if (Op.isGlobal()) {
19679       AM.GV = Op.getGlobal();
19680     } else {
19681       AM.Disp = Op.getImm();
19682     }
19683     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19684                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19685
19686     // Reload the original control word now.
19687     addFrameReference(BuildMI(*BB, MI, DL,
19688                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19689
19690     MI->eraseFromParent();   // The pseudo instruction is gone now.
19691     return BB;
19692   }
19693     // String/text processing lowering.
19694   case X86::PCMPISTRM128REG:
19695   case X86::VPCMPISTRM128REG:
19696   case X86::PCMPISTRM128MEM:
19697   case X86::VPCMPISTRM128MEM:
19698   case X86::PCMPESTRM128REG:
19699   case X86::VPCMPESTRM128REG:
19700   case X86::PCMPESTRM128MEM:
19701   case X86::VPCMPESTRM128MEM:
19702     assert(Subtarget->hasSSE42() &&
19703            "Target must have SSE4.2 or AVX features enabled");
19704     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19705
19706   // String/text processing lowering.
19707   case X86::PCMPISTRIREG:
19708   case X86::VPCMPISTRIREG:
19709   case X86::PCMPISTRIMEM:
19710   case X86::VPCMPISTRIMEM:
19711   case X86::PCMPESTRIREG:
19712   case X86::VPCMPESTRIREG:
19713   case X86::PCMPESTRIMEM:
19714   case X86::VPCMPESTRIMEM:
19715     assert(Subtarget->hasSSE42() &&
19716            "Target must have SSE4.2 or AVX features enabled");
19717     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19718
19719   // Thread synchronization.
19720   case X86::MONITOR:
19721     return EmitMonitor(MI, BB, Subtarget);
19722
19723   // xbegin
19724   case X86::XBEGIN:
19725     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19726
19727   case X86::VASTART_SAVE_XMM_REGS:
19728     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19729
19730   case X86::VAARG_64:
19731     return EmitVAARG64WithCustomInserter(MI, BB);
19732
19733   case X86::EH_SjLj_SetJmp32:
19734   case X86::EH_SjLj_SetJmp64:
19735     return emitEHSjLjSetJmp(MI, BB);
19736
19737   case X86::EH_SjLj_LongJmp32:
19738   case X86::EH_SjLj_LongJmp64:
19739     return emitEHSjLjLongJmp(MI, BB);
19740
19741   case TargetOpcode::STATEPOINT:
19742     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19743     // this point in the process.  We diverge later.
19744     return emitPatchPoint(MI, BB);
19745
19746   case TargetOpcode::STACKMAP:
19747   case TargetOpcode::PATCHPOINT:
19748     return emitPatchPoint(MI, BB);
19749
19750   case X86::VFMADDPDr213r:
19751   case X86::VFMADDPSr213r:
19752   case X86::VFMADDSDr213r:
19753   case X86::VFMADDSSr213r:
19754   case X86::VFMSUBPDr213r:
19755   case X86::VFMSUBPSr213r:
19756   case X86::VFMSUBSDr213r:
19757   case X86::VFMSUBSSr213r:
19758   case X86::VFNMADDPDr213r:
19759   case X86::VFNMADDPSr213r:
19760   case X86::VFNMADDSDr213r:
19761   case X86::VFNMADDSSr213r:
19762   case X86::VFNMSUBPDr213r:
19763   case X86::VFNMSUBPSr213r:
19764   case X86::VFNMSUBSDr213r:
19765   case X86::VFNMSUBSSr213r:
19766   case X86::VFMADDSUBPDr213r:
19767   case X86::VFMADDSUBPSr213r:
19768   case X86::VFMSUBADDPDr213r:
19769   case X86::VFMSUBADDPSr213r:
19770   case X86::VFMADDPDr213rY:
19771   case X86::VFMADDPSr213rY:
19772   case X86::VFMSUBPDr213rY:
19773   case X86::VFMSUBPSr213rY:
19774   case X86::VFNMADDPDr213rY:
19775   case X86::VFNMADDPSr213rY:
19776   case X86::VFNMSUBPDr213rY:
19777   case X86::VFNMSUBPSr213rY:
19778   case X86::VFMADDSUBPDr213rY:
19779   case X86::VFMADDSUBPSr213rY:
19780   case X86::VFMSUBADDPDr213rY:
19781   case X86::VFMSUBADDPSr213rY:
19782     return emitFMA3Instr(MI, BB);
19783   }
19784 }
19785
19786 //===----------------------------------------------------------------------===//
19787 //                           X86 Optimization Hooks
19788 //===----------------------------------------------------------------------===//
19789
19790 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19791                                                       APInt &KnownZero,
19792                                                       APInt &KnownOne,
19793                                                       const SelectionDAG &DAG,
19794                                                       unsigned Depth) const {
19795   unsigned BitWidth = KnownZero.getBitWidth();
19796   unsigned Opc = Op.getOpcode();
19797   assert((Opc >= ISD::BUILTIN_OP_END ||
19798           Opc == ISD::INTRINSIC_WO_CHAIN ||
19799           Opc == ISD::INTRINSIC_W_CHAIN ||
19800           Opc == ISD::INTRINSIC_VOID) &&
19801          "Should use MaskedValueIsZero if you don't know whether Op"
19802          " is a target node!");
19803
19804   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19805   switch (Opc) {
19806   default: break;
19807   case X86ISD::ADD:
19808   case X86ISD::SUB:
19809   case X86ISD::ADC:
19810   case X86ISD::SBB:
19811   case X86ISD::SMUL:
19812   case X86ISD::UMUL:
19813   case X86ISD::INC:
19814   case X86ISD::DEC:
19815   case X86ISD::OR:
19816   case X86ISD::XOR:
19817   case X86ISD::AND:
19818     // These nodes' second result is a boolean.
19819     if (Op.getResNo() == 0)
19820       break;
19821     // Fallthrough
19822   case X86ISD::SETCC:
19823     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19824     break;
19825   case ISD::INTRINSIC_WO_CHAIN: {
19826     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19827     unsigned NumLoBits = 0;
19828     switch (IntId) {
19829     default: break;
19830     case Intrinsic::x86_sse_movmsk_ps:
19831     case Intrinsic::x86_avx_movmsk_ps_256:
19832     case Intrinsic::x86_sse2_movmsk_pd:
19833     case Intrinsic::x86_avx_movmsk_pd_256:
19834     case Intrinsic::x86_mmx_pmovmskb:
19835     case Intrinsic::x86_sse2_pmovmskb_128:
19836     case Intrinsic::x86_avx2_pmovmskb: {
19837       // High bits of movmskp{s|d}, pmovmskb are known zero.
19838       switch (IntId) {
19839         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19840         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19841         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19842         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19843         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19844         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19845         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19846         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19847       }
19848       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19849       break;
19850     }
19851     }
19852     break;
19853   }
19854   }
19855 }
19856
19857 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19858   SDValue Op,
19859   const SelectionDAG &,
19860   unsigned Depth) const {
19861   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19862   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19863     return Op.getValueType().getScalarType().getSizeInBits();
19864
19865   // Fallback case.
19866   return 1;
19867 }
19868
19869 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19870 /// node is a GlobalAddress + offset.
19871 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19872                                        const GlobalValue* &GA,
19873                                        int64_t &Offset) const {
19874   if (N->getOpcode() == X86ISD::Wrapper) {
19875     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19876       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19877       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19878       return true;
19879     }
19880   }
19881   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19882 }
19883
19884 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19885 /// same as extracting the high 128-bit part of 256-bit vector and then
19886 /// inserting the result into the low part of a new 256-bit vector
19887 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19888   EVT VT = SVOp->getValueType(0);
19889   unsigned NumElems = VT.getVectorNumElements();
19890
19891   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19892   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19893     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19894         SVOp->getMaskElt(j) >= 0)
19895       return false;
19896
19897   return true;
19898 }
19899
19900 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19901 /// same as extracting the low 128-bit part of 256-bit vector and then
19902 /// inserting the result into the high part of a new 256-bit vector
19903 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19904   EVT VT = SVOp->getValueType(0);
19905   unsigned NumElems = VT.getVectorNumElements();
19906
19907   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19908   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19909     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19910         SVOp->getMaskElt(j) >= 0)
19911       return false;
19912
19913   return true;
19914 }
19915
19916 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19917 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19918                                         TargetLowering::DAGCombinerInfo &DCI,
19919                                         const X86Subtarget* Subtarget) {
19920   SDLoc dl(N);
19921   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19922   SDValue V1 = SVOp->getOperand(0);
19923   SDValue V2 = SVOp->getOperand(1);
19924   EVT VT = SVOp->getValueType(0);
19925   unsigned NumElems = VT.getVectorNumElements();
19926
19927   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19928       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19929     //
19930     //                   0,0,0,...
19931     //                      |
19932     //    V      UNDEF    BUILD_VECTOR    UNDEF
19933     //     \      /           \           /
19934     //  CONCAT_VECTOR         CONCAT_VECTOR
19935     //         \                  /
19936     //          \                /
19937     //          RESULT: V + zero extended
19938     //
19939     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19940         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19941         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19942       return SDValue();
19943
19944     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19945       return SDValue();
19946
19947     // To match the shuffle mask, the first half of the mask should
19948     // be exactly the first vector, and all the rest a splat with the
19949     // first element of the second one.
19950     for (unsigned i = 0; i != NumElems/2; ++i)
19951       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19952           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19953         return SDValue();
19954
19955     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19956     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19957       if (Ld->hasNUsesOfValue(1, 0)) {
19958         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19959         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19960         SDValue ResNode =
19961           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19962                                   Ld->getMemoryVT(),
19963                                   Ld->getPointerInfo(),
19964                                   Ld->getAlignment(),
19965                                   false/*isVolatile*/, true/*ReadMem*/,
19966                                   false/*WriteMem*/);
19967
19968         // Make sure the newly-created LOAD is in the same position as Ld in
19969         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19970         // and update uses of Ld's output chain to use the TokenFactor.
19971         if (Ld->hasAnyUseOfValue(1)) {
19972           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19973                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19974           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19975           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19976                                  SDValue(ResNode.getNode(), 1));
19977         }
19978
19979         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19980       }
19981     }
19982
19983     // Emit a zeroed vector and insert the desired subvector on its
19984     // first half.
19985     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19986     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19987     return DCI.CombineTo(N, InsV);
19988   }
19989
19990   //===--------------------------------------------------------------------===//
19991   // Combine some shuffles into subvector extracts and inserts:
19992   //
19993
19994   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19995   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19996     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19997     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19998     return DCI.CombineTo(N, InsV);
19999   }
20000
20001   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20002   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20003     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20004     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20005     return DCI.CombineTo(N, InsV);
20006   }
20007
20008   return SDValue();
20009 }
20010
20011 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20012 /// possible.
20013 ///
20014 /// This is the leaf of the recursive combinine below. When we have found some
20015 /// chain of single-use x86 shuffle instructions and accumulated the combined
20016 /// shuffle mask represented by them, this will try to pattern match that mask
20017 /// into either a single instruction if there is a special purpose instruction
20018 /// for this operation, or into a PSHUFB instruction which is a fully general
20019 /// instruction but should only be used to replace chains over a certain depth.
20020 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20021                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20022                                    TargetLowering::DAGCombinerInfo &DCI,
20023                                    const X86Subtarget *Subtarget) {
20024   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20025
20026   // Find the operand that enters the chain. Note that multiple uses are OK
20027   // here, we're not going to remove the operand we find.
20028   SDValue Input = Op.getOperand(0);
20029   while (Input.getOpcode() == ISD::BITCAST)
20030     Input = Input.getOperand(0);
20031
20032   MVT VT = Input.getSimpleValueType();
20033   MVT RootVT = Root.getSimpleValueType();
20034   SDLoc DL(Root);
20035
20036   // Just remove no-op shuffle masks.
20037   if (Mask.size() == 1) {
20038     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
20039                   /*AddTo*/ true);
20040     return true;
20041   }
20042
20043   // Use the float domain if the operand type is a floating point type.
20044   bool FloatDomain = VT.isFloatingPoint();
20045
20046   // For floating point shuffles, we don't have free copies in the shuffle
20047   // instructions or the ability to load as part of the instruction, so
20048   // canonicalize their shuffles to UNPCK or MOV variants.
20049   //
20050   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20051   // vectors because it can have a load folded into it that UNPCK cannot. This
20052   // doesn't preclude something switching to the shorter encoding post-RA.
20053   //
20054   // FIXME: Should teach these routines about AVX vector widths.
20055   if (FloatDomain && VT.getSizeInBits() == 128) {
20056     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20057       bool Lo = Mask.equals({0, 0});
20058       unsigned Shuffle;
20059       MVT ShuffleVT;
20060       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20061       // is no slower than UNPCKLPD but has the option to fold the input operand
20062       // into even an unaligned memory load.
20063       if (Lo && Subtarget->hasSSE3()) {
20064         Shuffle = X86ISD::MOVDDUP;
20065         ShuffleVT = MVT::v2f64;
20066       } else {
20067         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20068         // than the UNPCK variants.
20069         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20070         ShuffleVT = MVT::v4f32;
20071       }
20072       if (Depth == 1 && Root->getOpcode() == Shuffle)
20073         return false; // Nothing to do!
20074       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20075       DCI.AddToWorklist(Op.getNode());
20076       if (Shuffle == X86ISD::MOVDDUP)
20077         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20078       else
20079         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20080       DCI.AddToWorklist(Op.getNode());
20081       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20082                     /*AddTo*/ true);
20083       return true;
20084     }
20085     if (Subtarget->hasSSE3() &&
20086         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20087       bool Lo = Mask.equals({0, 0, 2, 2});
20088       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20089       MVT ShuffleVT = MVT::v4f32;
20090       if (Depth == 1 && Root->getOpcode() == Shuffle)
20091         return false; // Nothing to do!
20092       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20093       DCI.AddToWorklist(Op.getNode());
20094       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20095       DCI.AddToWorklist(Op.getNode());
20096       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20097                     /*AddTo*/ true);
20098       return true;
20099     }
20100     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20101       bool Lo = Mask.equals({0, 0, 1, 1});
20102       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20103       MVT ShuffleVT = MVT::v4f32;
20104       if (Depth == 1 && Root->getOpcode() == Shuffle)
20105         return false; // Nothing to do!
20106       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20107       DCI.AddToWorklist(Op.getNode());
20108       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20109       DCI.AddToWorklist(Op.getNode());
20110       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20111                     /*AddTo*/ true);
20112       return true;
20113     }
20114   }
20115
20116   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20117   // variants as none of these have single-instruction variants that are
20118   // superior to the UNPCK formulation.
20119   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20120       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20121        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20122        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20123        Mask.equals(
20124            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20125     bool Lo = Mask[0] == 0;
20126     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20127     if (Depth == 1 && Root->getOpcode() == Shuffle)
20128       return false; // Nothing to do!
20129     MVT ShuffleVT;
20130     switch (Mask.size()) {
20131     case 8:
20132       ShuffleVT = MVT::v8i16;
20133       break;
20134     case 16:
20135       ShuffleVT = MVT::v16i8;
20136       break;
20137     default:
20138       llvm_unreachable("Impossible mask size!");
20139     };
20140     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20141     DCI.AddToWorklist(Op.getNode());
20142     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20143     DCI.AddToWorklist(Op.getNode());
20144     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20145                   /*AddTo*/ true);
20146     return true;
20147   }
20148
20149   // Don't try to re-form single instruction chains under any circumstances now
20150   // that we've done encoding canonicalization for them.
20151   if (Depth < 2)
20152     return false;
20153
20154   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20155   // can replace them with a single PSHUFB instruction profitably. Intel's
20156   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20157   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20158   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20159     SmallVector<SDValue, 16> PSHUFBMask;
20160     int NumBytes = VT.getSizeInBits() / 8;
20161     int Ratio = NumBytes / Mask.size();
20162     for (int i = 0; i < NumBytes; ++i) {
20163       if (Mask[i / Ratio] == SM_SentinelUndef) {
20164         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20165         continue;
20166       }
20167       int M = Mask[i / Ratio] != SM_SentinelZero
20168                   ? Ratio * Mask[i / Ratio] + i % Ratio
20169                   : 255;
20170       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20171     }
20172     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20173     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20174     DCI.AddToWorklist(Op.getNode());
20175     SDValue PSHUFBMaskOp =
20176         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20177     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20178     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20179     DCI.AddToWorklist(Op.getNode());
20180     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20181                   /*AddTo*/ true);
20182     return true;
20183   }
20184
20185   // Failed to find any combines.
20186   return false;
20187 }
20188
20189 /// \brief Fully generic combining of x86 shuffle instructions.
20190 ///
20191 /// This should be the last combine run over the x86 shuffle instructions. Once
20192 /// they have been fully optimized, this will recursively consider all chains
20193 /// of single-use shuffle instructions, build a generic model of the cumulative
20194 /// shuffle operation, and check for simpler instructions which implement this
20195 /// operation. We use this primarily for two purposes:
20196 ///
20197 /// 1) Collapse generic shuffles to specialized single instructions when
20198 ///    equivalent. In most cases, this is just an encoding size win, but
20199 ///    sometimes we will collapse multiple generic shuffles into a single
20200 ///    special-purpose shuffle.
20201 /// 2) Look for sequences of shuffle instructions with 3 or more total
20202 ///    instructions, and replace them with the slightly more expensive SSSE3
20203 ///    PSHUFB instruction if available. We do this as the last combining step
20204 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20205 ///    a suitable short sequence of other instructions. The PHUFB will either
20206 ///    use a register or have to read from memory and so is slightly (but only
20207 ///    slightly) more expensive than the other shuffle instructions.
20208 ///
20209 /// Because this is inherently a quadratic operation (for each shuffle in
20210 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20211 /// This should never be an issue in practice as the shuffle lowering doesn't
20212 /// produce sequences of more than 8 instructions.
20213 ///
20214 /// FIXME: We will currently miss some cases where the redundant shuffling
20215 /// would simplify under the threshold for PSHUFB formation because of
20216 /// combine-ordering. To fix this, we should do the redundant instruction
20217 /// combining in this recursive walk.
20218 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20219                                           ArrayRef<int> RootMask,
20220                                           int Depth, bool HasPSHUFB,
20221                                           SelectionDAG &DAG,
20222                                           TargetLowering::DAGCombinerInfo &DCI,
20223                                           const X86Subtarget *Subtarget) {
20224   // Bound the depth of our recursive combine because this is ultimately
20225   // quadratic in nature.
20226   if (Depth > 8)
20227     return false;
20228
20229   // Directly rip through bitcasts to find the underlying operand.
20230   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20231     Op = Op.getOperand(0);
20232
20233   MVT VT = Op.getSimpleValueType();
20234   if (!VT.isVector())
20235     return false; // Bail if we hit a non-vector.
20236
20237   assert(Root.getSimpleValueType().isVector() &&
20238          "Shuffles operate on vector types!");
20239   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20240          "Can only combine shuffles of the same vector register size.");
20241
20242   if (!isTargetShuffle(Op.getOpcode()))
20243     return false;
20244   SmallVector<int, 16> OpMask;
20245   bool IsUnary;
20246   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20247   // We only can combine unary shuffles which we can decode the mask for.
20248   if (!HaveMask || !IsUnary)
20249     return false;
20250
20251   assert(VT.getVectorNumElements() == OpMask.size() &&
20252          "Different mask size from vector size!");
20253   assert(((RootMask.size() > OpMask.size() &&
20254            RootMask.size() % OpMask.size() == 0) ||
20255           (OpMask.size() > RootMask.size() &&
20256            OpMask.size() % RootMask.size() == 0) ||
20257           OpMask.size() == RootMask.size()) &&
20258          "The smaller number of elements must divide the larger.");
20259   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20260   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20261   assert(((RootRatio == 1 && OpRatio == 1) ||
20262           (RootRatio == 1) != (OpRatio == 1)) &&
20263          "Must not have a ratio for both incoming and op masks!");
20264
20265   SmallVector<int, 16> Mask;
20266   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20267
20268   // Merge this shuffle operation's mask into our accumulated mask. Note that
20269   // this shuffle's mask will be the first applied to the input, followed by the
20270   // root mask to get us all the way to the root value arrangement. The reason
20271   // for this order is that we are recursing up the operation chain.
20272   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20273     int RootIdx = i / RootRatio;
20274     if (RootMask[RootIdx] < 0) {
20275       // This is a zero or undef lane, we're done.
20276       Mask.push_back(RootMask[RootIdx]);
20277       continue;
20278     }
20279
20280     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20281     int OpIdx = RootMaskedIdx / OpRatio;
20282     if (OpMask[OpIdx] < 0) {
20283       // The incoming lanes are zero or undef, it doesn't matter which ones we
20284       // are using.
20285       Mask.push_back(OpMask[OpIdx]);
20286       continue;
20287     }
20288
20289     // Ok, we have non-zero lanes, map them through.
20290     Mask.push_back(OpMask[OpIdx] * OpRatio +
20291                    RootMaskedIdx % OpRatio);
20292   }
20293
20294   // See if we can recurse into the operand to combine more things.
20295   switch (Op.getOpcode()) {
20296     case X86ISD::PSHUFB:
20297       HasPSHUFB = true;
20298     case X86ISD::PSHUFD:
20299     case X86ISD::PSHUFHW:
20300     case X86ISD::PSHUFLW:
20301       if (Op.getOperand(0).hasOneUse() &&
20302           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20303                                         HasPSHUFB, DAG, DCI, Subtarget))
20304         return true;
20305       break;
20306
20307     case X86ISD::UNPCKL:
20308     case X86ISD::UNPCKH:
20309       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20310       // We can't check for single use, we have to check that this shuffle is the only user.
20311       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20312           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20313                                         HasPSHUFB, DAG, DCI, Subtarget))
20314           return true;
20315       break;
20316   }
20317
20318   // Minor canonicalization of the accumulated shuffle mask to make it easier
20319   // to match below. All this does is detect masks with squential pairs of
20320   // elements, and shrink them to the half-width mask. It does this in a loop
20321   // so it will reduce the size of the mask to the minimal width mask which
20322   // performs an equivalent shuffle.
20323   SmallVector<int, 16> WidenedMask;
20324   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20325     Mask = std::move(WidenedMask);
20326     WidenedMask.clear();
20327   }
20328
20329   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20330                                 Subtarget);
20331 }
20332
20333 /// \brief Get the PSHUF-style mask from PSHUF node.
20334 ///
20335 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20336 /// PSHUF-style masks that can be reused with such instructions.
20337 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20338   MVT VT = N.getSimpleValueType();
20339   SmallVector<int, 4> Mask;
20340   bool IsUnary;
20341   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20342   (void)HaveMask;
20343   assert(HaveMask);
20344
20345   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20346   // matter. Check that the upper masks are repeats and remove them.
20347   if (VT.getSizeInBits() > 128) {
20348     int LaneElts = 128 / VT.getScalarSizeInBits();
20349 #ifndef NDEBUG
20350     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20351       for (int j = 0; j < LaneElts; ++j)
20352         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20353                "Mask doesn't repeat in high 128-bit lanes!");
20354 #endif
20355     Mask.resize(LaneElts);
20356   }
20357
20358   switch (N.getOpcode()) {
20359   case X86ISD::PSHUFD:
20360     return Mask;
20361   case X86ISD::PSHUFLW:
20362     Mask.resize(4);
20363     return Mask;
20364   case X86ISD::PSHUFHW:
20365     Mask.erase(Mask.begin(), Mask.begin() + 4);
20366     for (int &M : Mask)
20367       M -= 4;
20368     return Mask;
20369   default:
20370     llvm_unreachable("No valid shuffle instruction found!");
20371   }
20372 }
20373
20374 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20375 ///
20376 /// We walk up the chain and look for a combinable shuffle, skipping over
20377 /// shuffles that we could hoist this shuffle's transformation past without
20378 /// altering anything.
20379 static SDValue
20380 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20381                              SelectionDAG &DAG,
20382                              TargetLowering::DAGCombinerInfo &DCI) {
20383   assert(N.getOpcode() == X86ISD::PSHUFD &&
20384          "Called with something other than an x86 128-bit half shuffle!");
20385   SDLoc DL(N);
20386
20387   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20388   // of the shuffles in the chain so that we can form a fresh chain to replace
20389   // this one.
20390   SmallVector<SDValue, 8> Chain;
20391   SDValue V = N.getOperand(0);
20392   for (; V.hasOneUse(); V = V.getOperand(0)) {
20393     switch (V.getOpcode()) {
20394     default:
20395       return SDValue(); // Nothing combined!
20396
20397     case ISD::BITCAST:
20398       // Skip bitcasts as we always know the type for the target specific
20399       // instructions.
20400       continue;
20401
20402     case X86ISD::PSHUFD:
20403       // Found another dword shuffle.
20404       break;
20405
20406     case X86ISD::PSHUFLW:
20407       // Check that the low words (being shuffled) are the identity in the
20408       // dword shuffle, and the high words are self-contained.
20409       if (Mask[0] != 0 || Mask[1] != 1 ||
20410           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20411         return SDValue();
20412
20413       Chain.push_back(V);
20414       continue;
20415
20416     case X86ISD::PSHUFHW:
20417       // Check that the high words (being shuffled) are the identity in the
20418       // dword shuffle, and the low words are self-contained.
20419       if (Mask[2] != 2 || Mask[3] != 3 ||
20420           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20421         return SDValue();
20422
20423       Chain.push_back(V);
20424       continue;
20425
20426     case X86ISD::UNPCKL:
20427     case X86ISD::UNPCKH:
20428       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20429       // shuffle into a preceding word shuffle.
20430       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20431           V.getSimpleValueType().getScalarType() != MVT::i16)
20432         return SDValue();
20433
20434       // Search for a half-shuffle which we can combine with.
20435       unsigned CombineOp =
20436           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20437       if (V.getOperand(0) != V.getOperand(1) ||
20438           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20439         return SDValue();
20440       Chain.push_back(V);
20441       V = V.getOperand(0);
20442       do {
20443         switch (V.getOpcode()) {
20444         default:
20445           return SDValue(); // Nothing to combine.
20446
20447         case X86ISD::PSHUFLW:
20448         case X86ISD::PSHUFHW:
20449           if (V.getOpcode() == CombineOp)
20450             break;
20451
20452           Chain.push_back(V);
20453
20454           // Fallthrough!
20455         case ISD::BITCAST:
20456           V = V.getOperand(0);
20457           continue;
20458         }
20459         break;
20460       } while (V.hasOneUse());
20461       break;
20462     }
20463     // Break out of the loop if we break out of the switch.
20464     break;
20465   }
20466
20467   if (!V.hasOneUse())
20468     // We fell out of the loop without finding a viable combining instruction.
20469     return SDValue();
20470
20471   // Merge this node's mask and our incoming mask.
20472   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20473   for (int &M : Mask)
20474     M = VMask[M];
20475   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20476                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20477
20478   // Rebuild the chain around this new shuffle.
20479   while (!Chain.empty()) {
20480     SDValue W = Chain.pop_back_val();
20481
20482     if (V.getValueType() != W.getOperand(0).getValueType())
20483       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20484
20485     switch (W.getOpcode()) {
20486     default:
20487       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20488
20489     case X86ISD::UNPCKL:
20490     case X86ISD::UNPCKH:
20491       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20492       break;
20493
20494     case X86ISD::PSHUFD:
20495     case X86ISD::PSHUFLW:
20496     case X86ISD::PSHUFHW:
20497       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20498       break;
20499     }
20500   }
20501   if (V.getValueType() != N.getValueType())
20502     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20503
20504   // Return the new chain to replace N.
20505   return V;
20506 }
20507
20508 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20509 ///
20510 /// We walk up the chain, skipping shuffles of the other half and looking
20511 /// through shuffles which switch halves trying to find a shuffle of the same
20512 /// pair of dwords.
20513 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20514                                         SelectionDAG &DAG,
20515                                         TargetLowering::DAGCombinerInfo &DCI) {
20516   assert(
20517       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20518       "Called with something other than an x86 128-bit half shuffle!");
20519   SDLoc DL(N);
20520   unsigned CombineOpcode = N.getOpcode();
20521
20522   // Walk up a single-use chain looking for a combinable shuffle.
20523   SDValue V = N.getOperand(0);
20524   for (; V.hasOneUse(); V = V.getOperand(0)) {
20525     switch (V.getOpcode()) {
20526     default:
20527       return false; // Nothing combined!
20528
20529     case ISD::BITCAST:
20530       // Skip bitcasts as we always know the type for the target specific
20531       // instructions.
20532       continue;
20533
20534     case X86ISD::PSHUFLW:
20535     case X86ISD::PSHUFHW:
20536       if (V.getOpcode() == CombineOpcode)
20537         break;
20538
20539       // Other-half shuffles are no-ops.
20540       continue;
20541     }
20542     // Break out of the loop if we break out of the switch.
20543     break;
20544   }
20545
20546   if (!V.hasOneUse())
20547     // We fell out of the loop without finding a viable combining instruction.
20548     return false;
20549
20550   // Combine away the bottom node as its shuffle will be accumulated into
20551   // a preceding shuffle.
20552   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20553
20554   // Record the old value.
20555   SDValue Old = V;
20556
20557   // Merge this node's mask and our incoming mask (adjusted to account for all
20558   // the pshufd instructions encountered).
20559   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20560   for (int &M : Mask)
20561     M = VMask[M];
20562   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20563                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20564
20565   // Check that the shuffles didn't cancel each other out. If not, we need to
20566   // combine to the new one.
20567   if (Old != V)
20568     // Replace the combinable shuffle with the combined one, updating all users
20569     // so that we re-evaluate the chain here.
20570     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20571
20572   return true;
20573 }
20574
20575 /// \brief Try to combine x86 target specific shuffles.
20576 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20577                                            TargetLowering::DAGCombinerInfo &DCI,
20578                                            const X86Subtarget *Subtarget) {
20579   SDLoc DL(N);
20580   MVT VT = N.getSimpleValueType();
20581   SmallVector<int, 4> Mask;
20582
20583   switch (N.getOpcode()) {
20584   case X86ISD::PSHUFD:
20585   case X86ISD::PSHUFLW:
20586   case X86ISD::PSHUFHW:
20587     Mask = getPSHUFShuffleMask(N);
20588     assert(Mask.size() == 4);
20589     break;
20590   default:
20591     return SDValue();
20592   }
20593
20594   // Nuke no-op shuffles that show up after combining.
20595   if (isNoopShuffleMask(Mask))
20596     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20597
20598   // Look for simplifications involving one or two shuffle instructions.
20599   SDValue V = N.getOperand(0);
20600   switch (N.getOpcode()) {
20601   default:
20602     break;
20603   case X86ISD::PSHUFLW:
20604   case X86ISD::PSHUFHW:
20605     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20606
20607     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20608       return SDValue(); // We combined away this shuffle, so we're done.
20609
20610     // See if this reduces to a PSHUFD which is no more expensive and can
20611     // combine with more operations. Note that it has to at least flip the
20612     // dwords as otherwise it would have been removed as a no-op.
20613     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20614       int DMask[] = {0, 1, 2, 3};
20615       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20616       DMask[DOffset + 0] = DOffset + 1;
20617       DMask[DOffset + 1] = DOffset + 0;
20618       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20619       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20620       DCI.AddToWorklist(V.getNode());
20621       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20622                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20623       DCI.AddToWorklist(V.getNode());
20624       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20625     }
20626
20627     // Look for shuffle patterns which can be implemented as a single unpack.
20628     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20629     // only works when we have a PSHUFD followed by two half-shuffles.
20630     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20631         (V.getOpcode() == X86ISD::PSHUFLW ||
20632          V.getOpcode() == X86ISD::PSHUFHW) &&
20633         V.getOpcode() != N.getOpcode() &&
20634         V.hasOneUse()) {
20635       SDValue D = V.getOperand(0);
20636       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20637         D = D.getOperand(0);
20638       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20639         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20640         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20641         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20642         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20643         int WordMask[8];
20644         for (int i = 0; i < 4; ++i) {
20645           WordMask[i + NOffset] = Mask[i] + NOffset;
20646           WordMask[i + VOffset] = VMask[i] + VOffset;
20647         }
20648         // Map the word mask through the DWord mask.
20649         int MappedMask[8];
20650         for (int i = 0; i < 8; ++i)
20651           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20652         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20653             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20654           // We can replace all three shuffles with an unpack.
20655           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20656           DCI.AddToWorklist(V.getNode());
20657           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20658                                                 : X86ISD::UNPCKH,
20659                              DL, VT, V, V);
20660         }
20661       }
20662     }
20663
20664     break;
20665
20666   case X86ISD::PSHUFD:
20667     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20668       return NewN;
20669
20670     break;
20671   }
20672
20673   return SDValue();
20674 }
20675
20676 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20677 ///
20678 /// We combine this directly on the abstract vector shuffle nodes so it is
20679 /// easier to generically match. We also insert dummy vector shuffle nodes for
20680 /// the operands which explicitly discard the lanes which are unused by this
20681 /// operation to try to flow through the rest of the combiner the fact that
20682 /// they're unused.
20683 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20684   SDLoc DL(N);
20685   EVT VT = N->getValueType(0);
20686
20687   // We only handle target-independent shuffles.
20688   // FIXME: It would be easy and harmless to use the target shuffle mask
20689   // extraction tool to support more.
20690   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20691     return SDValue();
20692
20693   auto *SVN = cast<ShuffleVectorSDNode>(N);
20694   ArrayRef<int> Mask = SVN->getMask();
20695   SDValue V1 = N->getOperand(0);
20696   SDValue V2 = N->getOperand(1);
20697
20698   // We require the first shuffle operand to be the SUB node, and the second to
20699   // be the ADD node.
20700   // FIXME: We should support the commuted patterns.
20701   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20702     return SDValue();
20703
20704   // If there are other uses of these operations we can't fold them.
20705   if (!V1->hasOneUse() || !V2->hasOneUse())
20706     return SDValue();
20707
20708   // Ensure that both operations have the same operands. Note that we can
20709   // commute the FADD operands.
20710   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20711   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20712       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20713     return SDValue();
20714
20715   // We're looking for blends between FADD and FSUB nodes. We insist on these
20716   // nodes being lined up in a specific expected pattern.
20717   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20718         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20719         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20720     return SDValue();
20721
20722   // Only specific types are legal at this point, assert so we notice if and
20723   // when these change.
20724   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20725           VT == MVT::v4f64) &&
20726          "Unknown vector type encountered!");
20727
20728   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20729 }
20730
20731 /// PerformShuffleCombine - Performs several different shuffle combines.
20732 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20733                                      TargetLowering::DAGCombinerInfo &DCI,
20734                                      const X86Subtarget *Subtarget) {
20735   SDLoc dl(N);
20736   SDValue N0 = N->getOperand(0);
20737   SDValue N1 = N->getOperand(1);
20738   EVT VT = N->getValueType(0);
20739
20740   // Don't create instructions with illegal types after legalize types has run.
20741   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20742   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20743     return SDValue();
20744
20745   // If we have legalized the vector types, look for blends of FADD and FSUB
20746   // nodes that we can fuse into an ADDSUB node.
20747   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20748     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20749       return AddSub;
20750
20751   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20752   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20753       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20754     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20755
20756   // During Type Legalization, when promoting illegal vector types,
20757   // the backend might introduce new shuffle dag nodes and bitcasts.
20758   //
20759   // This code performs the following transformation:
20760   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20761   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20762   //
20763   // We do this only if both the bitcast and the BINOP dag nodes have
20764   // one use. Also, perform this transformation only if the new binary
20765   // operation is legal. This is to avoid introducing dag nodes that
20766   // potentially need to be further expanded (or custom lowered) into a
20767   // less optimal sequence of dag nodes.
20768   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20769       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20770       N0.getOpcode() == ISD::BITCAST) {
20771     SDValue BC0 = N0.getOperand(0);
20772     EVT SVT = BC0.getValueType();
20773     unsigned Opcode = BC0.getOpcode();
20774     unsigned NumElts = VT.getVectorNumElements();
20775
20776     if (BC0.hasOneUse() && SVT.isVector() &&
20777         SVT.getVectorNumElements() * 2 == NumElts &&
20778         TLI.isOperationLegal(Opcode, VT)) {
20779       bool CanFold = false;
20780       switch (Opcode) {
20781       default : break;
20782       case ISD::ADD :
20783       case ISD::FADD :
20784       case ISD::SUB :
20785       case ISD::FSUB :
20786       case ISD::MUL :
20787       case ISD::FMUL :
20788         CanFold = true;
20789       }
20790
20791       unsigned SVTNumElts = SVT.getVectorNumElements();
20792       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20793       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20794         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20795       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20796         CanFold = SVOp->getMaskElt(i) < 0;
20797
20798       if (CanFold) {
20799         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20800         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20801         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20802         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20803       }
20804     }
20805   }
20806
20807   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20808   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20809   // consecutive, non-overlapping, and in the right order.
20810   SmallVector<SDValue, 16> Elts;
20811   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20812     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20813
20814   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20815   if (LD.getNode())
20816     return LD;
20817
20818   if (isTargetShuffle(N->getOpcode())) {
20819     SDValue Shuffle =
20820         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20821     if (Shuffle.getNode())
20822       return Shuffle;
20823
20824     // Try recursively combining arbitrary sequences of x86 shuffle
20825     // instructions into higher-order shuffles. We do this after combining
20826     // specific PSHUF instruction sequences into their minimal form so that we
20827     // can evaluate how many specialized shuffle instructions are involved in
20828     // a particular chain.
20829     SmallVector<int, 1> NonceMask; // Just a placeholder.
20830     NonceMask.push_back(0);
20831     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20832                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20833                                       DCI, Subtarget))
20834       return SDValue(); // This routine will use CombineTo to replace N.
20835   }
20836
20837   return SDValue();
20838 }
20839
20840 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20841 /// specific shuffle of a load can be folded into a single element load.
20842 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20843 /// shuffles have been custom lowered so we need to handle those here.
20844 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20845                                          TargetLowering::DAGCombinerInfo &DCI) {
20846   if (DCI.isBeforeLegalizeOps())
20847     return SDValue();
20848
20849   SDValue InVec = N->getOperand(0);
20850   SDValue EltNo = N->getOperand(1);
20851
20852   if (!isa<ConstantSDNode>(EltNo))
20853     return SDValue();
20854
20855   EVT OriginalVT = InVec.getValueType();
20856
20857   if (InVec.getOpcode() == ISD::BITCAST) {
20858     // Don't duplicate a load with other uses.
20859     if (!InVec.hasOneUse())
20860       return SDValue();
20861     EVT BCVT = InVec.getOperand(0).getValueType();
20862     if (!BCVT.isVector() || 
20863         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20864       return SDValue();
20865     InVec = InVec.getOperand(0);
20866   }
20867
20868   EVT CurrentVT = InVec.getValueType();
20869
20870   if (!isTargetShuffle(InVec.getOpcode()))
20871     return SDValue();
20872
20873   // Don't duplicate a load with other uses.
20874   if (!InVec.hasOneUse())
20875     return SDValue();
20876
20877   SmallVector<int, 16> ShuffleMask;
20878   bool UnaryShuffle;
20879   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20880                             ShuffleMask, UnaryShuffle))
20881     return SDValue();
20882
20883   // Select the input vector, guarding against out of range extract vector.
20884   unsigned NumElems = CurrentVT.getVectorNumElements();
20885   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20886   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20887   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20888                                          : InVec.getOperand(1);
20889
20890   // If inputs to shuffle are the same for both ops, then allow 2 uses
20891   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20892                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20893
20894   if (LdNode.getOpcode() == ISD::BITCAST) {
20895     // Don't duplicate a load with other uses.
20896     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20897       return SDValue();
20898
20899     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20900     LdNode = LdNode.getOperand(0);
20901   }
20902
20903   if (!ISD::isNormalLoad(LdNode.getNode()))
20904     return SDValue();
20905
20906   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20907
20908   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20909     return SDValue();
20910
20911   EVT EltVT = N->getValueType(0);
20912   // If there's a bitcast before the shuffle, check if the load type and
20913   // alignment is valid.
20914   unsigned Align = LN0->getAlignment();
20915   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20916   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20917       EltVT.getTypeForEVT(*DAG.getContext()));
20918
20919   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20920     return SDValue();
20921
20922   // All checks match so transform back to vector_shuffle so that DAG combiner
20923   // can finish the job
20924   SDLoc dl(N);
20925
20926   // Create shuffle node taking into account the case that its a unary shuffle
20927   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20928                                    : InVec.getOperand(1);
20929   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20930                                  InVec.getOperand(0), Shuffle,
20931                                  &ShuffleMask[0]);
20932   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20933   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20934                      EltNo);
20935 }
20936
20937 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20938 /// special and don't usually play with other vector types, it's better to
20939 /// handle them early to be sure we emit efficient code by avoiding
20940 /// store-load conversions.
20941 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20942   if (N->getValueType(0) != MVT::x86mmx ||
20943       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20944       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20945     return SDValue();
20946
20947   SDValue V = N->getOperand(0);
20948   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20949   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20950     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20951                        N->getValueType(0), V.getOperand(0));
20952
20953   return SDValue();
20954 }
20955
20956 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20957 /// generation and convert it from being a bunch of shuffles and extracts
20958 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20959 /// storing the value and loading scalars back, while for x64 we should
20960 /// use 64-bit extracts and shifts.
20961 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20962                                          TargetLowering::DAGCombinerInfo &DCI) {
20963   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20964   if (NewOp.getNode())
20965     return NewOp;
20966
20967   SDValue InputVector = N->getOperand(0);
20968   SDLoc dl(InputVector);
20969   // Detect mmx to i32 conversion through a v2i32 elt extract.
20970   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20971       N->getValueType(0) == MVT::i32 &&
20972       InputVector.getValueType() == MVT::v2i32) {
20973
20974     // The bitcast source is a direct mmx result.
20975     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20976     if (MMXSrc.getValueType() == MVT::x86mmx)
20977       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20978                          N->getValueType(0),
20979                          InputVector.getNode()->getOperand(0));
20980
20981     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20982     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20983     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20984         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20985         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20986         MMXSrcOp.getValueType() == MVT::v1i64 &&
20987         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20988       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20989                          N->getValueType(0),
20990                          MMXSrcOp.getOperand(0));
20991   }
20992
20993   EVT VT = N->getValueType(0);
20994   
20995   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
20996       InputVector.getOpcode() == ISD::BITCAST &&
20997       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
20998     uint64_t ExtractedElt =
20999           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21000     uint64_t InputValue =
21001           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21002     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21003     return DAG.getConstant(Res, dl, MVT::i1);
21004   }
21005   // Only operate on vectors of 4 elements, where the alternative shuffling
21006   // gets to be more expensive.
21007   if (InputVector.getValueType() != MVT::v4i32)
21008     return SDValue();
21009
21010   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21011   // single use which is a sign-extend or zero-extend, and all elements are
21012   // used.
21013   SmallVector<SDNode *, 4> Uses;
21014   unsigned ExtractedElements = 0;
21015   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21016        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21017     if (UI.getUse().getResNo() != InputVector.getResNo())
21018       return SDValue();
21019
21020     SDNode *Extract = *UI;
21021     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21022       return SDValue();
21023
21024     if (Extract->getValueType(0) != MVT::i32)
21025       return SDValue();
21026     if (!Extract->hasOneUse())
21027       return SDValue();
21028     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21029         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21030       return SDValue();
21031     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21032       return SDValue();
21033
21034     // Record which element was extracted.
21035     ExtractedElements |=
21036       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21037
21038     Uses.push_back(Extract);
21039   }
21040
21041   // If not all the elements were used, this may not be worthwhile.
21042   if (ExtractedElements != 15)
21043     return SDValue();
21044
21045   // Ok, we've now decided to do the transformation.
21046   // If 64-bit shifts are legal, use the extract-shift sequence,
21047   // otherwise bounce the vector off the cache.
21048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21049   SDValue Vals[4];
21050
21051   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21052     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
21053     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21054     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21055       DAG.getConstant(0, dl, VecIdxTy));
21056     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21057       DAG.getConstant(1, dl, VecIdxTy));
21058
21059     SDValue ShAmt = DAG.getConstant(32, dl,
21060       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21061     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21062     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21063       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21064     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21065     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21066       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21067   } else {
21068     // Store the value to a temporary stack slot.
21069     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21070     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21071       MachinePointerInfo(), false, false, 0);
21072
21073     EVT ElementType = InputVector.getValueType().getVectorElementType();
21074     unsigned EltSize = ElementType.getSizeInBits() / 8;
21075
21076     // Replace each use (extract) with a load of the appropriate element.
21077     for (unsigned i = 0; i < 4; ++i) {
21078       uint64_t Offset = EltSize * i;
21079       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21080
21081       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21082                                        StackPtr, OffsetVal);
21083
21084       // Load the scalar.
21085       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21086                             ScalarAddr, MachinePointerInfo(),
21087                             false, false, false, 0);
21088
21089     }
21090   }
21091
21092   // Replace the extracts
21093   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21094     UE = Uses.end(); UI != UE; ++UI) {
21095     SDNode *Extract = *UI;
21096
21097     SDValue Idx = Extract->getOperand(1);
21098     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21099     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21100   }
21101
21102   // The replacement was made in place; don't return anything.
21103   return SDValue();
21104 }
21105
21106 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21107 static std::pair<unsigned, bool>
21108 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21109                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21110   if (!VT.isVector())
21111     return std::make_pair(0, false);
21112
21113   bool NeedSplit = false;
21114   switch (VT.getSimpleVT().SimpleTy) {
21115   default: return std::make_pair(0, false);
21116   case MVT::v4i64:
21117   case MVT::v2i64:
21118     if (!Subtarget->hasVLX())
21119       return std::make_pair(0, false);
21120     break;
21121   case MVT::v64i8:
21122   case MVT::v32i16:
21123     if (!Subtarget->hasBWI())
21124       return std::make_pair(0, false);
21125     break;
21126   case MVT::v16i32:
21127   case MVT::v8i64:
21128     if (!Subtarget->hasAVX512())
21129       return std::make_pair(0, false);
21130     break;
21131   case MVT::v32i8:
21132   case MVT::v16i16:
21133   case MVT::v8i32:
21134     if (!Subtarget->hasAVX2())
21135       NeedSplit = true;
21136     if (!Subtarget->hasAVX())
21137       return std::make_pair(0, false);
21138     break;
21139   case MVT::v16i8:
21140   case MVT::v8i16:
21141   case MVT::v4i32:
21142     if (!Subtarget->hasSSE2())
21143       return std::make_pair(0, false);
21144   }
21145
21146   // SSE2 has only a small subset of the operations.
21147   bool hasUnsigned = Subtarget->hasSSE41() ||
21148                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21149   bool hasSigned = Subtarget->hasSSE41() ||
21150                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21151
21152   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21153
21154   unsigned Opc = 0;
21155   // Check for x CC y ? x : y.
21156   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21157       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21158     switch (CC) {
21159     default: break;
21160     case ISD::SETULT:
21161     case ISD::SETULE:
21162       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21163     case ISD::SETUGT:
21164     case ISD::SETUGE:
21165       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21166     case ISD::SETLT:
21167     case ISD::SETLE:
21168       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21169     case ISD::SETGT:
21170     case ISD::SETGE:
21171       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21172     }
21173   // Check for x CC y ? y : x -- a min/max with reversed arms.
21174   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21175              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21176     switch (CC) {
21177     default: break;
21178     case ISD::SETULT:
21179     case ISD::SETULE:
21180       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21181     case ISD::SETUGT:
21182     case ISD::SETUGE:
21183       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21184     case ISD::SETLT:
21185     case ISD::SETLE:
21186       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21187     case ISD::SETGT:
21188     case ISD::SETGE:
21189       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21190     }
21191   }
21192
21193   return std::make_pair(Opc, NeedSplit);
21194 }
21195
21196 static SDValue
21197 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21198                                       const X86Subtarget *Subtarget) {
21199   SDLoc dl(N);
21200   SDValue Cond = N->getOperand(0);
21201   SDValue LHS = N->getOperand(1);
21202   SDValue RHS = N->getOperand(2);
21203
21204   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21205     SDValue CondSrc = Cond->getOperand(0);
21206     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21207       Cond = CondSrc->getOperand(0);
21208   }
21209
21210   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21211     return SDValue();
21212
21213   // A vselect where all conditions and data are constants can be optimized into
21214   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21215   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21216       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21217     return SDValue();
21218
21219   unsigned MaskValue = 0;
21220   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21221     return SDValue();
21222
21223   MVT VT = N->getSimpleValueType(0);
21224   unsigned NumElems = VT.getVectorNumElements();
21225   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21226   for (unsigned i = 0; i < NumElems; ++i) {
21227     // Be sure we emit undef where we can.
21228     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21229       ShuffleMask[i] = -1;
21230     else
21231       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21232   }
21233
21234   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21235   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21236     return SDValue();
21237   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21238 }
21239
21240 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21241 /// nodes.
21242 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21243                                     TargetLowering::DAGCombinerInfo &DCI,
21244                                     const X86Subtarget *Subtarget) {
21245   SDLoc DL(N);
21246   SDValue Cond = N->getOperand(0);
21247   // Get the LHS/RHS of the select.
21248   SDValue LHS = N->getOperand(1);
21249   SDValue RHS = N->getOperand(2);
21250   EVT VT = LHS.getValueType();
21251   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21252
21253   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21254   // instructions match the semantics of the common C idiom x<y?x:y but not
21255   // x<=y?x:y, because of how they handle negative zero (which can be
21256   // ignored in unsafe-math mode).
21257   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21258   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21259       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21260       (Subtarget->hasSSE2() ||
21261        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21262     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21263
21264     unsigned Opcode = 0;
21265     // Check for x CC y ? x : y.
21266     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21267         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21268       switch (CC) {
21269       default: break;
21270       case ISD::SETULT:
21271         // Converting this to a min would handle NaNs incorrectly, and swapping
21272         // the operands would cause it to handle comparisons between positive
21273         // and negative zero incorrectly.
21274         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21275           if (!DAG.getTarget().Options.UnsafeFPMath &&
21276               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21277             break;
21278           std::swap(LHS, RHS);
21279         }
21280         Opcode = X86ISD::FMIN;
21281         break;
21282       case ISD::SETOLE:
21283         // Converting this to a min would handle comparisons between positive
21284         // and negative zero incorrectly.
21285         if (!DAG.getTarget().Options.UnsafeFPMath &&
21286             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21287           break;
21288         Opcode = X86ISD::FMIN;
21289         break;
21290       case ISD::SETULE:
21291         // Converting this to a min would handle both negative zeros and NaNs
21292         // incorrectly, but we can swap the operands to fix both.
21293         std::swap(LHS, RHS);
21294       case ISD::SETOLT:
21295       case ISD::SETLT:
21296       case ISD::SETLE:
21297         Opcode = X86ISD::FMIN;
21298         break;
21299
21300       case ISD::SETOGE:
21301         // Converting this to a max would handle comparisons between positive
21302         // and negative zero incorrectly.
21303         if (!DAG.getTarget().Options.UnsafeFPMath &&
21304             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21305           break;
21306         Opcode = X86ISD::FMAX;
21307         break;
21308       case ISD::SETUGT:
21309         // Converting this to a max would handle NaNs incorrectly, and swapping
21310         // the operands would cause it to handle comparisons between positive
21311         // and negative zero incorrectly.
21312         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21313           if (!DAG.getTarget().Options.UnsafeFPMath &&
21314               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21315             break;
21316           std::swap(LHS, RHS);
21317         }
21318         Opcode = X86ISD::FMAX;
21319         break;
21320       case ISD::SETUGE:
21321         // Converting this to a max would handle both negative zeros and NaNs
21322         // incorrectly, but we can swap the operands to fix both.
21323         std::swap(LHS, RHS);
21324       case ISD::SETOGT:
21325       case ISD::SETGT:
21326       case ISD::SETGE:
21327         Opcode = X86ISD::FMAX;
21328         break;
21329       }
21330     // Check for x CC y ? y : x -- a min/max with reversed arms.
21331     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21332                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21333       switch (CC) {
21334       default: break;
21335       case ISD::SETOGE:
21336         // Converting this to a min would handle comparisons between positive
21337         // and negative zero incorrectly, and swapping the operands would
21338         // cause it to handle NaNs incorrectly.
21339         if (!DAG.getTarget().Options.UnsafeFPMath &&
21340             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21341           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21342             break;
21343           std::swap(LHS, RHS);
21344         }
21345         Opcode = X86ISD::FMIN;
21346         break;
21347       case ISD::SETUGT:
21348         // Converting this to a min would handle NaNs incorrectly.
21349         if (!DAG.getTarget().Options.UnsafeFPMath &&
21350             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21351           break;
21352         Opcode = X86ISD::FMIN;
21353         break;
21354       case ISD::SETUGE:
21355         // Converting this to a min would handle both negative zeros and NaNs
21356         // incorrectly, but we can swap the operands to fix both.
21357         std::swap(LHS, RHS);
21358       case ISD::SETOGT:
21359       case ISD::SETGT:
21360       case ISD::SETGE:
21361         Opcode = X86ISD::FMIN;
21362         break;
21363
21364       case ISD::SETULT:
21365         // Converting this to a max would handle NaNs incorrectly.
21366         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21367           break;
21368         Opcode = X86ISD::FMAX;
21369         break;
21370       case ISD::SETOLE:
21371         // Converting this to a max would handle comparisons between positive
21372         // and negative zero incorrectly, and swapping the operands would
21373         // cause it to handle NaNs incorrectly.
21374         if (!DAG.getTarget().Options.UnsafeFPMath &&
21375             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21376           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21377             break;
21378           std::swap(LHS, RHS);
21379         }
21380         Opcode = X86ISD::FMAX;
21381         break;
21382       case ISD::SETULE:
21383         // Converting this to a max would handle both negative zeros and NaNs
21384         // incorrectly, but we can swap the operands to fix both.
21385         std::swap(LHS, RHS);
21386       case ISD::SETOLT:
21387       case ISD::SETLT:
21388       case ISD::SETLE:
21389         Opcode = X86ISD::FMAX;
21390         break;
21391       }
21392     }
21393
21394     if (Opcode)
21395       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21396   }
21397
21398   EVT CondVT = Cond.getValueType();
21399   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21400       CondVT.getVectorElementType() == MVT::i1) {
21401     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21402     // lowering on KNL. In this case we convert it to
21403     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21404     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21405     // Since SKX these selects have a proper lowering.
21406     EVT OpVT = LHS.getValueType();
21407     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21408         (OpVT.getVectorElementType() == MVT::i8 ||
21409          OpVT.getVectorElementType() == MVT::i16) &&
21410         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21411       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21412       DCI.AddToWorklist(Cond.getNode());
21413       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21414     }
21415   }
21416   // If this is a select between two integer constants, try to do some
21417   // optimizations.
21418   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21419     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21420       // Don't do this for crazy integer types.
21421       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21422         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21423         // so that TrueC (the true value) is larger than FalseC.
21424         bool NeedsCondInvert = false;
21425
21426         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21427             // Efficiently invertible.
21428             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21429              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21430               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21431           NeedsCondInvert = true;
21432           std::swap(TrueC, FalseC);
21433         }
21434
21435         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21436         if (FalseC->getAPIntValue() == 0 &&
21437             TrueC->getAPIntValue().isPowerOf2()) {
21438           if (NeedsCondInvert) // Invert the condition if needed.
21439             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21440                                DAG.getConstant(1, DL, Cond.getValueType()));
21441
21442           // Zero extend the condition if needed.
21443           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21444
21445           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21446           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21447                              DAG.getConstant(ShAmt, DL, MVT::i8));
21448         }
21449
21450         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21451         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21452           if (NeedsCondInvert) // Invert the condition if needed.
21453             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21454                                DAG.getConstant(1, DL, Cond.getValueType()));
21455
21456           // Zero extend the condition if needed.
21457           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21458                              FalseC->getValueType(0), Cond);
21459           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21460                              SDValue(FalseC, 0));
21461         }
21462
21463         // Optimize cases that will turn into an LEA instruction.  This requires
21464         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21465         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21466           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21467           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21468
21469           bool isFastMultiplier = false;
21470           if (Diff < 10) {
21471             switch ((unsigned char)Diff) {
21472               default: break;
21473               case 1:  // result = add base, cond
21474               case 2:  // result = lea base(    , cond*2)
21475               case 3:  // result = lea base(cond, cond*2)
21476               case 4:  // result = lea base(    , cond*4)
21477               case 5:  // result = lea base(cond, cond*4)
21478               case 8:  // result = lea base(    , cond*8)
21479               case 9:  // result = lea base(cond, cond*8)
21480                 isFastMultiplier = true;
21481                 break;
21482             }
21483           }
21484
21485           if (isFastMultiplier) {
21486             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21487             if (NeedsCondInvert) // Invert the condition if needed.
21488               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21489                                  DAG.getConstant(1, DL, Cond.getValueType()));
21490
21491             // Zero extend the condition if needed.
21492             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21493                                Cond);
21494             // Scale the condition by the difference.
21495             if (Diff != 1)
21496               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21497                                  DAG.getConstant(Diff, DL,
21498                                                  Cond.getValueType()));
21499
21500             // Add the base if non-zero.
21501             if (FalseC->getAPIntValue() != 0)
21502               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21503                                  SDValue(FalseC, 0));
21504             return Cond;
21505           }
21506         }
21507       }
21508   }
21509
21510   // Canonicalize max and min:
21511   // (x > y) ? x : y -> (x >= y) ? x : y
21512   // (x < y) ? x : y -> (x <= y) ? x : y
21513   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21514   // the need for an extra compare
21515   // against zero. e.g.
21516   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21517   // subl   %esi, %edi
21518   // testl  %edi, %edi
21519   // movl   $0, %eax
21520   // cmovgl %edi, %eax
21521   // =>
21522   // xorl   %eax, %eax
21523   // subl   %esi, $edi
21524   // cmovsl %eax, %edi
21525   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21526       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21527       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21528     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21529     switch (CC) {
21530     default: break;
21531     case ISD::SETLT:
21532     case ISD::SETGT: {
21533       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21534       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21535                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21536       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21537     }
21538     }
21539   }
21540
21541   // Early exit check
21542   if (!TLI.isTypeLegal(VT))
21543     return SDValue();
21544
21545   // Match VSELECTs into subs with unsigned saturation.
21546   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21547       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21548       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21549        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21550     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21551
21552     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21553     // left side invert the predicate to simplify logic below.
21554     SDValue Other;
21555     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21556       Other = RHS;
21557       CC = ISD::getSetCCInverse(CC, true);
21558     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21559       Other = LHS;
21560     }
21561
21562     if (Other.getNode() && Other->getNumOperands() == 2 &&
21563         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21564       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21565       SDValue CondRHS = Cond->getOperand(1);
21566
21567       // Look for a general sub with unsigned saturation first.
21568       // x >= y ? x-y : 0 --> subus x, y
21569       // x >  y ? x-y : 0 --> subus x, y
21570       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21571           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21572         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21573
21574       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21575         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21576           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21577             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21578               // If the RHS is a constant we have to reverse the const
21579               // canonicalization.
21580               // x > C-1 ? x+-C : 0 --> subus x, C
21581               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21582                   CondRHSConst->getAPIntValue() ==
21583                       (-OpRHSConst->getAPIntValue() - 1))
21584                 return DAG.getNode(
21585                     X86ISD::SUBUS, DL, VT, OpLHS,
21586                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21587
21588           // Another special case: If C was a sign bit, the sub has been
21589           // canonicalized into a xor.
21590           // FIXME: Would it be better to use computeKnownBits to determine
21591           //        whether it's safe to decanonicalize the xor?
21592           // x s< 0 ? x^C : 0 --> subus x, C
21593           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21594               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21595               OpRHSConst->getAPIntValue().isSignBit())
21596             // Note that we have to rebuild the RHS constant here to ensure we
21597             // don't rely on particular values of undef lanes.
21598             return DAG.getNode(
21599                 X86ISD::SUBUS, DL, VT, OpLHS,
21600                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21601         }
21602     }
21603   }
21604
21605   // Try to match a min/max vector operation.
21606   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21607     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21608     unsigned Opc = ret.first;
21609     bool NeedSplit = ret.second;
21610
21611     if (Opc && NeedSplit) {
21612       unsigned NumElems = VT.getVectorNumElements();
21613       // Extract the LHS vectors
21614       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21615       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21616
21617       // Extract the RHS vectors
21618       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21619       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21620
21621       // Create min/max for each subvector
21622       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21623       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21624
21625       // Merge the result
21626       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21627     } else if (Opc)
21628       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21629   }
21630
21631   // Simplify vector selection if condition value type matches vselect
21632   // operand type
21633   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21634     assert(Cond.getValueType().isVector() &&
21635            "vector select expects a vector selector!");
21636
21637     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21638     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21639
21640     // Try invert the condition if true value is not all 1s and false value
21641     // is not all 0s.
21642     if (!TValIsAllOnes && !FValIsAllZeros &&
21643         // Check if the selector will be produced by CMPP*/PCMP*
21644         Cond.getOpcode() == ISD::SETCC &&
21645         // Check if SETCC has already been promoted
21646         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21647       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21648       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21649
21650       if (TValIsAllZeros || FValIsAllOnes) {
21651         SDValue CC = Cond.getOperand(2);
21652         ISD::CondCode NewCC =
21653           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21654                                Cond.getOperand(0).getValueType().isInteger());
21655         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21656         std::swap(LHS, RHS);
21657         TValIsAllOnes = FValIsAllOnes;
21658         FValIsAllZeros = TValIsAllZeros;
21659       }
21660     }
21661
21662     if (TValIsAllOnes || FValIsAllZeros) {
21663       SDValue Ret;
21664
21665       if (TValIsAllOnes && FValIsAllZeros)
21666         Ret = Cond;
21667       else if (TValIsAllOnes)
21668         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21669                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21670       else if (FValIsAllZeros)
21671         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21672                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21673
21674       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21675     }
21676   }
21677
21678   // We should generate an X86ISD::BLENDI from a vselect if its argument
21679   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21680   // constants. This specific pattern gets generated when we split a
21681   // selector for a 512 bit vector in a machine without AVX512 (but with
21682   // 256-bit vectors), during legalization:
21683   //
21684   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21685   //
21686   // Iff we find this pattern and the build_vectors are built from
21687   // constants, we translate the vselect into a shuffle_vector that we
21688   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21689   if ((N->getOpcode() == ISD::VSELECT ||
21690        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21691       !DCI.isBeforeLegalize()) {
21692     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21693     if (Shuffle.getNode())
21694       return Shuffle;
21695   }
21696
21697   // If this is a *dynamic* select (non-constant condition) and we can match
21698   // this node with one of the variable blend instructions, restructure the
21699   // condition so that the blends can use the high bit of each element and use
21700   // SimplifyDemandedBits to simplify the condition operand.
21701   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21702       !DCI.isBeforeLegalize() &&
21703       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21704     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21705
21706     // Don't optimize vector selects that map to mask-registers.
21707     if (BitWidth == 1)
21708       return SDValue();
21709
21710     // We can only handle the cases where VSELECT is directly legal on the
21711     // subtarget. We custom lower VSELECT nodes with constant conditions and
21712     // this makes it hard to see whether a dynamic VSELECT will correctly
21713     // lower, so we both check the operation's status and explicitly handle the
21714     // cases where a *dynamic* blend will fail even though a constant-condition
21715     // blend could be custom lowered.
21716     // FIXME: We should find a better way to handle this class of problems.
21717     // Potentially, we should combine constant-condition vselect nodes
21718     // pre-legalization into shuffles and not mark as many types as custom
21719     // lowered.
21720     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21721       return SDValue();
21722     // FIXME: We don't support i16-element blends currently. We could and
21723     // should support them by making *all* the bits in the condition be set
21724     // rather than just the high bit and using an i8-element blend.
21725     if (VT.getScalarType() == MVT::i16)
21726       return SDValue();
21727     // Dynamic blending was only available from SSE4.1 onward.
21728     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21729       return SDValue();
21730     // Byte blends are only available in AVX2
21731     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21732         !Subtarget->hasAVX2())
21733       return SDValue();
21734
21735     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21736     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21737
21738     APInt KnownZero, KnownOne;
21739     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21740                                           DCI.isBeforeLegalizeOps());
21741     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21742         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21743                                  TLO)) {
21744       // If we changed the computation somewhere in the DAG, this change
21745       // will affect all users of Cond.
21746       // Make sure it is fine and update all the nodes so that we do not
21747       // use the generic VSELECT anymore. Otherwise, we may perform
21748       // wrong optimizations as we messed up with the actual expectation
21749       // for the vector boolean values.
21750       if (Cond != TLO.Old) {
21751         // Check all uses of that condition operand to check whether it will be
21752         // consumed by non-BLEND instructions, which may depend on all bits are
21753         // set properly.
21754         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21755              I != E; ++I)
21756           if (I->getOpcode() != ISD::VSELECT)
21757             // TODO: Add other opcodes eventually lowered into BLEND.
21758             return SDValue();
21759
21760         // Update all the users of the condition, before committing the change,
21761         // so that the VSELECT optimizations that expect the correct vector
21762         // boolean value will not be triggered.
21763         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21764              I != E; ++I)
21765           DAG.ReplaceAllUsesOfValueWith(
21766               SDValue(*I, 0),
21767               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21768                           Cond, I->getOperand(1), I->getOperand(2)));
21769         DCI.CommitTargetLoweringOpt(TLO);
21770         return SDValue();
21771       }
21772       // At this point, only Cond is changed. Change the condition
21773       // just for N to keep the opportunity to optimize all other
21774       // users their own way.
21775       DAG.ReplaceAllUsesOfValueWith(
21776           SDValue(N, 0),
21777           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21778                       TLO.New, N->getOperand(1), N->getOperand(2)));
21779       return SDValue();
21780     }
21781   }
21782
21783   return SDValue();
21784 }
21785
21786 // Check whether a boolean test is testing a boolean value generated by
21787 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21788 // code.
21789 //
21790 // Simplify the following patterns:
21791 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21792 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21793 // to (Op EFLAGS Cond)
21794 //
21795 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21796 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21797 // to (Op EFLAGS !Cond)
21798 //
21799 // where Op could be BRCOND or CMOV.
21800 //
21801 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21802   // Quit if not CMP and SUB with its value result used.
21803   if (Cmp.getOpcode() != X86ISD::CMP &&
21804       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21805       return SDValue();
21806
21807   // Quit if not used as a boolean value.
21808   if (CC != X86::COND_E && CC != X86::COND_NE)
21809     return SDValue();
21810
21811   // Check CMP operands. One of them should be 0 or 1 and the other should be
21812   // an SetCC or extended from it.
21813   SDValue Op1 = Cmp.getOperand(0);
21814   SDValue Op2 = Cmp.getOperand(1);
21815
21816   SDValue SetCC;
21817   const ConstantSDNode* C = nullptr;
21818   bool needOppositeCond = (CC == X86::COND_E);
21819   bool checkAgainstTrue = false; // Is it a comparison against 1?
21820
21821   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21822     SetCC = Op2;
21823   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21824     SetCC = Op1;
21825   else // Quit if all operands are not constants.
21826     return SDValue();
21827
21828   if (C->getZExtValue() == 1) {
21829     needOppositeCond = !needOppositeCond;
21830     checkAgainstTrue = true;
21831   } else if (C->getZExtValue() != 0)
21832     // Quit if the constant is neither 0 or 1.
21833     return SDValue();
21834
21835   bool truncatedToBoolWithAnd = false;
21836   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21837   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21838          SetCC.getOpcode() == ISD::TRUNCATE ||
21839          SetCC.getOpcode() == ISD::AND) {
21840     if (SetCC.getOpcode() == ISD::AND) {
21841       int OpIdx = -1;
21842       ConstantSDNode *CS;
21843       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21844           CS->getZExtValue() == 1)
21845         OpIdx = 1;
21846       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21847           CS->getZExtValue() == 1)
21848         OpIdx = 0;
21849       if (OpIdx == -1)
21850         break;
21851       SetCC = SetCC.getOperand(OpIdx);
21852       truncatedToBoolWithAnd = true;
21853     } else
21854       SetCC = SetCC.getOperand(0);
21855   }
21856
21857   switch (SetCC.getOpcode()) {
21858   case X86ISD::SETCC_CARRY:
21859     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21860     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21861     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21862     // truncated to i1 using 'and'.
21863     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21864       break;
21865     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21866            "Invalid use of SETCC_CARRY!");
21867     // FALL THROUGH
21868   case X86ISD::SETCC:
21869     // Set the condition code or opposite one if necessary.
21870     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21871     if (needOppositeCond)
21872       CC = X86::GetOppositeBranchCondition(CC);
21873     return SetCC.getOperand(1);
21874   case X86ISD::CMOV: {
21875     // Check whether false/true value has canonical one, i.e. 0 or 1.
21876     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21877     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21878     // Quit if true value is not a constant.
21879     if (!TVal)
21880       return SDValue();
21881     // Quit if false value is not a constant.
21882     if (!FVal) {
21883       SDValue Op = SetCC.getOperand(0);
21884       // Skip 'zext' or 'trunc' node.
21885       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21886           Op.getOpcode() == ISD::TRUNCATE)
21887         Op = Op.getOperand(0);
21888       // A special case for rdrand/rdseed, where 0 is set if false cond is
21889       // found.
21890       if ((Op.getOpcode() != X86ISD::RDRAND &&
21891            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21892         return SDValue();
21893     }
21894     // Quit if false value is not the constant 0 or 1.
21895     bool FValIsFalse = true;
21896     if (FVal && FVal->getZExtValue() != 0) {
21897       if (FVal->getZExtValue() != 1)
21898         return SDValue();
21899       // If FVal is 1, opposite cond is needed.
21900       needOppositeCond = !needOppositeCond;
21901       FValIsFalse = false;
21902     }
21903     // Quit if TVal is not the constant opposite of FVal.
21904     if (FValIsFalse && TVal->getZExtValue() != 1)
21905       return SDValue();
21906     if (!FValIsFalse && TVal->getZExtValue() != 0)
21907       return SDValue();
21908     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21909     if (needOppositeCond)
21910       CC = X86::GetOppositeBranchCondition(CC);
21911     return SetCC.getOperand(3);
21912   }
21913   }
21914
21915   return SDValue();
21916 }
21917
21918 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21919 /// Match:
21920 ///   (X86or (X86setcc) (X86setcc))
21921 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21922 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21923                                            X86::CondCode &CC1, SDValue &Flags,
21924                                            bool &isAnd) {
21925   if (Cond->getOpcode() == X86ISD::CMP) {
21926     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21927     if (!CondOp1C || !CondOp1C->isNullValue())
21928       return false;
21929
21930     Cond = Cond->getOperand(0);
21931   }
21932
21933   isAnd = false;
21934
21935   SDValue SetCC0, SetCC1;
21936   switch (Cond->getOpcode()) {
21937   default: return false;
21938   case ISD::AND:
21939   case X86ISD::AND:
21940     isAnd = true;
21941     // fallthru
21942   case ISD::OR:
21943   case X86ISD::OR:
21944     SetCC0 = Cond->getOperand(0);
21945     SetCC1 = Cond->getOperand(1);
21946     break;
21947   };
21948
21949   // Make sure we have SETCC nodes, using the same flags value.
21950   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21951       SetCC1.getOpcode() != X86ISD::SETCC ||
21952       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21953     return false;
21954
21955   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21956   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21957   Flags = SetCC0->getOperand(1);
21958   return true;
21959 }
21960
21961 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21962 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21963                                   TargetLowering::DAGCombinerInfo &DCI,
21964                                   const X86Subtarget *Subtarget) {
21965   SDLoc DL(N);
21966
21967   // If the flag operand isn't dead, don't touch this CMOV.
21968   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21969     return SDValue();
21970
21971   SDValue FalseOp = N->getOperand(0);
21972   SDValue TrueOp = N->getOperand(1);
21973   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21974   SDValue Cond = N->getOperand(3);
21975
21976   if (CC == X86::COND_E || CC == X86::COND_NE) {
21977     switch (Cond.getOpcode()) {
21978     default: break;
21979     case X86ISD::BSR:
21980     case X86ISD::BSF:
21981       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21982       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21983         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21984     }
21985   }
21986
21987   SDValue Flags;
21988
21989   Flags = checkBoolTestSetCCCombine(Cond, CC);
21990   if (Flags.getNode() &&
21991       // Extra check as FCMOV only supports a subset of X86 cond.
21992       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21993     SDValue Ops[] = { FalseOp, TrueOp,
21994                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21995     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21996   }
21997
21998   // If this is a select between two integer constants, try to do some
21999   // optimizations.  Note that the operands are ordered the opposite of SELECT
22000   // operands.
22001   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22002     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22003       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22004       // larger than FalseC (the false value).
22005       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22006         CC = X86::GetOppositeBranchCondition(CC);
22007         std::swap(TrueC, FalseC);
22008         std::swap(TrueOp, FalseOp);
22009       }
22010
22011       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22012       // This is efficient for any integer data type (including i8/i16) and
22013       // shift amount.
22014       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22015         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22016                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22017
22018         // Zero extend the condition if needed.
22019         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22020
22021         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22022         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22023                            DAG.getConstant(ShAmt, DL, MVT::i8));
22024         if (N->getNumValues() == 2)  // Dead flag value?
22025           return DCI.CombineTo(N, Cond, SDValue());
22026         return Cond;
22027       }
22028
22029       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22030       // for any integer data type, including i8/i16.
22031       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22032         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22033                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22034
22035         // Zero extend the condition if needed.
22036         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22037                            FalseC->getValueType(0), Cond);
22038         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22039                            SDValue(FalseC, 0));
22040
22041         if (N->getNumValues() == 2)  // Dead flag value?
22042           return DCI.CombineTo(N, Cond, SDValue());
22043         return Cond;
22044       }
22045
22046       // Optimize cases that will turn into an LEA instruction.  This requires
22047       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22048       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22049         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22050         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22051
22052         bool isFastMultiplier = false;
22053         if (Diff < 10) {
22054           switch ((unsigned char)Diff) {
22055           default: break;
22056           case 1:  // result = add base, cond
22057           case 2:  // result = lea base(    , cond*2)
22058           case 3:  // result = lea base(cond, cond*2)
22059           case 4:  // result = lea base(    , cond*4)
22060           case 5:  // result = lea base(cond, cond*4)
22061           case 8:  // result = lea base(    , cond*8)
22062           case 9:  // result = lea base(cond, cond*8)
22063             isFastMultiplier = true;
22064             break;
22065           }
22066         }
22067
22068         if (isFastMultiplier) {
22069           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22070           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22071                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22072           // Zero extend the condition if needed.
22073           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22074                              Cond);
22075           // Scale the condition by the difference.
22076           if (Diff != 1)
22077             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22078                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22079
22080           // Add the base if non-zero.
22081           if (FalseC->getAPIntValue() != 0)
22082             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22083                                SDValue(FalseC, 0));
22084           if (N->getNumValues() == 2)  // Dead flag value?
22085             return DCI.CombineTo(N, Cond, SDValue());
22086           return Cond;
22087         }
22088       }
22089     }
22090   }
22091
22092   // Handle these cases:
22093   //   (select (x != c), e, c) -> select (x != c), e, x),
22094   //   (select (x == c), c, e) -> select (x == c), x, e)
22095   // where the c is an integer constant, and the "select" is the combination
22096   // of CMOV and CMP.
22097   //
22098   // The rationale for this change is that the conditional-move from a constant
22099   // needs two instructions, however, conditional-move from a register needs
22100   // only one instruction.
22101   //
22102   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22103   //  some instruction-combining opportunities. This opt needs to be
22104   //  postponed as late as possible.
22105   //
22106   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22107     // the DCI.xxxx conditions are provided to postpone the optimization as
22108     // late as possible.
22109
22110     ConstantSDNode *CmpAgainst = nullptr;
22111     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22112         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22113         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22114
22115       if (CC == X86::COND_NE &&
22116           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22117         CC = X86::GetOppositeBranchCondition(CC);
22118         std::swap(TrueOp, FalseOp);
22119       }
22120
22121       if (CC == X86::COND_E &&
22122           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22123         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22124                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22125         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22126       }
22127     }
22128   }
22129
22130   // Fold and/or of setcc's to double CMOV:
22131   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22132   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22133   //
22134   // This combine lets us generate:
22135   //   cmovcc1 (jcc1 if we don't have CMOV)
22136   //   cmovcc2 (same)
22137   // instead of:
22138   //   setcc1
22139   //   setcc2
22140   //   and/or
22141   //   cmovne (jne if we don't have CMOV)
22142   // When we can't use the CMOV instruction, it might increase branch
22143   // mispredicts.
22144   // When we can use CMOV, or when there is no mispredict, this improves
22145   // throughput and reduces register pressure.
22146   //
22147   if (CC == X86::COND_NE) {
22148     SDValue Flags;
22149     X86::CondCode CC0, CC1;
22150     bool isAndSetCC;
22151     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22152       if (isAndSetCC) {
22153         std::swap(FalseOp, TrueOp);
22154         CC0 = X86::GetOppositeBranchCondition(CC0);
22155         CC1 = X86::GetOppositeBranchCondition(CC1);
22156       }
22157
22158       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22159         Flags};
22160       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22161       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22162       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22163       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22164       return CMOV;
22165     }
22166   }
22167
22168   return SDValue();
22169 }
22170
22171 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22172                                                 const X86Subtarget *Subtarget) {
22173   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22174   switch (IntNo) {
22175   default: return SDValue();
22176   // SSE/AVX/AVX2 blend intrinsics.
22177   case Intrinsic::x86_avx2_pblendvb:
22178     // Don't try to simplify this intrinsic if we don't have AVX2.
22179     if (!Subtarget->hasAVX2())
22180       return SDValue();
22181     // FALL-THROUGH
22182   case Intrinsic::x86_avx_blendv_pd_256:
22183   case Intrinsic::x86_avx_blendv_ps_256:
22184     // Don't try to simplify this intrinsic if we don't have AVX.
22185     if (!Subtarget->hasAVX())
22186       return SDValue();
22187     // FALL-THROUGH
22188   case Intrinsic::x86_sse41_blendvps:
22189   case Intrinsic::x86_sse41_blendvpd:
22190   case Intrinsic::x86_sse41_pblendvb: {
22191     SDValue Op0 = N->getOperand(1);
22192     SDValue Op1 = N->getOperand(2);
22193     SDValue Mask = N->getOperand(3);
22194
22195     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22196     if (!Subtarget->hasSSE41())
22197       return SDValue();
22198
22199     // fold (blend A, A, Mask) -> A
22200     if (Op0 == Op1)
22201       return Op0;
22202     // fold (blend A, B, allZeros) -> A
22203     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22204       return Op0;
22205     // fold (blend A, B, allOnes) -> B
22206     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22207       return Op1;
22208
22209     // Simplify the case where the mask is a constant i32 value.
22210     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22211       if (C->isNullValue())
22212         return Op0;
22213       if (C->isAllOnesValue())
22214         return Op1;
22215     }
22216
22217     return SDValue();
22218   }
22219
22220   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22221   case Intrinsic::x86_sse2_psrai_w:
22222   case Intrinsic::x86_sse2_psrai_d:
22223   case Intrinsic::x86_avx2_psrai_w:
22224   case Intrinsic::x86_avx2_psrai_d:
22225   case Intrinsic::x86_sse2_psra_w:
22226   case Intrinsic::x86_sse2_psra_d:
22227   case Intrinsic::x86_avx2_psra_w:
22228   case Intrinsic::x86_avx2_psra_d: {
22229     SDValue Op0 = N->getOperand(1);
22230     SDValue Op1 = N->getOperand(2);
22231     EVT VT = Op0.getValueType();
22232     assert(VT.isVector() && "Expected a vector type!");
22233
22234     if (isa<BuildVectorSDNode>(Op1))
22235       Op1 = Op1.getOperand(0);
22236
22237     if (!isa<ConstantSDNode>(Op1))
22238       return SDValue();
22239
22240     EVT SVT = VT.getVectorElementType();
22241     unsigned SVTBits = SVT.getSizeInBits();
22242
22243     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22244     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22245     uint64_t ShAmt = C.getZExtValue();
22246
22247     // Don't try to convert this shift into a ISD::SRA if the shift
22248     // count is bigger than or equal to the element size.
22249     if (ShAmt >= SVTBits)
22250       return SDValue();
22251
22252     // Trivial case: if the shift count is zero, then fold this
22253     // into the first operand.
22254     if (ShAmt == 0)
22255       return Op0;
22256
22257     // Replace this packed shift intrinsic with a target independent
22258     // shift dag node.
22259     SDLoc DL(N);
22260     SDValue Splat = DAG.getConstant(C, DL, VT);
22261     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22262   }
22263   }
22264 }
22265
22266 /// PerformMulCombine - Optimize a single multiply with constant into two
22267 /// in order to implement it with two cheaper instructions, e.g.
22268 /// LEA + SHL, LEA + LEA.
22269 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22270                                  TargetLowering::DAGCombinerInfo &DCI) {
22271   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22272     return SDValue();
22273
22274   EVT VT = N->getValueType(0);
22275   if (VT != MVT::i64 && VT != MVT::i32)
22276     return SDValue();
22277
22278   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22279   if (!C)
22280     return SDValue();
22281   uint64_t MulAmt = C->getZExtValue();
22282   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22283     return SDValue();
22284
22285   uint64_t MulAmt1 = 0;
22286   uint64_t MulAmt2 = 0;
22287   if ((MulAmt % 9) == 0) {
22288     MulAmt1 = 9;
22289     MulAmt2 = MulAmt / 9;
22290   } else if ((MulAmt % 5) == 0) {
22291     MulAmt1 = 5;
22292     MulAmt2 = MulAmt / 5;
22293   } else if ((MulAmt % 3) == 0) {
22294     MulAmt1 = 3;
22295     MulAmt2 = MulAmt / 3;
22296   }
22297   if (MulAmt2 &&
22298       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22299     SDLoc DL(N);
22300
22301     if (isPowerOf2_64(MulAmt2) &&
22302         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22303       // If second multiplifer is pow2, issue it first. We want the multiply by
22304       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22305       // is an add.
22306       std::swap(MulAmt1, MulAmt2);
22307
22308     SDValue NewMul;
22309     if (isPowerOf2_64(MulAmt1))
22310       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22311                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22312     else
22313       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22314                            DAG.getConstant(MulAmt1, DL, VT));
22315
22316     if (isPowerOf2_64(MulAmt2))
22317       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22318                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22319     else
22320       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22321                            DAG.getConstant(MulAmt2, DL, VT));
22322
22323     // Do not add new nodes to DAG combiner worklist.
22324     DCI.CombineTo(N, NewMul, false);
22325   }
22326   return SDValue();
22327 }
22328
22329 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22330   SDValue N0 = N->getOperand(0);
22331   SDValue N1 = N->getOperand(1);
22332   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22333   EVT VT = N0.getValueType();
22334
22335   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22336   // since the result of setcc_c is all zero's or all ones.
22337   if (VT.isInteger() && !VT.isVector() &&
22338       N1C && N0.getOpcode() == ISD::AND &&
22339       N0.getOperand(1).getOpcode() == ISD::Constant) {
22340     SDValue N00 = N0.getOperand(0);
22341     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22342         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22343           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22344          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22345       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22346       APInt ShAmt = N1C->getAPIntValue();
22347       Mask = Mask.shl(ShAmt);
22348       if (Mask != 0) {
22349         SDLoc DL(N);
22350         return DAG.getNode(ISD::AND, DL, VT,
22351                            N00, DAG.getConstant(Mask, DL, VT));
22352       }
22353     }
22354   }
22355
22356   // Hardware support for vector shifts is sparse which makes us scalarize the
22357   // vector operations in many cases. Also, on sandybridge ADD is faster than
22358   // shl.
22359   // (shl V, 1) -> add V,V
22360   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22361     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22362       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22363       // We shift all of the values by one. In many cases we do not have
22364       // hardware support for this operation. This is better expressed as an ADD
22365       // of two values.
22366       if (N1SplatC->getZExtValue() == 1)
22367         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22368     }
22369
22370   return SDValue();
22371 }
22372
22373 /// \brief Returns a vector of 0s if the node in input is a vector logical
22374 /// shift by a constant amount which is known to be bigger than or equal
22375 /// to the vector element size in bits.
22376 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22377                                       const X86Subtarget *Subtarget) {
22378   EVT VT = N->getValueType(0);
22379
22380   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22381       (!Subtarget->hasInt256() ||
22382        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22383     return SDValue();
22384
22385   SDValue Amt = N->getOperand(1);
22386   SDLoc DL(N);
22387   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22388     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22389       APInt ShiftAmt = AmtSplat->getAPIntValue();
22390       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22391
22392       // SSE2/AVX2 logical shifts always return a vector of 0s
22393       // if the shift amount is bigger than or equal to
22394       // the element size. The constant shift amount will be
22395       // encoded as a 8-bit immediate.
22396       if (ShiftAmt.trunc(8).uge(MaxAmount))
22397         return getZeroVector(VT, Subtarget, DAG, DL);
22398     }
22399
22400   return SDValue();
22401 }
22402
22403 /// PerformShiftCombine - Combine shifts.
22404 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22405                                    TargetLowering::DAGCombinerInfo &DCI,
22406                                    const X86Subtarget *Subtarget) {
22407   if (N->getOpcode() == ISD::SHL) {
22408     SDValue V = PerformSHLCombine(N, DAG);
22409     if (V.getNode()) return V;
22410   }
22411
22412   if (N->getOpcode() != ISD::SRA) {
22413     // Try to fold this logical shift into a zero vector.
22414     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22415     if (V.getNode()) return V;
22416   }
22417
22418   return SDValue();
22419 }
22420
22421 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22422 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22423 // and friends.  Likewise for OR -> CMPNEQSS.
22424 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22425                             TargetLowering::DAGCombinerInfo &DCI,
22426                             const X86Subtarget *Subtarget) {
22427   unsigned opcode;
22428
22429   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22430   // we're requiring SSE2 for both.
22431   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22432     SDValue N0 = N->getOperand(0);
22433     SDValue N1 = N->getOperand(1);
22434     SDValue CMP0 = N0->getOperand(1);
22435     SDValue CMP1 = N1->getOperand(1);
22436     SDLoc DL(N);
22437
22438     // The SETCCs should both refer to the same CMP.
22439     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22440       return SDValue();
22441
22442     SDValue CMP00 = CMP0->getOperand(0);
22443     SDValue CMP01 = CMP0->getOperand(1);
22444     EVT     VT    = CMP00.getValueType();
22445
22446     if (VT == MVT::f32 || VT == MVT::f64) {
22447       bool ExpectingFlags = false;
22448       // Check for any users that want flags:
22449       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22450            !ExpectingFlags && UI != UE; ++UI)
22451         switch (UI->getOpcode()) {
22452         default:
22453         case ISD::BR_CC:
22454         case ISD::BRCOND:
22455         case ISD::SELECT:
22456           ExpectingFlags = true;
22457           break;
22458         case ISD::CopyToReg:
22459         case ISD::SIGN_EXTEND:
22460         case ISD::ZERO_EXTEND:
22461         case ISD::ANY_EXTEND:
22462           break;
22463         }
22464
22465       if (!ExpectingFlags) {
22466         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22467         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22468
22469         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22470           X86::CondCode tmp = cc0;
22471           cc0 = cc1;
22472           cc1 = tmp;
22473         }
22474
22475         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22476             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22477           // FIXME: need symbolic constants for these magic numbers.
22478           // See X86ATTInstPrinter.cpp:printSSECC().
22479           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22480           if (Subtarget->hasAVX512()) {
22481             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22482                                          CMP01,
22483                                          DAG.getConstant(x86cc, DL, MVT::i8));
22484             if (N->getValueType(0) != MVT::i1)
22485               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22486                                  FSetCC);
22487             return FSetCC;
22488           }
22489           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22490                                               CMP00.getValueType(), CMP00, CMP01,
22491                                               DAG.getConstant(x86cc, DL,
22492                                                               MVT::i8));
22493
22494           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22495           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22496
22497           if (is64BitFP && !Subtarget->is64Bit()) {
22498             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22499             // 64-bit integer, since that's not a legal type. Since
22500             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22501             // bits, but can do this little dance to extract the lowest 32 bits
22502             // and work with those going forward.
22503             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22504                                            OnesOrZeroesF);
22505             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22506                                            Vector64);
22507             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22508                                         Vector32, DAG.getIntPtrConstant(0, DL));
22509             IntVT = MVT::i32;
22510           }
22511
22512           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22513                                               OnesOrZeroesF);
22514           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22515                                       DAG.getConstant(1, DL, IntVT));
22516           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22517                                               ANDed);
22518           return OneBitOfTruth;
22519         }
22520       }
22521     }
22522   }
22523   return SDValue();
22524 }
22525
22526 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22527 /// so it can be folded inside ANDNP.
22528 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22529   EVT VT = N->getValueType(0);
22530
22531   // Match direct AllOnes for 128 and 256-bit vectors
22532   if (ISD::isBuildVectorAllOnes(N))
22533     return true;
22534
22535   // Look through a bit convert.
22536   if (N->getOpcode() == ISD::BITCAST)
22537     N = N->getOperand(0).getNode();
22538
22539   // Sometimes the operand may come from a insert_subvector building a 256-bit
22540   // allones vector
22541   if (VT.is256BitVector() &&
22542       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22543     SDValue V1 = N->getOperand(0);
22544     SDValue V2 = N->getOperand(1);
22545
22546     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22547         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22548         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22549         ISD::isBuildVectorAllOnes(V2.getNode()))
22550       return true;
22551   }
22552
22553   return false;
22554 }
22555
22556 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22557 // register. In most cases we actually compare or select YMM-sized registers
22558 // and mixing the two types creates horrible code. This method optimizes
22559 // some of the transition sequences.
22560 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22561                                  TargetLowering::DAGCombinerInfo &DCI,
22562                                  const X86Subtarget *Subtarget) {
22563   EVT VT = N->getValueType(0);
22564   if (!VT.is256BitVector())
22565     return SDValue();
22566
22567   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22568           N->getOpcode() == ISD::ZERO_EXTEND ||
22569           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22570
22571   SDValue Narrow = N->getOperand(0);
22572   EVT NarrowVT = Narrow->getValueType(0);
22573   if (!NarrowVT.is128BitVector())
22574     return SDValue();
22575
22576   if (Narrow->getOpcode() != ISD::XOR &&
22577       Narrow->getOpcode() != ISD::AND &&
22578       Narrow->getOpcode() != ISD::OR)
22579     return SDValue();
22580
22581   SDValue N0  = Narrow->getOperand(0);
22582   SDValue N1  = Narrow->getOperand(1);
22583   SDLoc DL(Narrow);
22584
22585   // The Left side has to be a trunc.
22586   if (N0.getOpcode() != ISD::TRUNCATE)
22587     return SDValue();
22588
22589   // The type of the truncated inputs.
22590   EVT WideVT = N0->getOperand(0)->getValueType(0);
22591   if (WideVT != VT)
22592     return SDValue();
22593
22594   // The right side has to be a 'trunc' or a constant vector.
22595   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22596   ConstantSDNode *RHSConstSplat = nullptr;
22597   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22598     RHSConstSplat = RHSBV->getConstantSplatNode();
22599   if (!RHSTrunc && !RHSConstSplat)
22600     return SDValue();
22601
22602   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22603
22604   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22605     return SDValue();
22606
22607   // Set N0 and N1 to hold the inputs to the new wide operation.
22608   N0 = N0->getOperand(0);
22609   if (RHSConstSplat) {
22610     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22611                      SDValue(RHSConstSplat, 0));
22612     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22613     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22614   } else if (RHSTrunc) {
22615     N1 = N1->getOperand(0);
22616   }
22617
22618   // Generate the wide operation.
22619   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22620   unsigned Opcode = N->getOpcode();
22621   switch (Opcode) {
22622   case ISD::ANY_EXTEND:
22623     return Op;
22624   case ISD::ZERO_EXTEND: {
22625     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22626     APInt Mask = APInt::getAllOnesValue(InBits);
22627     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22628     return DAG.getNode(ISD::AND, DL, VT,
22629                        Op, DAG.getConstant(Mask, DL, VT));
22630   }
22631   case ISD::SIGN_EXTEND:
22632     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22633                        Op, DAG.getValueType(NarrowVT));
22634   default:
22635     llvm_unreachable("Unexpected opcode");
22636   }
22637 }
22638
22639 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22640                                  TargetLowering::DAGCombinerInfo &DCI,
22641                                  const X86Subtarget *Subtarget) {
22642   SDValue N0 = N->getOperand(0);
22643   SDValue N1 = N->getOperand(1);
22644   SDLoc DL(N);
22645
22646   // A vector zext_in_reg may be represented as a shuffle,
22647   // feeding into a bitcast (this represents anyext) feeding into
22648   // an and with a mask.
22649   // We'd like to try to combine that into a shuffle with zero
22650   // plus a bitcast, removing the and.
22651   if (N0.getOpcode() != ISD::BITCAST ||
22652       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22653     return SDValue();
22654
22655   // The other side of the AND should be a splat of 2^C, where C
22656   // is the number of bits in the source type.
22657   if (N1.getOpcode() == ISD::BITCAST)
22658     N1 = N1.getOperand(0);
22659   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22660     return SDValue();
22661   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22662
22663   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22664   EVT SrcType = Shuffle->getValueType(0);
22665
22666   // We expect a single-source shuffle
22667   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22668     return SDValue();
22669
22670   unsigned SrcSize = SrcType.getScalarSizeInBits();
22671
22672   APInt SplatValue, SplatUndef;
22673   unsigned SplatBitSize;
22674   bool HasAnyUndefs;
22675   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22676                                 SplatBitSize, HasAnyUndefs))
22677     return SDValue();
22678
22679   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22680   // Make sure the splat matches the mask we expect
22681   if (SplatBitSize > ResSize ||
22682       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22683     return SDValue();
22684
22685   // Make sure the input and output size make sense
22686   if (SrcSize >= ResSize || ResSize % SrcSize)
22687     return SDValue();
22688
22689   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22690   // The number of u's between each two values depends on the ratio between
22691   // the source and dest type.
22692   unsigned ZextRatio = ResSize / SrcSize;
22693   bool IsZext = true;
22694   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22695     if (i % ZextRatio) {
22696       if (Shuffle->getMaskElt(i) > 0) {
22697         // Expected undef
22698         IsZext = false;
22699         break;
22700       }
22701     } else {
22702       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22703         // Expected element number
22704         IsZext = false;
22705         break;
22706       }
22707     }
22708   }
22709
22710   if (!IsZext)
22711     return SDValue();
22712
22713   // Ok, perform the transformation - replace the shuffle with
22714   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22715   // (instead of undef) where the k elements come from the zero vector.
22716   SmallVector<int, 8> Mask;
22717   unsigned NumElems = SrcType.getVectorNumElements();
22718   for (unsigned i = 0; i < NumElems; ++i)
22719     if (i % ZextRatio)
22720       Mask.push_back(NumElems);
22721     else
22722       Mask.push_back(i / ZextRatio);
22723
22724   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22725     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22726   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22727 }
22728
22729 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22730                                  TargetLowering::DAGCombinerInfo &DCI,
22731                                  const X86Subtarget *Subtarget) {
22732   if (DCI.isBeforeLegalizeOps())
22733     return SDValue();
22734
22735   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22736     return Zext;
22737
22738   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22739     return R;
22740
22741   EVT VT = N->getValueType(0);
22742   SDValue N0 = N->getOperand(0);
22743   SDValue N1 = N->getOperand(1);
22744   SDLoc DL(N);
22745
22746   // Create BEXTR instructions
22747   // BEXTR is ((X >> imm) & (2**size-1))
22748   if (VT == MVT::i32 || VT == MVT::i64) {
22749     // Check for BEXTR.
22750     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22751         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22752       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22753       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22754       if (MaskNode && ShiftNode) {
22755         uint64_t Mask = MaskNode->getZExtValue();
22756         uint64_t Shift = ShiftNode->getZExtValue();
22757         if (isMask_64(Mask)) {
22758           uint64_t MaskSize = countPopulation(Mask);
22759           if (Shift + MaskSize <= VT.getSizeInBits())
22760             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22761                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22762                                                VT));
22763         }
22764       }
22765     } // BEXTR
22766
22767     return SDValue();
22768   }
22769
22770   // Want to form ANDNP nodes:
22771   // 1) In the hopes of then easily combining them with OR and AND nodes
22772   //    to form PBLEND/PSIGN.
22773   // 2) To match ANDN packed intrinsics
22774   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22775     return SDValue();
22776
22777   // Check LHS for vnot
22778   if (N0.getOpcode() == ISD::XOR &&
22779       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22780       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22781     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22782
22783   // Check RHS for vnot
22784   if (N1.getOpcode() == ISD::XOR &&
22785       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22786       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22787     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22788
22789   return SDValue();
22790 }
22791
22792 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22793                                 TargetLowering::DAGCombinerInfo &DCI,
22794                                 const X86Subtarget *Subtarget) {
22795   if (DCI.isBeforeLegalizeOps())
22796     return SDValue();
22797
22798   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22799   if (R.getNode())
22800     return R;
22801
22802   SDValue N0 = N->getOperand(0);
22803   SDValue N1 = N->getOperand(1);
22804   EVT VT = N->getValueType(0);
22805
22806   // look for psign/blend
22807   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22808     if (!Subtarget->hasSSSE3() ||
22809         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22810       return SDValue();
22811
22812     // Canonicalize pandn to RHS
22813     if (N0.getOpcode() == X86ISD::ANDNP)
22814       std::swap(N0, N1);
22815     // or (and (m, y), (pandn m, x))
22816     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22817       SDValue Mask = N1.getOperand(0);
22818       SDValue X    = N1.getOperand(1);
22819       SDValue Y;
22820       if (N0.getOperand(0) == Mask)
22821         Y = N0.getOperand(1);
22822       if (N0.getOperand(1) == Mask)
22823         Y = N0.getOperand(0);
22824
22825       // Check to see if the mask appeared in both the AND and ANDNP and
22826       if (!Y.getNode())
22827         return SDValue();
22828
22829       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22830       // Look through mask bitcast.
22831       if (Mask.getOpcode() == ISD::BITCAST)
22832         Mask = Mask.getOperand(0);
22833       if (X.getOpcode() == ISD::BITCAST)
22834         X = X.getOperand(0);
22835       if (Y.getOpcode() == ISD::BITCAST)
22836         Y = Y.getOperand(0);
22837
22838       EVT MaskVT = Mask.getValueType();
22839
22840       // Validate that the Mask operand is a vector sra node.
22841       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22842       // there is no psrai.b
22843       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22844       unsigned SraAmt = ~0;
22845       if (Mask.getOpcode() == ISD::SRA) {
22846         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22847           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22848             SraAmt = AmtConst->getZExtValue();
22849       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22850         SDValue SraC = Mask.getOperand(1);
22851         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22852       }
22853       if ((SraAmt + 1) != EltBits)
22854         return SDValue();
22855
22856       SDLoc DL(N);
22857
22858       // Now we know we at least have a plendvb with the mask val.  See if
22859       // we can form a psignb/w/d.
22860       // psign = x.type == y.type == mask.type && y = sub(0, x);
22861       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22862           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22863           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22864         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22865                "Unsupported VT for PSIGN");
22866         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22867         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22868       }
22869       // PBLENDVB only available on SSE 4.1
22870       if (!Subtarget->hasSSE41())
22871         return SDValue();
22872
22873       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22874
22875       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22876       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22877       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22878       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22879       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22880     }
22881   }
22882
22883   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22884     return SDValue();
22885
22886   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22887   MachineFunction &MF = DAG.getMachineFunction();
22888   bool OptForSize =
22889       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22890
22891   // SHLD/SHRD instructions have lower register pressure, but on some
22892   // platforms they have higher latency than the equivalent
22893   // series of shifts/or that would otherwise be generated.
22894   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22895   // have higher latencies and we are not optimizing for size.
22896   if (!OptForSize && Subtarget->isSHLDSlow())
22897     return SDValue();
22898
22899   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22900     std::swap(N0, N1);
22901   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22902     return SDValue();
22903   if (!N0.hasOneUse() || !N1.hasOneUse())
22904     return SDValue();
22905
22906   SDValue ShAmt0 = N0.getOperand(1);
22907   if (ShAmt0.getValueType() != MVT::i8)
22908     return SDValue();
22909   SDValue ShAmt1 = N1.getOperand(1);
22910   if (ShAmt1.getValueType() != MVT::i8)
22911     return SDValue();
22912   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22913     ShAmt0 = ShAmt0.getOperand(0);
22914   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22915     ShAmt1 = ShAmt1.getOperand(0);
22916
22917   SDLoc DL(N);
22918   unsigned Opc = X86ISD::SHLD;
22919   SDValue Op0 = N0.getOperand(0);
22920   SDValue Op1 = N1.getOperand(0);
22921   if (ShAmt0.getOpcode() == ISD::SUB) {
22922     Opc = X86ISD::SHRD;
22923     std::swap(Op0, Op1);
22924     std::swap(ShAmt0, ShAmt1);
22925   }
22926
22927   unsigned Bits = VT.getSizeInBits();
22928   if (ShAmt1.getOpcode() == ISD::SUB) {
22929     SDValue Sum = ShAmt1.getOperand(0);
22930     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22931       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22932       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22933         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22934       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22935         return DAG.getNode(Opc, DL, VT,
22936                            Op0, Op1,
22937                            DAG.getNode(ISD::TRUNCATE, DL,
22938                                        MVT::i8, ShAmt0));
22939     }
22940   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22941     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22942     if (ShAmt0C &&
22943         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22944       return DAG.getNode(Opc, DL, VT,
22945                          N0.getOperand(0), N1.getOperand(0),
22946                          DAG.getNode(ISD::TRUNCATE, DL,
22947                                        MVT::i8, ShAmt0));
22948   }
22949
22950   return SDValue();
22951 }
22952
22953 // Generate NEG and CMOV for integer abs.
22954 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22955   EVT VT = N->getValueType(0);
22956
22957   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22958   // 8-bit integer abs to NEG and CMOV.
22959   if (VT.isInteger() && VT.getSizeInBits() == 8)
22960     return SDValue();
22961
22962   SDValue N0 = N->getOperand(0);
22963   SDValue N1 = N->getOperand(1);
22964   SDLoc DL(N);
22965
22966   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22967   // and change it to SUB and CMOV.
22968   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22969       N0.getOpcode() == ISD::ADD &&
22970       N0.getOperand(1) == N1 &&
22971       N1.getOpcode() == ISD::SRA &&
22972       N1.getOperand(0) == N0.getOperand(0))
22973     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22974       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22975         // Generate SUB & CMOV.
22976         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22977                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22978
22979         SDValue Ops[] = { N0.getOperand(0), Neg,
22980                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22981                           SDValue(Neg.getNode(), 1) };
22982         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22983       }
22984   return SDValue();
22985 }
22986
22987 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22988 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22989                                  TargetLowering::DAGCombinerInfo &DCI,
22990                                  const X86Subtarget *Subtarget) {
22991   if (DCI.isBeforeLegalizeOps())
22992     return SDValue();
22993
22994   if (Subtarget->hasCMov()) {
22995     SDValue RV = performIntegerAbsCombine(N, DAG);
22996     if (RV.getNode())
22997       return RV;
22998   }
22999
23000   return SDValue();
23001 }
23002
23003 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23004 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23005                                   TargetLowering::DAGCombinerInfo &DCI,
23006                                   const X86Subtarget *Subtarget) {
23007   LoadSDNode *Ld = cast<LoadSDNode>(N);
23008   EVT RegVT = Ld->getValueType(0);
23009   EVT MemVT = Ld->getMemoryVT();
23010   SDLoc dl(Ld);
23011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23012
23013   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23014   // into two 16-byte operations.
23015   ISD::LoadExtType Ext = Ld->getExtensionType();
23016   unsigned Alignment = Ld->getAlignment();
23017   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23018   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23019       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23020     unsigned NumElems = RegVT.getVectorNumElements();
23021     if (NumElems < 2)
23022       return SDValue();
23023
23024     SDValue Ptr = Ld->getBasePtr();
23025     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23026
23027     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23028                                   NumElems/2);
23029     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23030                                 Ld->getPointerInfo(), Ld->isVolatile(),
23031                                 Ld->isNonTemporal(), Ld->isInvariant(),
23032                                 Alignment);
23033     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23034     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23035                                 Ld->getPointerInfo(), Ld->isVolatile(),
23036                                 Ld->isNonTemporal(), Ld->isInvariant(),
23037                                 std::min(16U, Alignment));
23038     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23039                              Load1.getValue(1),
23040                              Load2.getValue(1));
23041
23042     SDValue NewVec = DAG.getUNDEF(RegVT);
23043     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23044     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23045     return DCI.CombineTo(N, NewVec, TF, true);
23046   }
23047
23048   return SDValue();
23049 }
23050
23051 /// PerformMLOADCombine - Resolve extending loads
23052 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23053                                    TargetLowering::DAGCombinerInfo &DCI,
23054                                    const X86Subtarget *Subtarget) {
23055   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23056   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23057     return SDValue();
23058
23059   EVT VT = Mld->getValueType(0);
23060   unsigned NumElems = VT.getVectorNumElements();
23061   EVT LdVT = Mld->getMemoryVT();
23062   SDLoc dl(Mld);
23063
23064   assert(LdVT != VT && "Cannot extend to the same type");
23065   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23066   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23067   // From, To sizes and ElemCount must be pow of two
23068   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23069     "Unexpected size for extending masked load");
23070
23071   unsigned SizeRatio  = ToSz / FromSz;
23072   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23073
23074   // Create a type on which we perform the shuffle
23075   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23076           LdVT.getScalarType(), NumElems*SizeRatio);
23077   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23078
23079   // Convert Src0 value
23080   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
23081   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23082     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23083     for (unsigned i = 0; i != NumElems; ++i)
23084       ShuffleVec[i] = i * SizeRatio;
23085
23086     // Can't shuffle using an illegal type.
23087     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23088             && "WideVecVT should be legal");
23089     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23090                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23091   }
23092   // Prepare the new mask
23093   SDValue NewMask;
23094   SDValue Mask = Mld->getMask();
23095   if (Mask.getValueType() == VT) {
23096     // Mask and original value have the same type
23097     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23098     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23099     for (unsigned i = 0; i != NumElems; ++i)
23100       ShuffleVec[i] = i * SizeRatio;
23101     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23102       ShuffleVec[i] = NumElems*SizeRatio;
23103     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23104                                    DAG.getConstant(0, dl, WideVecVT),
23105                                    &ShuffleVec[0]);
23106   }
23107   else {
23108     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23109     unsigned WidenNumElts = NumElems*SizeRatio;
23110     unsigned MaskNumElts = VT.getVectorNumElements();
23111     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23112                                      WidenNumElts);
23113
23114     unsigned NumConcat = WidenNumElts / MaskNumElts;
23115     SmallVector<SDValue, 16> Ops(NumConcat);
23116     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23117     Ops[0] = Mask;
23118     for (unsigned i = 1; i != NumConcat; ++i)
23119       Ops[i] = ZeroVal;
23120
23121     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23122   }
23123
23124   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23125                                      Mld->getBasePtr(), NewMask, WideSrc0,
23126                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23127                                      ISD::NON_EXTLOAD);
23128   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23129   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23130
23131 }
23132 /// PerformMSTORECombine - Resolve truncating stores
23133 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23134                                     const X86Subtarget *Subtarget) {
23135   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23136   if (!Mst->isTruncatingStore())
23137     return SDValue();
23138
23139   EVT VT = Mst->getValue().getValueType();
23140   unsigned NumElems = VT.getVectorNumElements();
23141   EVT StVT = Mst->getMemoryVT();
23142   SDLoc dl(Mst);
23143
23144   assert(StVT != VT && "Cannot truncate to the same type");
23145   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23146   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23147
23148   // From, To sizes and ElemCount must be pow of two
23149   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23150     "Unexpected size for truncating masked store");
23151   // We are going to use the original vector elt for storing.
23152   // Accumulated smaller vector elements must be a multiple of the store size.
23153   assert (((NumElems * FromSz) % ToSz) == 0 &&
23154           "Unexpected ratio for truncating masked store");
23155
23156   unsigned SizeRatio  = FromSz / ToSz;
23157   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23158
23159   // Create a type on which we perform the shuffle
23160   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23161           StVT.getScalarType(), NumElems*SizeRatio);
23162
23163   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23164
23165   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23166   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23167   for (unsigned i = 0; i != NumElems; ++i)
23168     ShuffleVec[i] = i * SizeRatio;
23169
23170   // Can't shuffle using an illegal type.
23171   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23172           && "WideVecVT should be legal");
23173
23174   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23175                                         DAG.getUNDEF(WideVecVT),
23176                                         &ShuffleVec[0]);
23177
23178   SDValue NewMask;
23179   SDValue Mask = Mst->getMask();
23180   if (Mask.getValueType() == VT) {
23181     // Mask and original value have the same type
23182     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23183     for (unsigned i = 0; i != NumElems; ++i)
23184       ShuffleVec[i] = i * SizeRatio;
23185     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23186       ShuffleVec[i] = NumElems*SizeRatio;
23187     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23188                                    DAG.getConstant(0, dl, WideVecVT),
23189                                    &ShuffleVec[0]);
23190   }
23191   else {
23192     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23193     unsigned WidenNumElts = NumElems*SizeRatio;
23194     unsigned MaskNumElts = VT.getVectorNumElements();
23195     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23196                                      WidenNumElts);
23197
23198     unsigned NumConcat = WidenNumElts / MaskNumElts;
23199     SmallVector<SDValue, 16> Ops(NumConcat);
23200     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23201     Ops[0] = Mask;
23202     for (unsigned i = 1; i != NumConcat; ++i)
23203       Ops[i] = ZeroVal;
23204
23205     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23206   }
23207
23208   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23209                             NewMask, StVT, Mst->getMemOperand(), false);
23210 }
23211 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23212 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23213                                    const X86Subtarget *Subtarget) {
23214   StoreSDNode *St = cast<StoreSDNode>(N);
23215   EVT VT = St->getValue().getValueType();
23216   EVT StVT = St->getMemoryVT();
23217   SDLoc dl(St);
23218   SDValue StoredVal = St->getOperand(1);
23219   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23220
23221   // If we are saving a concatenation of two XMM registers and 32-byte stores
23222   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23223   unsigned Alignment = St->getAlignment();
23224   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23225   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23226       StVT == VT && !IsAligned) {
23227     unsigned NumElems = VT.getVectorNumElements();
23228     if (NumElems < 2)
23229       return SDValue();
23230
23231     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23232     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23233
23234     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23235     SDValue Ptr0 = St->getBasePtr();
23236     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23237
23238     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23239                                 St->getPointerInfo(), St->isVolatile(),
23240                                 St->isNonTemporal(), Alignment);
23241     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23242                                 St->getPointerInfo(), St->isVolatile(),
23243                                 St->isNonTemporal(),
23244                                 std::min(16U, Alignment));
23245     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23246   }
23247
23248   // Optimize trunc store (of multiple scalars) to shuffle and store.
23249   // First, pack all of the elements in one place. Next, store to memory
23250   // in fewer chunks.
23251   if (St->isTruncatingStore() && VT.isVector()) {
23252     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23253     unsigned NumElems = VT.getVectorNumElements();
23254     assert(StVT != VT && "Cannot truncate to the same type");
23255     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23256     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23257
23258     // From, To sizes and ElemCount must be pow of two
23259     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23260     // We are going to use the original vector elt for storing.
23261     // Accumulated smaller vector elements must be a multiple of the store size.
23262     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23263
23264     unsigned SizeRatio  = FromSz / ToSz;
23265
23266     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23267
23268     // Create a type on which we perform the shuffle
23269     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23270             StVT.getScalarType(), NumElems*SizeRatio);
23271
23272     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23273
23274     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23275     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23276     for (unsigned i = 0; i != NumElems; ++i)
23277       ShuffleVec[i] = i * SizeRatio;
23278
23279     // Can't shuffle using an illegal type.
23280     if (!TLI.isTypeLegal(WideVecVT))
23281       return SDValue();
23282
23283     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23284                                          DAG.getUNDEF(WideVecVT),
23285                                          &ShuffleVec[0]);
23286     // At this point all of the data is stored at the bottom of the
23287     // register. We now need to save it to mem.
23288
23289     // Find the largest store unit
23290     MVT StoreType = MVT::i8;
23291     for (MVT Tp : MVT::integer_valuetypes()) {
23292       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23293         StoreType = Tp;
23294     }
23295
23296     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23297     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23298         (64 <= NumElems * ToSz))
23299       StoreType = MVT::f64;
23300
23301     // Bitcast the original vector into a vector of store-size units
23302     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23303             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23304     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23305     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23306     SmallVector<SDValue, 8> Chains;
23307     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23308                                         TLI.getPointerTy());
23309     SDValue Ptr = St->getBasePtr();
23310
23311     // Perform one or more big stores into memory.
23312     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23313       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23314                                    StoreType, ShuffWide,
23315                                    DAG.getIntPtrConstant(i, dl));
23316       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23317                                 St->getPointerInfo(), St->isVolatile(),
23318                                 St->isNonTemporal(), St->getAlignment());
23319       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23320       Chains.push_back(Ch);
23321     }
23322
23323     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23324   }
23325
23326   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23327   // the FP state in cases where an emms may be missing.
23328   // A preferable solution to the general problem is to figure out the right
23329   // places to insert EMMS.  This qualifies as a quick hack.
23330
23331   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23332   if (VT.getSizeInBits() != 64)
23333     return SDValue();
23334
23335   const Function *F = DAG.getMachineFunction().getFunction();
23336   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23337   bool F64IsLegal =
23338       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23339   if ((VT.isVector() ||
23340        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23341       isa<LoadSDNode>(St->getValue()) &&
23342       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23343       St->getChain().hasOneUse() && !St->isVolatile()) {
23344     SDNode* LdVal = St->getValue().getNode();
23345     LoadSDNode *Ld = nullptr;
23346     int TokenFactorIndex = -1;
23347     SmallVector<SDValue, 8> Ops;
23348     SDNode* ChainVal = St->getChain().getNode();
23349     // Must be a store of a load.  We currently handle two cases:  the load
23350     // is a direct child, and it's under an intervening TokenFactor.  It is
23351     // possible to dig deeper under nested TokenFactors.
23352     if (ChainVal == LdVal)
23353       Ld = cast<LoadSDNode>(St->getChain());
23354     else if (St->getValue().hasOneUse() &&
23355              ChainVal->getOpcode() == ISD::TokenFactor) {
23356       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23357         if (ChainVal->getOperand(i).getNode() == LdVal) {
23358           TokenFactorIndex = i;
23359           Ld = cast<LoadSDNode>(St->getValue());
23360         } else
23361           Ops.push_back(ChainVal->getOperand(i));
23362       }
23363     }
23364
23365     if (!Ld || !ISD::isNormalLoad(Ld))
23366       return SDValue();
23367
23368     // If this is not the MMX case, i.e. we are just turning i64 load/store
23369     // into f64 load/store, avoid the transformation if there are multiple
23370     // uses of the loaded value.
23371     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23372       return SDValue();
23373
23374     SDLoc LdDL(Ld);
23375     SDLoc StDL(N);
23376     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23377     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23378     // pair instead.
23379     if (Subtarget->is64Bit() || F64IsLegal) {
23380       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23381       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23382                                   Ld->getPointerInfo(), Ld->isVolatile(),
23383                                   Ld->isNonTemporal(), Ld->isInvariant(),
23384                                   Ld->getAlignment());
23385       SDValue NewChain = NewLd.getValue(1);
23386       if (TokenFactorIndex != -1) {
23387         Ops.push_back(NewChain);
23388         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23389       }
23390       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23391                           St->getPointerInfo(),
23392                           St->isVolatile(), St->isNonTemporal(),
23393                           St->getAlignment());
23394     }
23395
23396     // Otherwise, lower to two pairs of 32-bit loads / stores.
23397     SDValue LoAddr = Ld->getBasePtr();
23398     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23399                                  DAG.getConstant(4, LdDL, MVT::i32));
23400
23401     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23402                                Ld->getPointerInfo(),
23403                                Ld->isVolatile(), Ld->isNonTemporal(),
23404                                Ld->isInvariant(), Ld->getAlignment());
23405     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23406                                Ld->getPointerInfo().getWithOffset(4),
23407                                Ld->isVolatile(), Ld->isNonTemporal(),
23408                                Ld->isInvariant(),
23409                                MinAlign(Ld->getAlignment(), 4));
23410
23411     SDValue NewChain = LoLd.getValue(1);
23412     if (TokenFactorIndex != -1) {
23413       Ops.push_back(LoLd);
23414       Ops.push_back(HiLd);
23415       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23416     }
23417
23418     LoAddr = St->getBasePtr();
23419     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23420                          DAG.getConstant(4, StDL, MVT::i32));
23421
23422     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23423                                 St->getPointerInfo(),
23424                                 St->isVolatile(), St->isNonTemporal(),
23425                                 St->getAlignment());
23426     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23427                                 St->getPointerInfo().getWithOffset(4),
23428                                 St->isVolatile(),
23429                                 St->isNonTemporal(),
23430                                 MinAlign(St->getAlignment(), 4));
23431     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23432   }
23433
23434   // This is similar to the above case, but here we handle a scalar 64-bit
23435   // integer store that is extracted from a vector on a 32-bit target.
23436   // If we have SSE2, then we can treat it like a floating-point double
23437   // to get past legalization. The execution dependencies fixup pass will
23438   // choose the optimal machine instruction for the store if this really is
23439   // an integer or v2f32 rather than an f64.
23440   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23441       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23442     SDValue OldExtract = St->getOperand(1);
23443     SDValue ExtOp0 = OldExtract.getOperand(0);
23444     unsigned VecSize = ExtOp0.getValueSizeInBits();
23445     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23446     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23447     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23448                                      BitCast, OldExtract.getOperand(1));
23449     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23450                         St->getPointerInfo(), St->isVolatile(),
23451                         St->isNonTemporal(), St->getAlignment());
23452   }
23453
23454   return SDValue();
23455 }
23456
23457 /// Return 'true' if this vector operation is "horizontal"
23458 /// and return the operands for the horizontal operation in LHS and RHS.  A
23459 /// horizontal operation performs the binary operation on successive elements
23460 /// of its first operand, then on successive elements of its second operand,
23461 /// returning the resulting values in a vector.  For example, if
23462 ///   A = < float a0, float a1, float a2, float a3 >
23463 /// and
23464 ///   B = < float b0, float b1, float b2, float b3 >
23465 /// then the result of doing a horizontal operation on A and B is
23466 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23467 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23468 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23469 /// set to A, RHS to B, and the routine returns 'true'.
23470 /// Note that the binary operation should have the property that if one of the
23471 /// operands is UNDEF then the result is UNDEF.
23472 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23473   // Look for the following pattern: if
23474   //   A = < float a0, float a1, float a2, float a3 >
23475   //   B = < float b0, float b1, float b2, float b3 >
23476   // and
23477   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23478   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23479   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23480   // which is A horizontal-op B.
23481
23482   // At least one of the operands should be a vector shuffle.
23483   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23484       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23485     return false;
23486
23487   MVT VT = LHS.getSimpleValueType();
23488
23489   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23490          "Unsupported vector type for horizontal add/sub");
23491
23492   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23493   // operate independently on 128-bit lanes.
23494   unsigned NumElts = VT.getVectorNumElements();
23495   unsigned NumLanes = VT.getSizeInBits()/128;
23496   unsigned NumLaneElts = NumElts / NumLanes;
23497   assert((NumLaneElts % 2 == 0) &&
23498          "Vector type should have an even number of elements in each lane");
23499   unsigned HalfLaneElts = NumLaneElts/2;
23500
23501   // View LHS in the form
23502   //   LHS = VECTOR_SHUFFLE A, B, LMask
23503   // If LHS is not a shuffle then pretend it is the shuffle
23504   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23505   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23506   // type VT.
23507   SDValue A, B;
23508   SmallVector<int, 16> LMask(NumElts);
23509   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23510     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23511       A = LHS.getOperand(0);
23512     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23513       B = LHS.getOperand(1);
23514     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23515     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23516   } else {
23517     if (LHS.getOpcode() != ISD::UNDEF)
23518       A = LHS;
23519     for (unsigned i = 0; i != NumElts; ++i)
23520       LMask[i] = i;
23521   }
23522
23523   // Likewise, view RHS in the form
23524   //   RHS = VECTOR_SHUFFLE C, D, RMask
23525   SDValue C, D;
23526   SmallVector<int, 16> RMask(NumElts);
23527   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23528     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23529       C = RHS.getOperand(0);
23530     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23531       D = RHS.getOperand(1);
23532     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23533     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23534   } else {
23535     if (RHS.getOpcode() != ISD::UNDEF)
23536       C = RHS;
23537     for (unsigned i = 0; i != NumElts; ++i)
23538       RMask[i] = i;
23539   }
23540
23541   // Check that the shuffles are both shuffling the same vectors.
23542   if (!(A == C && B == D) && !(A == D && B == C))
23543     return false;
23544
23545   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23546   if (!A.getNode() && !B.getNode())
23547     return false;
23548
23549   // If A and B occur in reverse order in RHS, then "swap" them (which means
23550   // rewriting the mask).
23551   if (A != C)
23552     ShuffleVectorSDNode::commuteMask(RMask);
23553
23554   // At this point LHS and RHS are equivalent to
23555   //   LHS = VECTOR_SHUFFLE A, B, LMask
23556   //   RHS = VECTOR_SHUFFLE A, B, RMask
23557   // Check that the masks correspond to performing a horizontal operation.
23558   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23559     for (unsigned i = 0; i != NumLaneElts; ++i) {
23560       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23561
23562       // Ignore any UNDEF components.
23563       if (LIdx < 0 || RIdx < 0 ||
23564           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23565           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23566         continue;
23567
23568       // Check that successive elements are being operated on.  If not, this is
23569       // not a horizontal operation.
23570       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23571       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23572       if (!(LIdx == Index && RIdx == Index + 1) &&
23573           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23574         return false;
23575     }
23576   }
23577
23578   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23579   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23580   return true;
23581 }
23582
23583 /// Do target-specific dag combines on floating point adds.
23584 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23585                                   const X86Subtarget *Subtarget) {
23586   EVT VT = N->getValueType(0);
23587   SDValue LHS = N->getOperand(0);
23588   SDValue RHS = N->getOperand(1);
23589
23590   // Try to synthesize horizontal adds from adds of shuffles.
23591   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23592        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23593       isHorizontalBinOp(LHS, RHS, true))
23594     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23595   return SDValue();
23596 }
23597
23598 /// Do target-specific dag combines on floating point subs.
23599 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23600                                   const X86Subtarget *Subtarget) {
23601   EVT VT = N->getValueType(0);
23602   SDValue LHS = N->getOperand(0);
23603   SDValue RHS = N->getOperand(1);
23604
23605   // Try to synthesize horizontal subs from subs of shuffles.
23606   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23607        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23608       isHorizontalBinOp(LHS, RHS, false))
23609     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23610   return SDValue();
23611 }
23612
23613 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23614 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23615   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23616
23617   // F[X]OR(0.0, x) -> x
23618   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23619     if (C->getValueAPF().isPosZero())
23620       return N->getOperand(1);
23621
23622   // F[X]OR(x, 0.0) -> x
23623   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23624     if (C->getValueAPF().isPosZero())
23625       return N->getOperand(0);
23626   return SDValue();
23627 }
23628
23629 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23630 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23631   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23632
23633   // Only perform optimizations if UnsafeMath is used.
23634   if (!DAG.getTarget().Options.UnsafeFPMath)
23635     return SDValue();
23636
23637   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23638   // into FMINC and FMAXC, which are Commutative operations.
23639   unsigned NewOp = 0;
23640   switch (N->getOpcode()) {
23641     default: llvm_unreachable("unknown opcode");
23642     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23643     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23644   }
23645
23646   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23647                      N->getOperand(0), N->getOperand(1));
23648 }
23649
23650 /// Do target-specific dag combines on X86ISD::FAND nodes.
23651 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23652   // FAND(0.0, x) -> 0.0
23653   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23654     if (C->getValueAPF().isPosZero())
23655       return N->getOperand(0);
23656
23657   // FAND(x, 0.0) -> 0.0
23658   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23659     if (C->getValueAPF().isPosZero())
23660       return N->getOperand(1);
23661
23662   return SDValue();
23663 }
23664
23665 /// Do target-specific dag combines on X86ISD::FANDN nodes
23666 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23667   // FANDN(0.0, x) -> x
23668   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23669     if (C->getValueAPF().isPosZero())
23670       return N->getOperand(1);
23671
23672   // FANDN(x, 0.0) -> 0.0
23673   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23674     if (C->getValueAPF().isPosZero())
23675       return N->getOperand(1);
23676
23677   return SDValue();
23678 }
23679
23680 static SDValue PerformBTCombine(SDNode *N,
23681                                 SelectionDAG &DAG,
23682                                 TargetLowering::DAGCombinerInfo &DCI) {
23683   // BT ignores high bits in the bit index operand.
23684   SDValue Op1 = N->getOperand(1);
23685   if (Op1.hasOneUse()) {
23686     unsigned BitWidth = Op1.getValueSizeInBits();
23687     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23688     APInt KnownZero, KnownOne;
23689     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23690                                           !DCI.isBeforeLegalizeOps());
23691     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23692     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23693         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23694       DCI.CommitTargetLoweringOpt(TLO);
23695   }
23696   return SDValue();
23697 }
23698
23699 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23700   SDValue Op = N->getOperand(0);
23701   if (Op.getOpcode() == ISD::BITCAST)
23702     Op = Op.getOperand(0);
23703   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23704   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23705       VT.getVectorElementType().getSizeInBits() ==
23706       OpVT.getVectorElementType().getSizeInBits()) {
23707     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23708   }
23709   return SDValue();
23710 }
23711
23712 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23713                                                const X86Subtarget *Subtarget) {
23714   EVT VT = N->getValueType(0);
23715   if (!VT.isVector())
23716     return SDValue();
23717
23718   SDValue N0 = N->getOperand(0);
23719   SDValue N1 = N->getOperand(1);
23720   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23721   SDLoc dl(N);
23722
23723   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23724   // both SSE and AVX2 since there is no sign-extended shift right
23725   // operation on a vector with 64-bit elements.
23726   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23727   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23728   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23729       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23730     SDValue N00 = N0.getOperand(0);
23731
23732     // EXTLOAD has a better solution on AVX2,
23733     // it may be replaced with X86ISD::VSEXT node.
23734     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23735       if (!ISD::isNormalLoad(N00.getNode()))
23736         return SDValue();
23737
23738     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23739         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23740                                   N00, N1);
23741       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23742     }
23743   }
23744   return SDValue();
23745 }
23746
23747 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23748                                   TargetLowering::DAGCombinerInfo &DCI,
23749                                   const X86Subtarget *Subtarget) {
23750   SDValue N0 = N->getOperand(0);
23751   EVT VT = N->getValueType(0);
23752   EVT SVT = VT.getScalarType();
23753   EVT InVT = N0->getValueType(0);
23754   EVT InSVT = InVT.getScalarType();
23755   SDLoc DL(N);
23756
23757   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23758   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23759   // This exposes the sext to the sdivrem lowering, so that it directly extends
23760   // from AH (which we otherwise need to do contortions to access).
23761   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23762       InVT == MVT::i8 && VT == MVT::i32) {
23763     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23764     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
23765                             N0.getOperand(0), N0.getOperand(1));
23766     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23767     return R.getValue(1);
23768   }
23769
23770   if (!DCI.isBeforeLegalizeOps()) {
23771     if (N0.getValueType() == MVT::i1) {
23772       SDValue Zero = DAG.getConstant(0, DL, VT);
23773       SDValue AllOnes =
23774         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
23775       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
23776     }
23777     return SDValue();
23778   }
23779
23780   if (VT.isVector()) {
23781     auto ExtendToVec128 = [&DAG](SDLoc DL, SDValue N) {
23782       EVT InVT = N->getValueType(0);
23783       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
23784                                    128 / InVT.getScalarSizeInBits());
23785       SmallVector<SDValue, 8> Opnds(128 / InVT.getSizeInBits(),
23786                                     DAG.getUNDEF(InVT));
23787       Opnds[0] = N;
23788       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
23789     };
23790
23791     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
23792     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
23793     if (VT.getSizeInBits() == 128 &&
23794         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23795         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23796       SDValue ExOp = ExtendToVec128(DL, N0);
23797       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
23798     }
23799
23800     // On pre-AVX2 targets, split into 128-bit nodes of
23801     // ISD::SIGN_EXTEND_VECTOR_INREG.
23802     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
23803         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23804         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23805       unsigned NumVecs = VT.getSizeInBits() / 128;
23806       unsigned NumSubElts = 128 / SVT.getSizeInBits();
23807       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
23808       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
23809
23810       SmallVector<SDValue, 8> Opnds;
23811       for (unsigned i = 0, Offset = 0; i != NumVecs;
23812            ++i, Offset += NumSubElts) {
23813         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
23814                                      DAG.getIntPtrConstant(Offset, DL));
23815         SrcVec = ExtendToVec128(DL, SrcVec);
23816         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
23817         Opnds.push_back(SrcVec);
23818       }
23819       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
23820     }
23821   }
23822
23823   if (!Subtarget->hasFp256())
23824     return SDValue();
23825
23826   if (VT.isVector() && VT.getSizeInBits() == 256) {
23827     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23828     if (R.getNode())
23829       return R;
23830   }
23831
23832   return SDValue();
23833 }
23834
23835 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23836                                  const X86Subtarget* Subtarget) {
23837   SDLoc dl(N);
23838   EVT VT = N->getValueType(0);
23839
23840   // Let legalize expand this if it isn't a legal type yet.
23841   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23842     return SDValue();
23843
23844   EVT ScalarVT = VT.getScalarType();
23845   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23846       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23847     return SDValue();
23848
23849   SDValue A = N->getOperand(0);
23850   SDValue B = N->getOperand(1);
23851   SDValue C = N->getOperand(2);
23852
23853   bool NegA = (A.getOpcode() == ISD::FNEG);
23854   bool NegB = (B.getOpcode() == ISD::FNEG);
23855   bool NegC = (C.getOpcode() == ISD::FNEG);
23856
23857   // Negative multiplication when NegA xor NegB
23858   bool NegMul = (NegA != NegB);
23859   if (NegA)
23860     A = A.getOperand(0);
23861   if (NegB)
23862     B = B.getOperand(0);
23863   if (NegC)
23864     C = C.getOperand(0);
23865
23866   unsigned Opcode;
23867   if (!NegMul)
23868     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23869   else
23870     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23871
23872   return DAG.getNode(Opcode, dl, VT, A, B, C);
23873 }
23874
23875 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23876                                   TargetLowering::DAGCombinerInfo &DCI,
23877                                   const X86Subtarget *Subtarget) {
23878   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23879   //           (and (i32 x86isd::setcc_carry), 1)
23880   // This eliminates the zext. This transformation is necessary because
23881   // ISD::SETCC is always legalized to i8.
23882   SDLoc dl(N);
23883   SDValue N0 = N->getOperand(0);
23884   EVT VT = N->getValueType(0);
23885
23886   if (N0.getOpcode() == ISD::AND &&
23887       N0.hasOneUse() &&
23888       N0.getOperand(0).hasOneUse()) {
23889     SDValue N00 = N0.getOperand(0);
23890     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23891       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23892       if (!C || C->getZExtValue() != 1)
23893         return SDValue();
23894       return DAG.getNode(ISD::AND, dl, VT,
23895                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23896                                      N00.getOperand(0), N00.getOperand(1)),
23897                          DAG.getConstant(1, dl, VT));
23898     }
23899   }
23900
23901   if (N0.getOpcode() == ISD::TRUNCATE &&
23902       N0.hasOneUse() &&
23903       N0.getOperand(0).hasOneUse()) {
23904     SDValue N00 = N0.getOperand(0);
23905     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23906       return DAG.getNode(ISD::AND, dl, VT,
23907                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23908                                      N00.getOperand(0), N00.getOperand(1)),
23909                          DAG.getConstant(1, dl, VT));
23910     }
23911   }
23912   if (VT.is256BitVector()) {
23913     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23914     if (R.getNode())
23915       return R;
23916   }
23917
23918   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23919   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23920   // This exposes the zext to the udivrem lowering, so that it directly extends
23921   // from AH (which we otherwise need to do contortions to access).
23922   if (N0.getOpcode() == ISD::UDIVREM &&
23923       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23924       (VT == MVT::i32 || VT == MVT::i64)) {
23925     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23926     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23927                             N0.getOperand(0), N0.getOperand(1));
23928     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23929     return R.getValue(1);
23930   }
23931
23932   return SDValue();
23933 }
23934
23935 // Optimize x == -y --> x+y == 0
23936 //          x != -y --> x+y != 0
23937 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23938                                       const X86Subtarget* Subtarget) {
23939   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23940   SDValue LHS = N->getOperand(0);
23941   SDValue RHS = N->getOperand(1);
23942   EVT VT = N->getValueType(0);
23943   SDLoc DL(N);
23944
23945   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23946     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23947       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23948         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23949                                    LHS.getOperand(1));
23950         return DAG.getSetCC(DL, N->getValueType(0), addV,
23951                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23952       }
23953   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23954     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23955       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23956         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23957                                    RHS.getOperand(1));
23958         return DAG.getSetCC(DL, N->getValueType(0), addV,
23959                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23960       }
23961
23962   if (VT.getScalarType() == MVT::i1 &&
23963       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23964     bool IsSEXT0 =
23965         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23966         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23967     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23968
23969     if (!IsSEXT0 || !IsVZero1) {
23970       // Swap the operands and update the condition code.
23971       std::swap(LHS, RHS);
23972       CC = ISD::getSetCCSwappedOperands(CC);
23973
23974       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23975                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23976       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23977     }
23978
23979     if (IsSEXT0 && IsVZero1) {
23980       assert(VT == LHS.getOperand(0).getValueType() &&
23981              "Uexpected operand type");
23982       if (CC == ISD::SETGT)
23983         return DAG.getConstant(0, DL, VT);
23984       if (CC == ISD::SETLE)
23985         return DAG.getConstant(1, DL, VT);
23986       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23987         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23988
23989       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23990              "Unexpected condition code!");
23991       return LHS.getOperand(0);
23992     }
23993   }
23994
23995   return SDValue();
23996 }
23997
23998 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23999                                          SelectionDAG &DAG) {
24000   SDLoc dl(Load);
24001   MVT VT = Load->getSimpleValueType(0);
24002   MVT EVT = VT.getVectorElementType();
24003   SDValue Addr = Load->getOperand(1);
24004   SDValue NewAddr = DAG.getNode(
24005       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24006       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24007                       Addr.getSimpleValueType()));
24008
24009   SDValue NewLoad =
24010       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24011                   DAG.getMachineFunction().getMachineMemOperand(
24012                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24013   return NewLoad;
24014 }
24015
24016 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24017                                       const X86Subtarget *Subtarget) {
24018   SDLoc dl(N);
24019   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24020   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24021          "X86insertps is only defined for v4x32");
24022
24023   SDValue Ld = N->getOperand(1);
24024   if (MayFoldLoad(Ld)) {
24025     // Extract the countS bits from the immediate so we can get the proper
24026     // address when narrowing the vector load to a specific element.
24027     // When the second source op is a memory address, insertps doesn't use
24028     // countS and just gets an f32 from that address.
24029     unsigned DestIndex =
24030         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24031
24032     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24033
24034     // Create this as a scalar to vector to match the instruction pattern.
24035     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24036     // countS bits are ignored when loading from memory on insertps, which
24037     // means we don't need to explicitly set them to 0.
24038     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24039                        LoadScalarToVector, N->getOperand(2));
24040   }
24041   return SDValue();
24042 }
24043
24044 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24045   SDValue V0 = N->getOperand(0);
24046   SDValue V1 = N->getOperand(1);
24047   SDLoc DL(N);
24048   EVT VT = N->getValueType(0);
24049
24050   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24051   // operands and changing the mask to 1. This saves us a bunch of
24052   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24053   // x86InstrInfo knows how to commute this back after instruction selection
24054   // if it would help register allocation.
24055
24056   // TODO: If optimizing for size or a processor that doesn't suffer from
24057   // partial register update stalls, this should be transformed into a MOVSD
24058   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24059
24060   if (VT == MVT::v2f64)
24061     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24062       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24063         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24064         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24065       }
24066
24067   return SDValue();
24068 }
24069
24070 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24071 // as "sbb reg,reg", since it can be extended without zext and produces
24072 // an all-ones bit which is more useful than 0/1 in some cases.
24073 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24074                                MVT VT) {
24075   if (VT == MVT::i8)
24076     return DAG.getNode(ISD::AND, DL, VT,
24077                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24078                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24079                                    EFLAGS),
24080                        DAG.getConstant(1, DL, VT));
24081   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24082   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24083                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24084                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24085                                  EFLAGS));
24086 }
24087
24088 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24089 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24090                                    TargetLowering::DAGCombinerInfo &DCI,
24091                                    const X86Subtarget *Subtarget) {
24092   SDLoc DL(N);
24093   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24094   SDValue EFLAGS = N->getOperand(1);
24095
24096   if (CC == X86::COND_A) {
24097     // Try to convert COND_A into COND_B in an attempt to facilitate
24098     // materializing "setb reg".
24099     //
24100     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24101     // cannot take an immediate as its first operand.
24102     //
24103     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24104         EFLAGS.getValueType().isInteger() &&
24105         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24106       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24107                                    EFLAGS.getNode()->getVTList(),
24108                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24109       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24110       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24111     }
24112   }
24113
24114   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24115   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24116   // cases.
24117   if (CC == X86::COND_B)
24118     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24119
24120   SDValue Flags;
24121
24122   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24123   if (Flags.getNode()) {
24124     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24125     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24126   }
24127
24128   return SDValue();
24129 }
24130
24131 // Optimize branch condition evaluation.
24132 //
24133 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24134                                     TargetLowering::DAGCombinerInfo &DCI,
24135                                     const X86Subtarget *Subtarget) {
24136   SDLoc DL(N);
24137   SDValue Chain = N->getOperand(0);
24138   SDValue Dest = N->getOperand(1);
24139   SDValue EFLAGS = N->getOperand(3);
24140   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24141
24142   SDValue Flags;
24143
24144   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24145   if (Flags.getNode()) {
24146     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24147     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24148                        Flags);
24149   }
24150
24151   return SDValue();
24152 }
24153
24154 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24155                                                          SelectionDAG &DAG) {
24156   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24157   // optimize away operation when it's from a constant.
24158   //
24159   // The general transformation is:
24160   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24161   //       AND(VECTOR_CMP(x,y), constant2)
24162   //    constant2 = UNARYOP(constant)
24163
24164   // Early exit if this isn't a vector operation, the operand of the
24165   // unary operation isn't a bitwise AND, or if the sizes of the operations
24166   // aren't the same.
24167   EVT VT = N->getValueType(0);
24168   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24169       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24170       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24171     return SDValue();
24172
24173   // Now check that the other operand of the AND is a constant. We could
24174   // make the transformation for non-constant splats as well, but it's unclear
24175   // that would be a benefit as it would not eliminate any operations, just
24176   // perform one more step in scalar code before moving to the vector unit.
24177   if (BuildVectorSDNode *BV =
24178           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24179     // Bail out if the vector isn't a constant.
24180     if (!BV->isConstant())
24181       return SDValue();
24182
24183     // Everything checks out. Build up the new and improved node.
24184     SDLoc DL(N);
24185     EVT IntVT = BV->getValueType(0);
24186     // Create a new constant of the appropriate type for the transformed
24187     // DAG.
24188     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24189     // The AND node needs bitcasts to/from an integer vector type around it.
24190     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24191     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24192                                  N->getOperand(0)->getOperand(0), MaskConst);
24193     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24194     return Res;
24195   }
24196
24197   return SDValue();
24198 }
24199
24200 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24201                                         const X86Subtarget *Subtarget) {
24202   // First try to optimize away the conversion entirely when it's
24203   // conditionally from a constant. Vectors only.
24204   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24205   if (Res != SDValue())
24206     return Res;
24207
24208   // Now move on to more general possibilities.
24209   SDValue Op0 = N->getOperand(0);
24210   EVT InVT = Op0->getValueType(0);
24211
24212   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24213   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24214     SDLoc dl(N);
24215     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24216     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24217     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24218   }
24219
24220   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24221   // a 32-bit target where SSE doesn't support i64->FP operations.
24222   if (Op0.getOpcode() == ISD::LOAD) {
24223     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24224     EVT VT = Ld->getValueType(0);
24225
24226     // This transformation is not supported if the result type is f16
24227     if (N->getValueType(0) == MVT::f16)
24228       return SDValue();
24229
24230     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24231         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24232         !Subtarget->is64Bit() && VT == MVT::i64) {
24233       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24234           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24235       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24236       return FILDChain;
24237     }
24238   }
24239   return SDValue();
24240 }
24241
24242 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24243 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24244                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24245   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24246   // the result is either zero or one (depending on the input carry bit).
24247   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24248   if (X86::isZeroNode(N->getOperand(0)) &&
24249       X86::isZeroNode(N->getOperand(1)) &&
24250       // We don't have a good way to replace an EFLAGS use, so only do this when
24251       // dead right now.
24252       SDValue(N, 1).use_empty()) {
24253     SDLoc DL(N);
24254     EVT VT = N->getValueType(0);
24255     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24256     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24257                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24258                                            DAG.getConstant(X86::COND_B, DL,
24259                                                            MVT::i8),
24260                                            N->getOperand(2)),
24261                                DAG.getConstant(1, DL, VT));
24262     return DCI.CombineTo(N, Res1, CarryOut);
24263   }
24264
24265   return SDValue();
24266 }
24267
24268 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24269 //      (add Y, (setne X, 0)) -> sbb -1, Y
24270 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24271 //      (sub (setne X, 0), Y) -> adc -1, Y
24272 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24273   SDLoc DL(N);
24274
24275   // Look through ZExts.
24276   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24277   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24278     return SDValue();
24279
24280   SDValue SetCC = Ext.getOperand(0);
24281   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24282     return SDValue();
24283
24284   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24285   if (CC != X86::COND_E && CC != X86::COND_NE)
24286     return SDValue();
24287
24288   SDValue Cmp = SetCC.getOperand(1);
24289   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24290       !X86::isZeroNode(Cmp.getOperand(1)) ||
24291       !Cmp.getOperand(0).getValueType().isInteger())
24292     return SDValue();
24293
24294   SDValue CmpOp0 = Cmp.getOperand(0);
24295   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24296                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24297
24298   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24299   if (CC == X86::COND_NE)
24300     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24301                        DL, OtherVal.getValueType(), OtherVal,
24302                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24303                        NewCmp);
24304   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24305                      DL, OtherVal.getValueType(), OtherVal,
24306                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24307 }
24308
24309 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24310 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24311                                  const X86Subtarget *Subtarget) {
24312   EVT VT = N->getValueType(0);
24313   SDValue Op0 = N->getOperand(0);
24314   SDValue Op1 = N->getOperand(1);
24315
24316   // Try to synthesize horizontal adds from adds of shuffles.
24317   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24318        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24319       isHorizontalBinOp(Op0, Op1, true))
24320     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24321
24322   return OptimizeConditionalInDecrement(N, DAG);
24323 }
24324
24325 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24326                                  const X86Subtarget *Subtarget) {
24327   SDValue Op0 = N->getOperand(0);
24328   SDValue Op1 = N->getOperand(1);
24329
24330   // X86 can't encode an immediate LHS of a sub. See if we can push the
24331   // negation into a preceding instruction.
24332   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24333     // If the RHS of the sub is a XOR with one use and a constant, invert the
24334     // immediate. Then add one to the LHS of the sub so we can turn
24335     // X-Y -> X+~Y+1, saving one register.
24336     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24337         isa<ConstantSDNode>(Op1.getOperand(1))) {
24338       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24339       EVT VT = Op0.getValueType();
24340       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24341                                    Op1.getOperand(0),
24342                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24343       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24344                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24345     }
24346   }
24347
24348   // Try to synthesize horizontal adds from adds of shuffles.
24349   EVT VT = N->getValueType(0);
24350   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24351        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24352       isHorizontalBinOp(Op0, Op1, true))
24353     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24354
24355   return OptimizeConditionalInDecrement(N, DAG);
24356 }
24357
24358 /// performVZEXTCombine - Performs build vector combines
24359 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24360                                    TargetLowering::DAGCombinerInfo &DCI,
24361                                    const X86Subtarget *Subtarget) {
24362   SDLoc DL(N);
24363   MVT VT = N->getSimpleValueType(0);
24364   SDValue Op = N->getOperand(0);
24365   MVT OpVT = Op.getSimpleValueType();
24366   MVT OpEltVT = OpVT.getVectorElementType();
24367   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24368
24369   // (vzext (bitcast (vzext (x)) -> (vzext x)
24370   SDValue V = Op;
24371   while (V.getOpcode() == ISD::BITCAST)
24372     V = V.getOperand(0);
24373
24374   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24375     MVT InnerVT = V.getSimpleValueType();
24376     MVT InnerEltVT = InnerVT.getVectorElementType();
24377
24378     // If the element sizes match exactly, we can just do one larger vzext. This
24379     // is always an exact type match as vzext operates on integer types.
24380     if (OpEltVT == InnerEltVT) {
24381       assert(OpVT == InnerVT && "Types must match for vzext!");
24382       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24383     }
24384
24385     // The only other way we can combine them is if only a single element of the
24386     // inner vzext is used in the input to the outer vzext.
24387     if (InnerEltVT.getSizeInBits() < InputBits)
24388       return SDValue();
24389
24390     // In this case, the inner vzext is completely dead because we're going to
24391     // only look at bits inside of the low element. Just do the outer vzext on
24392     // a bitcast of the input to the inner.
24393     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24394                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24395   }
24396
24397   // Check if we can bypass extracting and re-inserting an element of an input
24398   // vector. Essentialy:
24399   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24400   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24401       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24402       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24403     SDValue ExtractedV = V.getOperand(0);
24404     SDValue OrigV = ExtractedV.getOperand(0);
24405     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24406       if (ExtractIdx->getZExtValue() == 0) {
24407         MVT OrigVT = OrigV.getSimpleValueType();
24408         // Extract a subvector if necessary...
24409         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24410           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24411           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24412                                     OrigVT.getVectorNumElements() / Ratio);
24413           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24414                               DAG.getIntPtrConstant(0, DL));
24415         }
24416         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24417         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24418       }
24419   }
24420
24421   return SDValue();
24422 }
24423
24424 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24425                                              DAGCombinerInfo &DCI) const {
24426   SelectionDAG &DAG = DCI.DAG;
24427   switch (N->getOpcode()) {
24428   default: break;
24429   case ISD::EXTRACT_VECTOR_ELT:
24430     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24431   case ISD::VSELECT:
24432   case ISD::SELECT:
24433   case X86ISD::SHRUNKBLEND:
24434     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24435   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24436   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24437   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24438   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24439   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24440   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24441   case ISD::SHL:
24442   case ISD::SRA:
24443   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24444   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24445   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24446   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24447   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24448   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24449   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24450   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24451   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24452   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24453   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24454   case X86ISD::FXOR:
24455   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24456   case X86ISD::FMIN:
24457   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24458   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24459   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24460   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24461   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24462   case ISD::ANY_EXTEND:
24463   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24464   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24465   case ISD::SIGN_EXTEND_INREG:
24466     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24467   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24468   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24469   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24470   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24471   case X86ISD::SHUFP:       // Handle all target specific shuffles
24472   case X86ISD::PALIGNR:
24473   case X86ISD::UNPCKH:
24474   case X86ISD::UNPCKL:
24475   case X86ISD::MOVHLPS:
24476   case X86ISD::MOVLHPS:
24477   case X86ISD::PSHUFB:
24478   case X86ISD::PSHUFD:
24479   case X86ISD::PSHUFHW:
24480   case X86ISD::PSHUFLW:
24481   case X86ISD::MOVSS:
24482   case X86ISD::MOVSD:
24483   case X86ISD::VPERMILPI:
24484   case X86ISD::VPERM2X128:
24485   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24486   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24487   case ISD::INTRINSIC_WO_CHAIN:
24488     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24489   case X86ISD::INSERTPS: {
24490     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24491       return PerformINSERTPSCombine(N, DAG, Subtarget);
24492     break;
24493   }
24494   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24495   }
24496
24497   return SDValue();
24498 }
24499
24500 /// isTypeDesirableForOp - Return true if the target has native support for
24501 /// the specified value type and it is 'desirable' to use the type for the
24502 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24503 /// instruction encodings are longer and some i16 instructions are slow.
24504 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24505   if (!isTypeLegal(VT))
24506     return false;
24507   if (VT != MVT::i16)
24508     return true;
24509
24510   switch (Opc) {
24511   default:
24512     return true;
24513   case ISD::LOAD:
24514   case ISD::SIGN_EXTEND:
24515   case ISD::ZERO_EXTEND:
24516   case ISD::ANY_EXTEND:
24517   case ISD::SHL:
24518   case ISD::SRL:
24519   case ISD::SUB:
24520   case ISD::ADD:
24521   case ISD::MUL:
24522   case ISD::AND:
24523   case ISD::OR:
24524   case ISD::XOR:
24525     return false;
24526   }
24527 }
24528
24529 /// IsDesirableToPromoteOp - This method query the target whether it is
24530 /// beneficial for dag combiner to promote the specified node. If true, it
24531 /// should return the desired promotion type by reference.
24532 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24533   EVT VT = Op.getValueType();
24534   if (VT != MVT::i16)
24535     return false;
24536
24537   bool Promote = false;
24538   bool Commute = false;
24539   switch (Op.getOpcode()) {
24540   default: break;
24541   case ISD::LOAD: {
24542     LoadSDNode *LD = cast<LoadSDNode>(Op);
24543     // If the non-extending load has a single use and it's not live out, then it
24544     // might be folded.
24545     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24546                                                      Op.hasOneUse()*/) {
24547       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24548              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24549         // The only case where we'd want to promote LOAD (rather then it being
24550         // promoted as an operand is when it's only use is liveout.
24551         if (UI->getOpcode() != ISD::CopyToReg)
24552           return false;
24553       }
24554     }
24555     Promote = true;
24556     break;
24557   }
24558   case ISD::SIGN_EXTEND:
24559   case ISD::ZERO_EXTEND:
24560   case ISD::ANY_EXTEND:
24561     Promote = true;
24562     break;
24563   case ISD::SHL:
24564   case ISD::SRL: {
24565     SDValue N0 = Op.getOperand(0);
24566     // Look out for (store (shl (load), x)).
24567     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24568       return false;
24569     Promote = true;
24570     break;
24571   }
24572   case ISD::ADD:
24573   case ISD::MUL:
24574   case ISD::AND:
24575   case ISD::OR:
24576   case ISD::XOR:
24577     Commute = true;
24578     // fallthrough
24579   case ISD::SUB: {
24580     SDValue N0 = Op.getOperand(0);
24581     SDValue N1 = Op.getOperand(1);
24582     if (!Commute && MayFoldLoad(N1))
24583       return false;
24584     // Avoid disabling potential load folding opportunities.
24585     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24586       return false;
24587     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24588       return false;
24589     Promote = true;
24590   }
24591   }
24592
24593   PVT = MVT::i32;
24594   return Promote;
24595 }
24596
24597 //===----------------------------------------------------------------------===//
24598 //                           X86 Inline Assembly Support
24599 //===----------------------------------------------------------------------===//
24600
24601 // Helper to match a string separated by whitespace.
24602 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24603   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24604
24605   for (StringRef Piece : Pieces) {
24606     if (!S.startswith(Piece)) // Check if the piece matches.
24607       return false;
24608
24609     S = S.substr(Piece.size());
24610     StringRef::size_type Pos = S.find_first_not_of(" \t");
24611     if (Pos == 0) // We matched a prefix.
24612       return false;
24613
24614     S = S.substr(Pos);
24615   }
24616
24617   return S.empty();
24618 }
24619
24620 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24621
24622   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24623     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24624         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24625         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24626
24627       if (AsmPieces.size() == 3)
24628         return true;
24629       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24630         return true;
24631     }
24632   }
24633   return false;
24634 }
24635
24636 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24637   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24638
24639   std::string AsmStr = IA->getAsmString();
24640
24641   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24642   if (!Ty || Ty->getBitWidth() % 16 != 0)
24643     return false;
24644
24645   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24646   SmallVector<StringRef, 4> AsmPieces;
24647   SplitString(AsmStr, AsmPieces, ";\n");
24648
24649   switch (AsmPieces.size()) {
24650   default: return false;
24651   case 1:
24652     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24653     // we will turn this bswap into something that will be lowered to logical
24654     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24655     // lower so don't worry about this.
24656     // bswap $0
24657     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24658         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24659         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24660         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24661         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24662         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24663       // No need to check constraints, nothing other than the equivalent of
24664       // "=r,0" would be valid here.
24665       return IntrinsicLowering::LowerToByteSwap(CI);
24666     }
24667
24668     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24669     if (CI->getType()->isIntegerTy(16) &&
24670         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24671         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24672          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24673       AsmPieces.clear();
24674       const std::string &ConstraintsStr = IA->getConstraintString();
24675       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24676       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24677       if (clobbersFlagRegisters(AsmPieces))
24678         return IntrinsicLowering::LowerToByteSwap(CI);
24679     }
24680     break;
24681   case 3:
24682     if (CI->getType()->isIntegerTy(32) &&
24683         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24684         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24685         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24686         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24687       AsmPieces.clear();
24688       const std::string &ConstraintsStr = IA->getConstraintString();
24689       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24690       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24691       if (clobbersFlagRegisters(AsmPieces))
24692         return IntrinsicLowering::LowerToByteSwap(CI);
24693     }
24694
24695     if (CI->getType()->isIntegerTy(64)) {
24696       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24697       if (Constraints.size() >= 2 &&
24698           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24699           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24700         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24701         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24702             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24703             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24704           return IntrinsicLowering::LowerToByteSwap(CI);
24705       }
24706     }
24707     break;
24708   }
24709   return false;
24710 }
24711
24712 /// getConstraintType - Given a constraint letter, return the type of
24713 /// constraint it is for this target.
24714 X86TargetLowering::ConstraintType
24715 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24716   if (Constraint.size() == 1) {
24717     switch (Constraint[0]) {
24718     case 'R':
24719     case 'q':
24720     case 'Q':
24721     case 'f':
24722     case 't':
24723     case 'u':
24724     case 'y':
24725     case 'x':
24726     case 'Y':
24727     case 'l':
24728       return C_RegisterClass;
24729     case 'a':
24730     case 'b':
24731     case 'c':
24732     case 'd':
24733     case 'S':
24734     case 'D':
24735     case 'A':
24736       return C_Register;
24737     case 'I':
24738     case 'J':
24739     case 'K':
24740     case 'L':
24741     case 'M':
24742     case 'N':
24743     case 'G':
24744     case 'C':
24745     case 'e':
24746     case 'Z':
24747       return C_Other;
24748     default:
24749       break;
24750     }
24751   }
24752   return TargetLowering::getConstraintType(Constraint);
24753 }
24754
24755 /// Examine constraint type and operand type and determine a weight value.
24756 /// This object must already have been set up with the operand type
24757 /// and the current alternative constraint selected.
24758 TargetLowering::ConstraintWeight
24759   X86TargetLowering::getSingleConstraintMatchWeight(
24760     AsmOperandInfo &info, const char *constraint) const {
24761   ConstraintWeight weight = CW_Invalid;
24762   Value *CallOperandVal = info.CallOperandVal;
24763     // If we don't have a value, we can't do a match,
24764     // but allow it at the lowest weight.
24765   if (!CallOperandVal)
24766     return CW_Default;
24767   Type *type = CallOperandVal->getType();
24768   // Look at the constraint type.
24769   switch (*constraint) {
24770   default:
24771     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24772   case 'R':
24773   case 'q':
24774   case 'Q':
24775   case 'a':
24776   case 'b':
24777   case 'c':
24778   case 'd':
24779   case 'S':
24780   case 'D':
24781   case 'A':
24782     if (CallOperandVal->getType()->isIntegerTy())
24783       weight = CW_SpecificReg;
24784     break;
24785   case 'f':
24786   case 't':
24787   case 'u':
24788     if (type->isFloatingPointTy())
24789       weight = CW_SpecificReg;
24790     break;
24791   case 'y':
24792     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24793       weight = CW_SpecificReg;
24794     break;
24795   case 'x':
24796   case 'Y':
24797     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24798         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24799       weight = CW_Register;
24800     break;
24801   case 'I':
24802     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24803       if (C->getZExtValue() <= 31)
24804         weight = CW_Constant;
24805     }
24806     break;
24807   case 'J':
24808     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24809       if (C->getZExtValue() <= 63)
24810         weight = CW_Constant;
24811     }
24812     break;
24813   case 'K':
24814     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24815       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24816         weight = CW_Constant;
24817     }
24818     break;
24819   case 'L':
24820     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24821       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24822         weight = CW_Constant;
24823     }
24824     break;
24825   case 'M':
24826     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24827       if (C->getZExtValue() <= 3)
24828         weight = CW_Constant;
24829     }
24830     break;
24831   case 'N':
24832     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24833       if (C->getZExtValue() <= 0xff)
24834         weight = CW_Constant;
24835     }
24836     break;
24837   case 'G':
24838   case 'C':
24839     if (isa<ConstantFP>(CallOperandVal)) {
24840       weight = CW_Constant;
24841     }
24842     break;
24843   case 'e':
24844     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24845       if ((C->getSExtValue() >= -0x80000000LL) &&
24846           (C->getSExtValue() <= 0x7fffffffLL))
24847         weight = CW_Constant;
24848     }
24849     break;
24850   case 'Z':
24851     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24852       if (C->getZExtValue() <= 0xffffffff)
24853         weight = CW_Constant;
24854     }
24855     break;
24856   }
24857   return weight;
24858 }
24859
24860 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24861 /// with another that has more specific requirements based on the type of the
24862 /// corresponding operand.
24863 const char *X86TargetLowering::
24864 LowerXConstraint(EVT ConstraintVT) const {
24865   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24866   // 'f' like normal targets.
24867   if (ConstraintVT.isFloatingPoint()) {
24868     if (Subtarget->hasSSE2())
24869       return "Y";
24870     if (Subtarget->hasSSE1())
24871       return "x";
24872   }
24873
24874   return TargetLowering::LowerXConstraint(ConstraintVT);
24875 }
24876
24877 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24878 /// vector.  If it is invalid, don't add anything to Ops.
24879 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24880                                                      std::string &Constraint,
24881                                                      std::vector<SDValue>&Ops,
24882                                                      SelectionDAG &DAG) const {
24883   SDValue Result;
24884
24885   // Only support length 1 constraints for now.
24886   if (Constraint.length() > 1) return;
24887
24888   char ConstraintLetter = Constraint[0];
24889   switch (ConstraintLetter) {
24890   default: break;
24891   case 'I':
24892     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24893       if (C->getZExtValue() <= 31) {
24894         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24895                                        Op.getValueType());
24896         break;
24897       }
24898     }
24899     return;
24900   case 'J':
24901     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24902       if (C->getZExtValue() <= 63) {
24903         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24904                                        Op.getValueType());
24905         break;
24906       }
24907     }
24908     return;
24909   case 'K':
24910     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24911       if (isInt<8>(C->getSExtValue())) {
24912         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24913                                        Op.getValueType());
24914         break;
24915       }
24916     }
24917     return;
24918   case 'L':
24919     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24920       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24921           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24922         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24923                                        Op.getValueType());
24924         break;
24925       }
24926     }
24927     return;
24928   case 'M':
24929     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24930       if (C->getZExtValue() <= 3) {
24931         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24932                                        Op.getValueType());
24933         break;
24934       }
24935     }
24936     return;
24937   case 'N':
24938     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24939       if (C->getZExtValue() <= 255) {
24940         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24941                                        Op.getValueType());
24942         break;
24943       }
24944     }
24945     return;
24946   case 'O':
24947     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24948       if (C->getZExtValue() <= 127) {
24949         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24950                                        Op.getValueType());
24951         break;
24952       }
24953     }
24954     return;
24955   case 'e': {
24956     // 32-bit signed value
24957     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24958       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24959                                            C->getSExtValue())) {
24960         // Widen to 64 bits here to get it sign extended.
24961         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24962         break;
24963       }
24964     // FIXME gcc accepts some relocatable values here too, but only in certain
24965     // memory models; it's complicated.
24966     }
24967     return;
24968   }
24969   case 'Z': {
24970     // 32-bit unsigned value
24971     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24972       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24973                                            C->getZExtValue())) {
24974         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24975                                        Op.getValueType());
24976         break;
24977       }
24978     }
24979     // FIXME gcc accepts some relocatable values here too, but only in certain
24980     // memory models; it's complicated.
24981     return;
24982   }
24983   case 'i': {
24984     // Literal immediates are always ok.
24985     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24986       // Widen to 64 bits here to get it sign extended.
24987       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24988       break;
24989     }
24990
24991     // In any sort of PIC mode addresses need to be computed at runtime by
24992     // adding in a register or some sort of table lookup.  These can't
24993     // be used as immediates.
24994     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24995       return;
24996
24997     // If we are in non-pic codegen mode, we allow the address of a global (with
24998     // an optional displacement) to be used with 'i'.
24999     GlobalAddressSDNode *GA = nullptr;
25000     int64_t Offset = 0;
25001
25002     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25003     while (1) {
25004       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25005         Offset += GA->getOffset();
25006         break;
25007       } else if (Op.getOpcode() == ISD::ADD) {
25008         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25009           Offset += C->getZExtValue();
25010           Op = Op.getOperand(0);
25011           continue;
25012         }
25013       } else if (Op.getOpcode() == ISD::SUB) {
25014         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25015           Offset += -C->getZExtValue();
25016           Op = Op.getOperand(0);
25017           continue;
25018         }
25019       }
25020
25021       // Otherwise, this isn't something we can handle, reject it.
25022       return;
25023     }
25024
25025     const GlobalValue *GV = GA->getGlobal();
25026     // If we require an extra load to get this address, as in PIC mode, we
25027     // can't accept it.
25028     if (isGlobalStubReference(
25029             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25030       return;
25031
25032     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25033                                         GA->getValueType(0), Offset);
25034     break;
25035   }
25036   }
25037
25038   if (Result.getNode()) {
25039     Ops.push_back(Result);
25040     return;
25041   }
25042   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25043 }
25044
25045 std::pair<unsigned, const TargetRegisterClass *>
25046 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25047                                                 const std::string &Constraint,
25048                                                 MVT VT) const {
25049   // First, see if this is a constraint that directly corresponds to an LLVM
25050   // register class.
25051   if (Constraint.size() == 1) {
25052     // GCC Constraint Letters
25053     switch (Constraint[0]) {
25054     default: break;
25055       // TODO: Slight differences here in allocation order and leaving
25056       // RIP in the class. Do they matter any more here than they do
25057       // in the normal allocation?
25058     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25059       if (Subtarget->is64Bit()) {
25060         if (VT == MVT::i32 || VT == MVT::f32)
25061           return std::make_pair(0U, &X86::GR32RegClass);
25062         if (VT == MVT::i16)
25063           return std::make_pair(0U, &X86::GR16RegClass);
25064         if (VT == MVT::i8 || VT == MVT::i1)
25065           return std::make_pair(0U, &X86::GR8RegClass);
25066         if (VT == MVT::i64 || VT == MVT::f64)
25067           return std::make_pair(0U, &X86::GR64RegClass);
25068         break;
25069       }
25070       // 32-bit fallthrough
25071     case 'Q':   // Q_REGS
25072       if (VT == MVT::i32 || VT == MVT::f32)
25073         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25074       if (VT == MVT::i16)
25075         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25076       if (VT == MVT::i8 || VT == MVT::i1)
25077         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25078       if (VT == MVT::i64)
25079         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25080       break;
25081     case 'r':   // GENERAL_REGS
25082     case 'l':   // INDEX_REGS
25083       if (VT == MVT::i8 || VT == MVT::i1)
25084         return std::make_pair(0U, &X86::GR8RegClass);
25085       if (VT == MVT::i16)
25086         return std::make_pair(0U, &X86::GR16RegClass);
25087       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25088         return std::make_pair(0U, &X86::GR32RegClass);
25089       return std::make_pair(0U, &X86::GR64RegClass);
25090     case 'R':   // LEGACY_REGS
25091       if (VT == MVT::i8 || VT == MVT::i1)
25092         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25093       if (VT == MVT::i16)
25094         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25095       if (VT == MVT::i32 || !Subtarget->is64Bit())
25096         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25097       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25098     case 'f':  // FP Stack registers.
25099       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25100       // value to the correct fpstack register class.
25101       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25102         return std::make_pair(0U, &X86::RFP32RegClass);
25103       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25104         return std::make_pair(0U, &X86::RFP64RegClass);
25105       return std::make_pair(0U, &X86::RFP80RegClass);
25106     case 'y':   // MMX_REGS if MMX allowed.
25107       if (!Subtarget->hasMMX()) break;
25108       return std::make_pair(0U, &X86::VR64RegClass);
25109     case 'Y':   // SSE_REGS if SSE2 allowed
25110       if (!Subtarget->hasSSE2()) break;
25111       // FALL THROUGH.
25112     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25113       if (!Subtarget->hasSSE1()) break;
25114
25115       switch (VT.SimpleTy) {
25116       default: break;
25117       // Scalar SSE types.
25118       case MVT::f32:
25119       case MVT::i32:
25120         return std::make_pair(0U, &X86::FR32RegClass);
25121       case MVT::f64:
25122       case MVT::i64:
25123         return std::make_pair(0U, &X86::FR64RegClass);
25124       // Vector types.
25125       case MVT::v16i8:
25126       case MVT::v8i16:
25127       case MVT::v4i32:
25128       case MVT::v2i64:
25129       case MVT::v4f32:
25130       case MVT::v2f64:
25131         return std::make_pair(0U, &X86::VR128RegClass);
25132       // AVX types.
25133       case MVT::v32i8:
25134       case MVT::v16i16:
25135       case MVT::v8i32:
25136       case MVT::v4i64:
25137       case MVT::v8f32:
25138       case MVT::v4f64:
25139         return std::make_pair(0U, &X86::VR256RegClass);
25140       case MVT::v8f64:
25141       case MVT::v16f32:
25142       case MVT::v16i32:
25143       case MVT::v8i64:
25144         return std::make_pair(0U, &X86::VR512RegClass);
25145       }
25146       break;
25147     }
25148   }
25149
25150   // Use the default implementation in TargetLowering to convert the register
25151   // constraint into a member of a register class.
25152   std::pair<unsigned, const TargetRegisterClass*> Res;
25153   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25154
25155   // Not found as a standard register?
25156   if (!Res.second) {
25157     // Map st(0) -> st(7) -> ST0
25158     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25159         tolower(Constraint[1]) == 's' &&
25160         tolower(Constraint[2]) == 't' &&
25161         Constraint[3] == '(' &&
25162         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25163         Constraint[5] == ')' &&
25164         Constraint[6] == '}') {
25165
25166       Res.first = X86::FP0+Constraint[4]-'0';
25167       Res.second = &X86::RFP80RegClass;
25168       return Res;
25169     }
25170
25171     // GCC allows "st(0)" to be called just plain "st".
25172     if (StringRef("{st}").equals_lower(Constraint)) {
25173       Res.first = X86::FP0;
25174       Res.second = &X86::RFP80RegClass;
25175       return Res;
25176     }
25177
25178     // flags -> EFLAGS
25179     if (StringRef("{flags}").equals_lower(Constraint)) {
25180       Res.first = X86::EFLAGS;
25181       Res.second = &X86::CCRRegClass;
25182       return Res;
25183     }
25184
25185     // 'A' means EAX + EDX.
25186     if (Constraint == "A") {
25187       Res.first = X86::EAX;
25188       Res.second = &X86::GR32_ADRegClass;
25189       return Res;
25190     }
25191     return Res;
25192   }
25193
25194   // Otherwise, check to see if this is a register class of the wrong value
25195   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25196   // turn into {ax},{dx}.
25197   if (Res.second->hasType(VT))
25198     return Res;   // Correct type already, nothing to do.
25199
25200   // All of the single-register GCC register classes map their values onto
25201   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25202   // really want an 8-bit or 32-bit register, map to the appropriate register
25203   // class and return the appropriate register.
25204   if (Res.second == &X86::GR16RegClass) {
25205     if (VT == MVT::i8 || VT == MVT::i1) {
25206       unsigned DestReg = 0;
25207       switch (Res.first) {
25208       default: break;
25209       case X86::AX: DestReg = X86::AL; break;
25210       case X86::DX: DestReg = X86::DL; break;
25211       case X86::CX: DestReg = X86::CL; break;
25212       case X86::BX: DestReg = X86::BL; break;
25213       }
25214       if (DestReg) {
25215         Res.first = DestReg;
25216         Res.second = &X86::GR8RegClass;
25217       }
25218     } else if (VT == MVT::i32 || VT == MVT::f32) {
25219       unsigned DestReg = 0;
25220       switch (Res.first) {
25221       default: break;
25222       case X86::AX: DestReg = X86::EAX; break;
25223       case X86::DX: DestReg = X86::EDX; break;
25224       case X86::CX: DestReg = X86::ECX; break;
25225       case X86::BX: DestReg = X86::EBX; break;
25226       case X86::SI: DestReg = X86::ESI; break;
25227       case X86::DI: DestReg = X86::EDI; break;
25228       case X86::BP: DestReg = X86::EBP; break;
25229       case X86::SP: DestReg = X86::ESP; break;
25230       }
25231       if (DestReg) {
25232         Res.first = DestReg;
25233         Res.second = &X86::GR32RegClass;
25234       }
25235     } else if (VT == MVT::i64 || VT == MVT::f64) {
25236       unsigned DestReg = 0;
25237       switch (Res.first) {
25238       default: break;
25239       case X86::AX: DestReg = X86::RAX; break;
25240       case X86::DX: DestReg = X86::RDX; break;
25241       case X86::CX: DestReg = X86::RCX; break;
25242       case X86::BX: DestReg = X86::RBX; break;
25243       case X86::SI: DestReg = X86::RSI; break;
25244       case X86::DI: DestReg = X86::RDI; break;
25245       case X86::BP: DestReg = X86::RBP; break;
25246       case X86::SP: DestReg = X86::RSP; break;
25247       }
25248       if (DestReg) {
25249         Res.first = DestReg;
25250         Res.second = &X86::GR64RegClass;
25251       }
25252     }
25253   } else if (Res.second == &X86::FR32RegClass ||
25254              Res.second == &X86::FR64RegClass ||
25255              Res.second == &X86::VR128RegClass ||
25256              Res.second == &X86::VR256RegClass ||
25257              Res.second == &X86::FR32XRegClass ||
25258              Res.second == &X86::FR64XRegClass ||
25259              Res.second == &X86::VR128XRegClass ||
25260              Res.second == &X86::VR256XRegClass ||
25261              Res.second == &X86::VR512RegClass) {
25262     // Handle references to XMM physical registers that got mapped into the
25263     // wrong class.  This can happen with constraints like {xmm0} where the
25264     // target independent register mapper will just pick the first match it can
25265     // find, ignoring the required type.
25266
25267     if (VT == MVT::f32 || VT == MVT::i32)
25268       Res.second = &X86::FR32RegClass;
25269     else if (VT == MVT::f64 || VT == MVT::i64)
25270       Res.second = &X86::FR64RegClass;
25271     else if (X86::VR128RegClass.hasType(VT))
25272       Res.second = &X86::VR128RegClass;
25273     else if (X86::VR256RegClass.hasType(VT))
25274       Res.second = &X86::VR256RegClass;
25275     else if (X86::VR512RegClass.hasType(VT))
25276       Res.second = &X86::VR512RegClass;
25277   }
25278
25279   return Res;
25280 }
25281
25282 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25283                                             Type *Ty) const {
25284   // Scaling factors are not free at all.
25285   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25286   // will take 2 allocations in the out of order engine instead of 1
25287   // for plain addressing mode, i.e. inst (reg1).
25288   // E.g.,
25289   // vaddps (%rsi,%drx), %ymm0, %ymm1
25290   // Requires two allocations (one for the load, one for the computation)
25291   // whereas:
25292   // vaddps (%rsi), %ymm0, %ymm1
25293   // Requires just 1 allocation, i.e., freeing allocations for other operations
25294   // and having less micro operations to execute.
25295   //
25296   // For some X86 architectures, this is even worse because for instance for
25297   // stores, the complex addressing mode forces the instruction to use the
25298   // "load" ports instead of the dedicated "store" port.
25299   // E.g., on Haswell:
25300   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25301   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25302   if (isLegalAddressingMode(AM, Ty))
25303     // Scale represents reg2 * scale, thus account for 1
25304     // as soon as we use a second register.
25305     return AM.Scale != 0;
25306   return -1;
25307 }
25308
25309 bool X86TargetLowering::isTargetFTOL() const {
25310   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25311 }