75e03a50f39a72646c2e03f319f10720743aa1ec
[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     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1265     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1266     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1267     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1268     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1269     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1270     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1271     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1272     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1273     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1274     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1275     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1276     
1277     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1278     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1279     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1280     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1281     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1282     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1283     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1284     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1285     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1286     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1287     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1288     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1289     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1290
1291     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1292     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1293     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1294     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1295     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1296     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1297
1298     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1299     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1300     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1301     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1302     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1303     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1304     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1305     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1306
1307     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1308     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1309     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1310     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1311     if (Subtarget->is64Bit()) {
1312       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1313       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1314       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1315       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1316     }
1317     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1318     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1319     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1320     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1321     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1322     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1323     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1324     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1325     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1326     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1328     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1329     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1330     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1331     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1332     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1333
1334     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1335     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1336     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1337     if (Subtarget->hasDQI()) {
1338       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1339       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1340     }
1341     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1342     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1343     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1344     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1345     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1346     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1347     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1348     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1349     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1350     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1351     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1352     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1353     if (Subtarget->hasDQI()) {
1354       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1355       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1356     }
1357     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1358     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1359     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1360     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1361     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1362     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1363     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1364     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1365     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1366     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1367
1368     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1369     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1370     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1371     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1372     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1373
1374     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1375     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1376
1377     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1378
1379     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1380     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1381     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1382     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1383     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1384     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1385     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1386     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1387     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1388     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1389     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1390
1391     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1392     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1393
1394     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1395     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1396
1397     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1398
1399     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1400     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1401
1402     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1403     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1404
1405     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1406     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1407
1408     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1409     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1410     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1411     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1412     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1413     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1414
1415     if (Subtarget->hasCDI()) {
1416       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1417       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1418     }
1419     if (Subtarget->hasDQI()) {
1420       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1421       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1422       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1423     }
1424     // Custom lower several nodes.
1425     for (MVT VT : MVT::vector_valuetypes()) {
1426       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1427       if (EltSize == 1) {
1428         setOperationAction(ISD::AND, VT, Legal);
1429         setOperationAction(ISD::OR,  VT, Legal);
1430         setOperationAction(ISD::XOR,  VT, Legal);
1431       }
1432       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1433         setOperationAction(ISD::MGATHER,  VT, Custom);
1434         setOperationAction(ISD::MSCATTER, VT, Custom);
1435       }
1436       // Extract subvector is special because the value type
1437       // (result) is 256/128-bit but the source is 512-bit wide.
1438       if (VT.is128BitVector() || VT.is256BitVector()) {
1439         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1440       }
1441       if (VT.getVectorElementType() == MVT::i1)
1442         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1443
1444       // Do not attempt to custom lower other non-512-bit vectors
1445       if (!VT.is512BitVector())
1446         continue;
1447
1448       if (EltSize >= 32) {
1449         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1450         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1451         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1452         setOperationAction(ISD::VSELECT,             VT, Legal);
1453         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1454         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1455         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1456         setOperationAction(ISD::MLOAD,               VT, Legal);
1457         setOperationAction(ISD::MSTORE,              VT, Legal);
1458       }
1459     }
1460     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1461       MVT VT = (MVT::SimpleValueType)i;
1462
1463       // Do not attempt to promote non-512-bit vectors.
1464       if (!VT.is512BitVector())
1465         continue;
1466
1467       setOperationAction(ISD::SELECT, VT, Promote);
1468       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1469     }
1470   }// has  AVX-512
1471
1472   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1473     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1474     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1475
1476     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1477     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1478
1479     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1480     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1481     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1482     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1483     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1484     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1485     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1486     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1487     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1488     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1489     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1490     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1491     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1492     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1493     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1494     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1495     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1496     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1497     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1498     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1499     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1500     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1501     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1502     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1503     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1504     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1505     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1506
1507     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1508       const MVT VT = (MVT::SimpleValueType)i;
1509
1510       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1511
1512       // Do not attempt to promote non-512-bit vectors.
1513       if (!VT.is512BitVector())
1514         continue;
1515
1516       if (EltSize < 32) {
1517         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1518         setOperationAction(ISD::VSELECT,             VT, Legal);
1519       }
1520     }
1521   }
1522
1523   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1524     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1525     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1526
1527     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1528     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1529     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1530     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1531     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1532     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1533     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1534     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1535     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1536     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1537
1538     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1539     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1540     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1541     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1542     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1543     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1544     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1545     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1546   }
1547
1548   // We want to custom lower some of our intrinsics.
1549   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1550   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1551   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1552   if (!Subtarget->is64Bit())
1553     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1554
1555   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1556   // handle type legalization for these operations here.
1557   //
1558   // FIXME: We really should do custom legalization for addition and
1559   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1560   // than generic legalization for 64-bit multiplication-with-overflow, though.
1561   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1562     // Add/Sub/Mul with overflow operations are custom lowered.
1563     MVT VT = IntVTs[i];
1564     setOperationAction(ISD::SADDO, VT, Custom);
1565     setOperationAction(ISD::UADDO, VT, Custom);
1566     setOperationAction(ISD::SSUBO, VT, Custom);
1567     setOperationAction(ISD::USUBO, VT, Custom);
1568     setOperationAction(ISD::SMULO, VT, Custom);
1569     setOperationAction(ISD::UMULO, VT, Custom);
1570   }
1571
1572
1573   if (!Subtarget->is64Bit()) {
1574     // These libcalls are not available in 32-bit.
1575     setLibcallName(RTLIB::SHL_I128, nullptr);
1576     setLibcallName(RTLIB::SRL_I128, nullptr);
1577     setLibcallName(RTLIB::SRA_I128, nullptr);
1578   }
1579
1580   // Combine sin / cos into one node or libcall if possible.
1581   if (Subtarget->hasSinCos()) {
1582     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1583     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1584     if (Subtarget->isTargetDarwin()) {
1585       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1586       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1587       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1588       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1589     }
1590   }
1591
1592   if (Subtarget->isTargetWin64()) {
1593     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1595     setOperationAction(ISD::SREM, MVT::i128, Custom);
1596     setOperationAction(ISD::UREM, MVT::i128, Custom);
1597     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1598     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1599   }
1600
1601   // We have target-specific dag combine patterns for the following nodes:
1602   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1603   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1604   setTargetDAGCombine(ISD::BITCAST);
1605   setTargetDAGCombine(ISD::VSELECT);
1606   setTargetDAGCombine(ISD::SELECT);
1607   setTargetDAGCombine(ISD::SHL);
1608   setTargetDAGCombine(ISD::SRA);
1609   setTargetDAGCombine(ISD::SRL);
1610   setTargetDAGCombine(ISD::OR);
1611   setTargetDAGCombine(ISD::AND);
1612   setTargetDAGCombine(ISD::ADD);
1613   setTargetDAGCombine(ISD::FADD);
1614   setTargetDAGCombine(ISD::FSUB);
1615   setTargetDAGCombine(ISD::FMA);
1616   setTargetDAGCombine(ISD::SUB);
1617   setTargetDAGCombine(ISD::LOAD);
1618   setTargetDAGCombine(ISD::MLOAD);
1619   setTargetDAGCombine(ISD::STORE);
1620   setTargetDAGCombine(ISD::MSTORE);
1621   setTargetDAGCombine(ISD::ZERO_EXTEND);
1622   setTargetDAGCombine(ISD::ANY_EXTEND);
1623   setTargetDAGCombine(ISD::SIGN_EXTEND);
1624   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1625   setTargetDAGCombine(ISD::SINT_TO_FP);
1626   setTargetDAGCombine(ISD::SETCC);
1627   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1628   setTargetDAGCombine(ISD::BUILD_VECTOR);
1629   setTargetDAGCombine(ISD::MUL);
1630   setTargetDAGCombine(ISD::XOR);
1631
1632   computeRegisterProperties(Subtarget->getRegisterInfo());
1633
1634   // On Darwin, -Os means optimize for size without hurting performance,
1635   // do not reduce the limit.
1636   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1637   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1638   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1639   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1641   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1642   setPrefLoopAlignment(4); // 2^4 bytes.
1643
1644   // Predictable cmov don't hurt on atom because it's in-order.
1645   PredictableSelectIsExpensive = !Subtarget->isAtom();
1646   EnableExtLdPromotion = true;
1647   setPrefFunctionAlignment(4); // 2^4 bytes.
1648
1649   verifyIntrinsicTables();
1650 }
1651
1652 // This has so far only been implemented for 64-bit MachO.
1653 bool X86TargetLowering::useLoadStackGuardNode() const {
1654   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1655 }
1656
1657 TargetLoweringBase::LegalizeTypeAction
1658 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1659   if (ExperimentalVectorWideningLegalization &&
1660       VT.getVectorNumElements() != 1 &&
1661       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1662     return TypeWidenVector;
1663
1664   return TargetLoweringBase::getPreferredVectorAction(VT);
1665 }
1666
1667 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1668   if (!VT.isVector())
1669     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1670
1671   const unsigned NumElts = VT.getVectorNumElements();
1672   const EVT EltVT = VT.getVectorElementType();
1673   if (VT.is512BitVector()) {
1674     if (Subtarget->hasAVX512())
1675       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1676           EltVT == MVT::f32 || EltVT == MVT::f64)
1677         switch(NumElts) {
1678         case  8: return MVT::v8i1;
1679         case 16: return MVT::v16i1;
1680       }
1681     if (Subtarget->hasBWI())
1682       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1683         switch(NumElts) {
1684         case 32: return MVT::v32i1;
1685         case 64: return MVT::v64i1;
1686       }
1687   }
1688
1689   if (VT.is256BitVector() || VT.is128BitVector()) {
1690     if (Subtarget->hasVLX())
1691       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1692           EltVT == MVT::f32 || EltVT == MVT::f64)
1693         switch(NumElts) {
1694         case 2: return MVT::v2i1;
1695         case 4: return MVT::v4i1;
1696         case 8: return MVT::v8i1;
1697       }
1698     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1699       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1700         switch(NumElts) {
1701         case  8: return MVT::v8i1;
1702         case 16: return MVT::v16i1;
1703         case 32: return MVT::v32i1;
1704       }
1705   }
1706
1707   return VT.changeVectorElementTypeToInteger();
1708 }
1709
1710 /// Helper for getByValTypeAlignment to determine
1711 /// the desired ByVal argument alignment.
1712 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1713   if (MaxAlign == 16)
1714     return;
1715   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1716     if (VTy->getBitWidth() == 128)
1717       MaxAlign = 16;
1718   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1719     unsigned EltAlign = 0;
1720     getMaxByValAlign(ATy->getElementType(), EltAlign);
1721     if (EltAlign > MaxAlign)
1722       MaxAlign = EltAlign;
1723   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1724     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1725       unsigned EltAlign = 0;
1726       getMaxByValAlign(STy->getElementType(i), EltAlign);
1727       if (EltAlign > MaxAlign)
1728         MaxAlign = EltAlign;
1729       if (MaxAlign == 16)
1730         break;
1731     }
1732   }
1733 }
1734
1735 /// Return the desired alignment for ByVal aggregate
1736 /// function arguments in the caller parameter area. For X86, aggregates
1737 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1738 /// are at 4-byte boundaries.
1739 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1740   if (Subtarget->is64Bit()) {
1741     // Max of 8 and alignment of type.
1742     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1743     if (TyAlign > 8)
1744       return TyAlign;
1745     return 8;
1746   }
1747
1748   unsigned Align = 4;
1749   if (Subtarget->hasSSE1())
1750     getMaxByValAlign(Ty, Align);
1751   return Align;
1752 }
1753
1754 /// Returns the target specific optimal type for load
1755 /// and store operations as a result of memset, memcpy, and memmove
1756 /// lowering. If DstAlign is zero that means it's safe to destination
1757 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1758 /// means there isn't a need to check it against alignment requirement,
1759 /// probably because the source does not need to be loaded. If 'IsMemset' is
1760 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1761 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1762 /// source is constant so it does not need to be loaded.
1763 /// It returns EVT::Other if the type should be determined using generic
1764 /// target-independent logic.
1765 EVT
1766 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1767                                        unsigned DstAlign, unsigned SrcAlign,
1768                                        bool IsMemset, bool ZeroMemset,
1769                                        bool MemcpyStrSrc,
1770                                        MachineFunction &MF) const {
1771   const Function *F = MF.getFunction();
1772   if ((!IsMemset || ZeroMemset) &&
1773       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1774     if (Size >= 16 &&
1775         (Subtarget->isUnalignedMemAccessFast() ||
1776          ((DstAlign == 0 || DstAlign >= 16) &&
1777           (SrcAlign == 0 || SrcAlign >= 16)))) {
1778       if (Size >= 32) {
1779         if (Subtarget->hasInt256())
1780           return MVT::v8i32;
1781         if (Subtarget->hasFp256())
1782           return MVT::v8f32;
1783       }
1784       if (Subtarget->hasSSE2())
1785         return MVT::v4i32;
1786       if (Subtarget->hasSSE1())
1787         return MVT::v4f32;
1788     } else if (!MemcpyStrSrc && Size >= 8 &&
1789                !Subtarget->is64Bit() &&
1790                Subtarget->hasSSE2()) {
1791       // Do not use f64 to lower memcpy if source is string constant. It's
1792       // better to use i32 to avoid the loads.
1793       return MVT::f64;
1794     }
1795   }
1796   if (Subtarget->is64Bit() && Size >= 8)
1797     return MVT::i64;
1798   return MVT::i32;
1799 }
1800
1801 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1802   if (VT == MVT::f32)
1803     return X86ScalarSSEf32;
1804   else if (VT == MVT::f64)
1805     return X86ScalarSSEf64;
1806   return true;
1807 }
1808
1809 bool
1810 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1811                                                   unsigned,
1812                                                   unsigned,
1813                                                   bool *Fast) const {
1814   if (Fast)
1815     *Fast = Subtarget->isUnalignedMemAccessFast();
1816   return true;
1817 }
1818
1819 /// Return the entry encoding for a jump table in the
1820 /// current function.  The returned value is a member of the
1821 /// MachineJumpTableInfo::JTEntryKind enum.
1822 unsigned X86TargetLowering::getJumpTableEncoding() const {
1823   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1824   // symbol.
1825   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1826       Subtarget->isPICStyleGOT())
1827     return MachineJumpTableInfo::EK_Custom32;
1828
1829   // Otherwise, use the normal jump table encoding heuristics.
1830   return TargetLowering::getJumpTableEncoding();
1831 }
1832
1833 bool X86TargetLowering::useSoftFloat() const {
1834   return Subtarget->useSoftFloat();
1835 }
1836
1837 const MCExpr *
1838 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1839                                              const MachineBasicBlock *MBB,
1840                                              unsigned uid,MCContext &Ctx) const{
1841   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1842          Subtarget->isPICStyleGOT());
1843   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1844   // entries.
1845   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1846                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1847 }
1848
1849 /// Returns relocation base for the given PIC jumptable.
1850 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1851                                                     SelectionDAG &DAG) const {
1852   if (!Subtarget->is64Bit())
1853     // This doesn't have SDLoc associated with it, but is not really the
1854     // same as a Register.
1855     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1856   return Table;
1857 }
1858
1859 /// This returns the relocation base for the given PIC jumptable,
1860 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1861 const MCExpr *X86TargetLowering::
1862 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1863                              MCContext &Ctx) const {
1864   // X86-64 uses RIP relative addressing based on the jump table label.
1865   if (Subtarget->isPICStyleRIPRel())
1866     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1867
1868   // Otherwise, the reference is relative to the PIC base.
1869   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1870 }
1871
1872 std::pair<const TargetRegisterClass *, uint8_t>
1873 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1874                                            MVT VT) const {
1875   const TargetRegisterClass *RRC = nullptr;
1876   uint8_t Cost = 1;
1877   switch (VT.SimpleTy) {
1878   default:
1879     return TargetLowering::findRepresentativeClass(TRI, VT);
1880   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1881     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1882     break;
1883   case MVT::x86mmx:
1884     RRC = &X86::VR64RegClass;
1885     break;
1886   case MVT::f32: case MVT::f64:
1887   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1888   case MVT::v4f32: case MVT::v2f64:
1889   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1890   case MVT::v4f64:
1891     RRC = &X86::VR128RegClass;
1892     break;
1893   }
1894   return std::make_pair(RRC, Cost);
1895 }
1896
1897 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1898                                                unsigned &Offset) const {
1899   if (!Subtarget->isTargetLinux())
1900     return false;
1901
1902   if (Subtarget->is64Bit()) {
1903     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1904     Offset = 0x28;
1905     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1906       AddressSpace = 256;
1907     else
1908       AddressSpace = 257;
1909   } else {
1910     // %gs:0x14 on i386
1911     Offset = 0x14;
1912     AddressSpace = 256;
1913   }
1914   return true;
1915 }
1916
1917 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1918                                             unsigned DestAS) const {
1919   assert(SrcAS != DestAS && "Expected different address spaces!");
1920
1921   return SrcAS < 256 && DestAS < 256;
1922 }
1923
1924 //===----------------------------------------------------------------------===//
1925 //               Return Value Calling Convention Implementation
1926 //===----------------------------------------------------------------------===//
1927
1928 #include "X86GenCallingConv.inc"
1929
1930 bool
1931 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1932                                   MachineFunction &MF, bool isVarArg,
1933                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1934                         LLVMContext &Context) const {
1935   SmallVector<CCValAssign, 16> RVLocs;
1936   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1937   return CCInfo.CheckReturn(Outs, RetCC_X86);
1938 }
1939
1940 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1941   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1942   return ScratchRegs;
1943 }
1944
1945 SDValue
1946 X86TargetLowering::LowerReturn(SDValue Chain,
1947                                CallingConv::ID CallConv, bool isVarArg,
1948                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1949                                const SmallVectorImpl<SDValue> &OutVals,
1950                                SDLoc dl, SelectionDAG &DAG) const {
1951   MachineFunction &MF = DAG.getMachineFunction();
1952   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1953
1954   SmallVector<CCValAssign, 16> RVLocs;
1955   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1956   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1957
1958   SDValue Flag;
1959   SmallVector<SDValue, 6> RetOps;
1960   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1961   // Operand #1 = Bytes To Pop
1962   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1963                    MVT::i16));
1964
1965   // Copy the result values into the output registers.
1966   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1967     CCValAssign &VA = RVLocs[i];
1968     assert(VA.isRegLoc() && "Can only return in registers!");
1969     SDValue ValToCopy = OutVals[i];
1970     EVT ValVT = ValToCopy.getValueType();
1971
1972     // Promote values to the appropriate types.
1973     if (VA.getLocInfo() == CCValAssign::SExt)
1974       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1975     else if (VA.getLocInfo() == CCValAssign::ZExt)
1976       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1977     else if (VA.getLocInfo() == CCValAssign::AExt) {
1978       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1979         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1980       else
1981         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1982     }
1983     else if (VA.getLocInfo() == CCValAssign::BCvt)
1984       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1985
1986     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1987            "Unexpected FP-extend for return value.");
1988
1989     // If this is x86-64, and we disabled SSE, we can't return FP values,
1990     // or SSE or MMX vectors.
1991     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1992          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1993           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1994       report_fatal_error("SSE register return with SSE disabled");
1995     }
1996     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1997     // llvm-gcc has never done it right and no one has noticed, so this
1998     // should be OK for now.
1999     if (ValVT == MVT::f64 &&
2000         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2001       report_fatal_error("SSE2 register return with SSE2 disabled");
2002
2003     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2004     // the RET instruction and handled by the FP Stackifier.
2005     if (VA.getLocReg() == X86::FP0 ||
2006         VA.getLocReg() == X86::FP1) {
2007       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2008       // change the value to the FP stack register class.
2009       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2010         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2011       RetOps.push_back(ValToCopy);
2012       // Don't emit a copytoreg.
2013       continue;
2014     }
2015
2016     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2017     // which is returned in RAX / RDX.
2018     if (Subtarget->is64Bit()) {
2019       if (ValVT == MVT::x86mmx) {
2020         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2021           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2022           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2023                                   ValToCopy);
2024           // If we don't have SSE2 available, convert to v4f32 so the generated
2025           // register is legal.
2026           if (!Subtarget->hasSSE2())
2027             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2028         }
2029       }
2030     }
2031
2032     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2033     Flag = Chain.getValue(1);
2034     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2035   }
2036
2037   // All x86 ABIs require that for returning structs by value we copy
2038   // the sret argument into %rax/%eax (depending on ABI) for the return.
2039   // We saved the argument into a virtual register in the entry block,
2040   // so now we copy the value out and into %rax/%eax.
2041   //
2042   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2043   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2044   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2045   // either case FuncInfo->setSRetReturnReg() will have been called.
2046   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2047     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2048
2049     unsigned RetValReg
2050         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2051           X86::RAX : X86::EAX;
2052     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2053     Flag = Chain.getValue(1);
2054
2055     // RAX/EAX now acts like a return value.
2056     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2057   }
2058
2059   RetOps[0] = Chain;  // Update chain.
2060
2061   // Add the flag if we have it.
2062   if (Flag.getNode())
2063     RetOps.push_back(Flag);
2064
2065   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2066 }
2067
2068 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2069   if (N->getNumValues() != 1)
2070     return false;
2071   if (!N->hasNUsesOfValue(1, 0))
2072     return false;
2073
2074   SDValue TCChain = Chain;
2075   SDNode *Copy = *N->use_begin();
2076   if (Copy->getOpcode() == ISD::CopyToReg) {
2077     // If the copy has a glue operand, we conservatively assume it isn't safe to
2078     // perform a tail call.
2079     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2080       return false;
2081     TCChain = Copy->getOperand(0);
2082   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2083     return false;
2084
2085   bool HasRet = false;
2086   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2087        UI != UE; ++UI) {
2088     if (UI->getOpcode() != X86ISD::RET_FLAG)
2089       return false;
2090     // If we are returning more than one value, we can definitely
2091     // not make a tail call see PR19530
2092     if (UI->getNumOperands() > 4)
2093       return false;
2094     if (UI->getNumOperands() == 4 &&
2095         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2096       return false;
2097     HasRet = true;
2098   }
2099
2100   if (!HasRet)
2101     return false;
2102
2103   Chain = TCChain;
2104   return true;
2105 }
2106
2107 EVT
2108 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2109                                             ISD::NodeType ExtendKind) const {
2110   MVT ReturnMVT;
2111   // TODO: Is this also valid on 32-bit?
2112   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2113     ReturnMVT = MVT::i8;
2114   else
2115     ReturnMVT = MVT::i32;
2116
2117   EVT MinVT = getRegisterType(Context, ReturnMVT);
2118   return VT.bitsLT(MinVT) ? MinVT : VT;
2119 }
2120
2121 /// Lower the result values of a call into the
2122 /// appropriate copies out of appropriate physical registers.
2123 ///
2124 SDValue
2125 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2126                                    CallingConv::ID CallConv, bool isVarArg,
2127                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2128                                    SDLoc dl, SelectionDAG &DAG,
2129                                    SmallVectorImpl<SDValue> &InVals) const {
2130
2131   // Assign locations to each value returned by this call.
2132   SmallVector<CCValAssign, 16> RVLocs;
2133   bool Is64Bit = Subtarget->is64Bit();
2134   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2135                  *DAG.getContext());
2136   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2137
2138   // Copy all of the result registers out of their specified physreg.
2139   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2140     CCValAssign &VA = RVLocs[i];
2141     EVT CopyVT = VA.getLocVT();
2142
2143     // If this is x86-64, and we disabled SSE, we can't return FP values
2144     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2145         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2146       report_fatal_error("SSE register return with SSE disabled");
2147     }
2148
2149     // If we prefer to use the value in xmm registers, copy it out as f80 and
2150     // use a truncate to move it from fp stack reg to xmm reg.
2151     bool RoundAfterCopy = false;
2152     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2153         isScalarFPTypeInSSEReg(VA.getValVT())) {
2154       CopyVT = MVT::f80;
2155       RoundAfterCopy = (CopyVT != VA.getLocVT());
2156     }
2157
2158     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2159                                CopyVT, InFlag).getValue(1);
2160     SDValue Val = Chain.getValue(0);
2161
2162     if (RoundAfterCopy)
2163       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2164                         // This truncation won't change the value.
2165                         DAG.getIntPtrConstant(1, dl));
2166
2167     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2168       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2169
2170     InFlag = Chain.getValue(2);
2171     InVals.push_back(Val);
2172   }
2173
2174   return Chain;
2175 }
2176
2177 //===----------------------------------------------------------------------===//
2178 //                C & StdCall & Fast Calling Convention implementation
2179 //===----------------------------------------------------------------------===//
2180 //  StdCall calling convention seems to be standard for many Windows' API
2181 //  routines and around. It differs from C calling convention just a little:
2182 //  callee should clean up the stack, not caller. Symbols should be also
2183 //  decorated in some fancy way :) It doesn't support any vector arguments.
2184 //  For info on fast calling convention see Fast Calling Convention (tail call)
2185 //  implementation LowerX86_32FastCCCallTo.
2186
2187 /// CallIsStructReturn - Determines whether a call uses struct return
2188 /// semantics.
2189 enum StructReturnType {
2190   NotStructReturn,
2191   RegStructReturn,
2192   StackStructReturn
2193 };
2194 static StructReturnType
2195 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2196   if (Outs.empty())
2197     return NotStructReturn;
2198
2199   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2200   if (!Flags.isSRet())
2201     return NotStructReturn;
2202   if (Flags.isInReg())
2203     return RegStructReturn;
2204   return StackStructReturn;
2205 }
2206
2207 /// Determines whether a function uses struct return semantics.
2208 static StructReturnType
2209 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2210   if (Ins.empty())
2211     return NotStructReturn;
2212
2213   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2214   if (!Flags.isSRet())
2215     return NotStructReturn;
2216   if (Flags.isInReg())
2217     return RegStructReturn;
2218   return StackStructReturn;
2219 }
2220
2221 /// Make a copy of an aggregate at address specified by "Src" to address
2222 /// "Dst" with size and alignment information specified by the specific
2223 /// parameter attribute. The copy will be passed as a byval function parameter.
2224 static SDValue
2225 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2226                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2227                           SDLoc dl) {
2228   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2229
2230   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2231                        /*isVolatile*/false, /*AlwaysInline=*/true,
2232                        /*isTailCall*/false,
2233                        MachinePointerInfo(), MachinePointerInfo());
2234 }
2235
2236 /// Return true if the calling convention is one that
2237 /// supports tail call optimization.
2238 static bool IsTailCallConvention(CallingConv::ID CC) {
2239   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2240           CC == CallingConv::HiPE);
2241 }
2242
2243 /// \brief Return true if the calling convention is a C calling convention.
2244 static bool IsCCallConvention(CallingConv::ID CC) {
2245   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2246           CC == CallingConv::X86_64_SysV);
2247 }
2248
2249 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2250   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2251     return false;
2252
2253   CallSite CS(CI);
2254   CallingConv::ID CalleeCC = CS.getCallingConv();
2255   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2256     return false;
2257
2258   return true;
2259 }
2260
2261 /// Return true if the function is being made into
2262 /// a tailcall target by changing its ABI.
2263 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2264                                    bool GuaranteedTailCallOpt) {
2265   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2266 }
2267
2268 SDValue
2269 X86TargetLowering::LowerMemArgument(SDValue Chain,
2270                                     CallingConv::ID CallConv,
2271                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2272                                     SDLoc dl, SelectionDAG &DAG,
2273                                     const CCValAssign &VA,
2274                                     MachineFrameInfo *MFI,
2275                                     unsigned i) const {
2276   // Create the nodes corresponding to a load from this parameter slot.
2277   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2278   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2279       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2280   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2281   EVT ValVT;
2282
2283   // If value is passed by pointer we have address passed instead of the value
2284   // itself.
2285   bool ExtendedInMem = VA.isExtInLoc() &&
2286     VA.getValVT().getScalarType() == MVT::i1;
2287
2288   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2289     ValVT = VA.getLocVT();
2290   else
2291     ValVT = VA.getValVT();
2292
2293   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2294   // changed with more analysis.
2295   // In case of tail call optimization mark all arguments mutable. Since they
2296   // could be overwritten by lowering of arguments in case of a tail call.
2297   if (Flags.isByVal()) {
2298     unsigned Bytes = Flags.getByValSize();
2299     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2300     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2301     return DAG.getFrameIndex(FI, getPointerTy());
2302   } else {
2303     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2304                                     VA.getLocMemOffset(), isImmutable);
2305     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2306     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2307                                MachinePointerInfo::getFixedStack(FI),
2308                                false, false, false, 0);
2309     return ExtendedInMem ?
2310       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2311   }
2312 }
2313
2314 // FIXME: Get this from tablegen.
2315 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2316                                                 const X86Subtarget *Subtarget) {
2317   assert(Subtarget->is64Bit());
2318
2319   if (Subtarget->isCallingConvWin64(CallConv)) {
2320     static const MCPhysReg GPR64ArgRegsWin64[] = {
2321       X86::RCX, X86::RDX, X86::R8,  X86::R9
2322     };
2323     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2324   }
2325
2326   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2327     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2328   };
2329   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2330 }
2331
2332 // FIXME: Get this from tablegen.
2333 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2334                                                 CallingConv::ID CallConv,
2335                                                 const X86Subtarget *Subtarget) {
2336   assert(Subtarget->is64Bit());
2337   if (Subtarget->isCallingConvWin64(CallConv)) {
2338     // The XMM registers which might contain var arg parameters are shadowed
2339     // in their paired GPR.  So we only need to save the GPR to their home
2340     // slots.
2341     // TODO: __vectorcall will change this.
2342     return None;
2343   }
2344
2345   const Function *Fn = MF.getFunction();
2346   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2347   bool isSoftFloat = Subtarget->useSoftFloat();
2348   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2349          "SSE register cannot be used when SSE is disabled!");
2350   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2351     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2352     // registers.
2353     return None;
2354
2355   static const MCPhysReg XMMArgRegs64Bit[] = {
2356     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2357     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2358   };
2359   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2360 }
2361
2362 SDValue
2363 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2364                                         CallingConv::ID CallConv,
2365                                         bool isVarArg,
2366                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2367                                         SDLoc dl,
2368                                         SelectionDAG &DAG,
2369                                         SmallVectorImpl<SDValue> &InVals)
2370                                           const {
2371   MachineFunction &MF = DAG.getMachineFunction();
2372   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2373   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2374
2375   const Function* Fn = MF.getFunction();
2376   if (Fn->hasExternalLinkage() &&
2377       Subtarget->isTargetCygMing() &&
2378       Fn->getName() == "main")
2379     FuncInfo->setForceFramePointer(true);
2380
2381   MachineFrameInfo *MFI = MF.getFrameInfo();
2382   bool Is64Bit = Subtarget->is64Bit();
2383   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2384
2385   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2386          "Var args not supported with calling convention fastcc, ghc or hipe");
2387
2388   // Assign locations to all of the incoming arguments.
2389   SmallVector<CCValAssign, 16> ArgLocs;
2390   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2391
2392   // Allocate shadow area for Win64
2393   if (IsWin64)
2394     CCInfo.AllocateStack(32, 8);
2395
2396   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2397
2398   unsigned LastVal = ~0U;
2399   SDValue ArgValue;
2400   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2401     CCValAssign &VA = ArgLocs[i];
2402     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2403     // places.
2404     assert(VA.getValNo() != LastVal &&
2405            "Don't support value assigned to multiple locs yet");
2406     (void)LastVal;
2407     LastVal = VA.getValNo();
2408
2409     if (VA.isRegLoc()) {
2410       EVT RegVT = VA.getLocVT();
2411       const TargetRegisterClass *RC;
2412       if (RegVT == MVT::i32)
2413         RC = &X86::GR32RegClass;
2414       else if (Is64Bit && RegVT == MVT::i64)
2415         RC = &X86::GR64RegClass;
2416       else if (RegVT == MVT::f32)
2417         RC = &X86::FR32RegClass;
2418       else if (RegVT == MVT::f64)
2419         RC = &X86::FR64RegClass;
2420       else if (RegVT.is512BitVector())
2421         RC = &X86::VR512RegClass;
2422       else if (RegVT.is256BitVector())
2423         RC = &X86::VR256RegClass;
2424       else if (RegVT.is128BitVector())
2425         RC = &X86::VR128RegClass;
2426       else if (RegVT == MVT::x86mmx)
2427         RC = &X86::VR64RegClass;
2428       else if (RegVT == MVT::i1)
2429         RC = &X86::VK1RegClass;
2430       else if (RegVT == MVT::v8i1)
2431         RC = &X86::VK8RegClass;
2432       else if (RegVT == MVT::v16i1)
2433         RC = &X86::VK16RegClass;
2434       else if (RegVT == MVT::v32i1)
2435         RC = &X86::VK32RegClass;
2436       else if (RegVT == MVT::v64i1)
2437         RC = &X86::VK64RegClass;
2438       else
2439         llvm_unreachable("Unknown argument type!");
2440
2441       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2442       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2443
2444       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2445       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2446       // right size.
2447       if (VA.getLocInfo() == CCValAssign::SExt)
2448         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2449                                DAG.getValueType(VA.getValVT()));
2450       else if (VA.getLocInfo() == CCValAssign::ZExt)
2451         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2452                                DAG.getValueType(VA.getValVT()));
2453       else if (VA.getLocInfo() == CCValAssign::BCvt)
2454         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2455
2456       if (VA.isExtInLoc()) {
2457         // Handle MMX values passed in XMM regs.
2458         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2459           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2460         else
2461           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2462       }
2463     } else {
2464       assert(VA.isMemLoc());
2465       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2466     }
2467
2468     // If value is passed via pointer - do a load.
2469     if (VA.getLocInfo() == CCValAssign::Indirect)
2470       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2471                              MachinePointerInfo(), false, false, false, 0);
2472
2473     InVals.push_back(ArgValue);
2474   }
2475
2476   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2477     // All x86 ABIs require that for returning structs by value we copy the
2478     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2479     // the argument into a virtual register so that we can access it from the
2480     // return points.
2481     if (Ins[i].Flags.isSRet()) {
2482       unsigned Reg = FuncInfo->getSRetReturnReg();
2483       if (!Reg) {
2484         MVT PtrTy = getPointerTy();
2485         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2486         FuncInfo->setSRetReturnReg(Reg);
2487       }
2488       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2489       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2490       break;
2491     }
2492   }
2493
2494   unsigned StackSize = CCInfo.getNextStackOffset();
2495   // Align stack specially for tail calls.
2496   if (FuncIsMadeTailCallSafe(CallConv,
2497                              MF.getTarget().Options.GuaranteedTailCallOpt))
2498     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2499
2500   // If the function takes variable number of arguments, make a frame index for
2501   // the start of the first vararg value... for expansion of llvm.va_start. We
2502   // can skip this if there are no va_start calls.
2503   if (MFI->hasVAStart() &&
2504       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2505                    CallConv != CallingConv::X86_ThisCall))) {
2506     FuncInfo->setVarArgsFrameIndex(
2507         MFI->CreateFixedObject(1, StackSize, true));
2508   }
2509
2510   MachineModuleInfo &MMI = MF.getMMI();
2511   const Function *WinEHParent = nullptr;
2512   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2513     WinEHParent = MMI.getWinEHParent(Fn);
2514   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2515   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2516
2517   // Figure out if XMM registers are in use.
2518   assert(!(Subtarget->useSoftFloat() &&
2519            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2520          "SSE register cannot be used when SSE is disabled!");
2521
2522   // 64-bit calling conventions support varargs and register parameters, so we
2523   // have to do extra work to spill them in the prologue.
2524   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2525     // Find the first unallocated argument registers.
2526     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2527     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2528     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2529     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2530     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2531            "SSE register cannot be used when SSE is disabled!");
2532
2533     // Gather all the live in physical registers.
2534     SmallVector<SDValue, 6> LiveGPRs;
2535     SmallVector<SDValue, 8> LiveXMMRegs;
2536     SDValue ALVal;
2537     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2538       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2539       LiveGPRs.push_back(
2540           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2541     }
2542     if (!ArgXMMs.empty()) {
2543       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2544       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2545       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2546         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2547         LiveXMMRegs.push_back(
2548             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2549       }
2550     }
2551
2552     if (IsWin64) {
2553       // Get to the caller-allocated home save location.  Add 8 to account
2554       // for the return address.
2555       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2556       FuncInfo->setRegSaveFrameIndex(
2557           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2558       // Fixup to set vararg frame on shadow area (4 x i64).
2559       if (NumIntRegs < 4)
2560         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2561     } else {
2562       // For X86-64, if there are vararg parameters that are passed via
2563       // registers, then we must store them to their spots on the stack so
2564       // they may be loaded by deferencing the result of va_next.
2565       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2566       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2567       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2568           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2569     }
2570
2571     // Store the integer parameter registers.
2572     SmallVector<SDValue, 8> MemOps;
2573     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2574                                       getPointerTy());
2575     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2576     for (SDValue Val : LiveGPRs) {
2577       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2578                                 DAG.getIntPtrConstant(Offset, dl));
2579       SDValue Store =
2580         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2581                      MachinePointerInfo::getFixedStack(
2582                        FuncInfo->getRegSaveFrameIndex(), Offset),
2583                      false, false, 0);
2584       MemOps.push_back(Store);
2585       Offset += 8;
2586     }
2587
2588     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2589       // Now store the XMM (fp + vector) parameter registers.
2590       SmallVector<SDValue, 12> SaveXMMOps;
2591       SaveXMMOps.push_back(Chain);
2592       SaveXMMOps.push_back(ALVal);
2593       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2594                              FuncInfo->getRegSaveFrameIndex(), dl));
2595       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2596                              FuncInfo->getVarArgsFPOffset(), dl));
2597       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2598                         LiveXMMRegs.end());
2599       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2600                                    MVT::Other, SaveXMMOps));
2601     }
2602
2603     if (!MemOps.empty())
2604       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2605   } else if (IsWinEHOutlined) {
2606     // Get to the caller-allocated home save location.  Add 8 to account
2607     // for the return address.
2608     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2609     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2610         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2611
2612     MMI.getWinEHFuncInfo(Fn)
2613         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2614         FuncInfo->getRegSaveFrameIndex();
2615
2616     // Store the second integer parameter (rdx) into rsp+16 relative to the
2617     // stack pointer at the entry of the function.
2618     SDValue RSFIN =
2619         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2620     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2621     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2622     Chain = DAG.getStore(
2623         Val.getValue(1), dl, Val, RSFIN,
2624         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2625         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2626   }
2627
2628   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2629     // Find the largest legal vector type.
2630     MVT VecVT = MVT::Other;
2631     // FIXME: Only some x86_32 calling conventions support AVX512.
2632     if (Subtarget->hasAVX512() &&
2633         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2634                      CallConv == CallingConv::Intel_OCL_BI)))
2635       VecVT = MVT::v16f32;
2636     else if (Subtarget->hasAVX())
2637       VecVT = MVT::v8f32;
2638     else if (Subtarget->hasSSE2())
2639       VecVT = MVT::v4f32;
2640
2641     // We forward some GPRs and some vector types.
2642     SmallVector<MVT, 2> RegParmTypes;
2643     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2644     RegParmTypes.push_back(IntVT);
2645     if (VecVT != MVT::Other)
2646       RegParmTypes.push_back(VecVT);
2647
2648     // Compute the set of forwarded registers. The rest are scratch.
2649     SmallVectorImpl<ForwardedRegister> &Forwards =
2650         FuncInfo->getForwardedMustTailRegParms();
2651     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2652
2653     // Conservatively forward AL on x86_64, since it might be used for varargs.
2654     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2655       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2656       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2657     }
2658
2659     // Copy all forwards from physical to virtual registers.
2660     for (ForwardedRegister &F : Forwards) {
2661       // FIXME: Can we use a less constrained schedule?
2662       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2663       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2664       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2665     }
2666   }
2667
2668   // Some CCs need callee pop.
2669   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2670                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2671     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2672   } else {
2673     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2674     // If this is an sret function, the return should pop the hidden pointer.
2675     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2676         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2677         argsAreStructReturn(Ins) == StackStructReturn)
2678       FuncInfo->setBytesToPopOnReturn(4);
2679   }
2680
2681   if (!Is64Bit) {
2682     // RegSaveFrameIndex is X86-64 only.
2683     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2684     if (CallConv == CallingConv::X86_FastCall ||
2685         CallConv == CallingConv::X86_ThisCall)
2686       // fastcc functions can't have varargs.
2687       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2688   }
2689
2690   FuncInfo->setArgumentStackSize(StackSize);
2691
2692   if (IsWinEHParent) {
2693     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2694     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2695     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2696     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2697     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2698                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2699                          /*isVolatile=*/true,
2700                          /*isNonTemporal=*/false, /*Alignment=*/0);
2701   }
2702
2703   return Chain;
2704 }
2705
2706 SDValue
2707 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2708                                     SDValue StackPtr, SDValue Arg,
2709                                     SDLoc dl, SelectionDAG &DAG,
2710                                     const CCValAssign &VA,
2711                                     ISD::ArgFlagsTy Flags) const {
2712   unsigned LocMemOffset = VA.getLocMemOffset();
2713   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2714   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2715   if (Flags.isByVal())
2716     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2717
2718   return DAG.getStore(Chain, dl, Arg, PtrOff,
2719                       MachinePointerInfo::getStack(LocMemOffset),
2720                       false, false, 0);
2721 }
2722
2723 /// Emit a load of return address if tail call
2724 /// optimization is performed and it is required.
2725 SDValue
2726 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2727                                            SDValue &OutRetAddr, SDValue Chain,
2728                                            bool IsTailCall, bool Is64Bit,
2729                                            int FPDiff, SDLoc dl) const {
2730   // Adjust the Return address stack slot.
2731   EVT VT = getPointerTy();
2732   OutRetAddr = getReturnAddressFrameIndex(DAG);
2733
2734   // Load the "old" Return address.
2735   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2736                            false, false, false, 0);
2737   return SDValue(OutRetAddr.getNode(), 1);
2738 }
2739
2740 /// Emit a store of the return address if tail call
2741 /// optimization is performed and it is required (FPDiff!=0).
2742 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2743                                         SDValue Chain, SDValue RetAddrFrIdx,
2744                                         EVT PtrVT, unsigned SlotSize,
2745                                         int FPDiff, SDLoc dl) {
2746   // Store the return address to the appropriate stack slot.
2747   if (!FPDiff) return Chain;
2748   // Calculate the new stack slot for the return address.
2749   int NewReturnAddrFI =
2750     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2751                                          false);
2752   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2753   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2754                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2755                        false, false, 0);
2756   return Chain;
2757 }
2758
2759 SDValue
2760 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2761                              SmallVectorImpl<SDValue> &InVals) const {
2762   SelectionDAG &DAG                     = CLI.DAG;
2763   SDLoc &dl                             = CLI.DL;
2764   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2765   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2766   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2767   SDValue Chain                         = CLI.Chain;
2768   SDValue Callee                        = CLI.Callee;
2769   CallingConv::ID CallConv              = CLI.CallConv;
2770   bool &isTailCall                      = CLI.IsTailCall;
2771   bool isVarArg                         = CLI.IsVarArg;
2772
2773   MachineFunction &MF = DAG.getMachineFunction();
2774   bool Is64Bit        = Subtarget->is64Bit();
2775   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2776   StructReturnType SR = callIsStructReturn(Outs);
2777   bool IsSibcall      = false;
2778   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2779
2780   if (MF.getTarget().Options.DisableTailCalls)
2781     isTailCall = false;
2782
2783   if (Subtarget->isPICStyleGOT() &&
2784       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2785     // If we are using a GOT, disable tail calls to external symbols with
2786     // default visibility. Tail calling such a symbol requires using a GOT
2787     // relocation, which forces early binding of the symbol. This breaks code
2788     // that require lazy function symbol resolution. Using musttail or
2789     // GuaranteedTailCallOpt will override this.
2790     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2791     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2792                G->getGlobal()->hasDefaultVisibility())) {
2793       isTailCall = false;
2794       if (G) {
2795         llvm::errs() << "disabling tail call for default visibility symbol\n";
2796         G->getGlobal()->dump();
2797       }
2798     }
2799   }
2800
2801   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2802   if (IsMustTail) {
2803     // Force this to be a tail call.  The verifier rules are enough to ensure
2804     // that we can lower this successfully without moving the return address
2805     // around.
2806     isTailCall = true;
2807   } else if (isTailCall) {
2808     // Check if it's really possible to do a tail call.
2809     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2810                     isVarArg, SR != NotStructReturn,
2811                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2812                     Outs, OutVals, Ins, DAG);
2813
2814     // Sibcalls are automatically detected tailcalls which do not require
2815     // ABI changes.
2816     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2817       IsSibcall = true;
2818
2819     if (isTailCall)
2820       ++NumTailCalls;
2821   }
2822
2823   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2824          "Var args not supported with calling convention fastcc, ghc or hipe");
2825
2826   // Analyze operands of the call, assigning locations to each operand.
2827   SmallVector<CCValAssign, 16> ArgLocs;
2828   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2829
2830   // Allocate shadow area for Win64
2831   if (IsWin64)
2832     CCInfo.AllocateStack(32, 8);
2833
2834   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2835
2836   // Get a count of how many bytes are to be pushed on the stack.
2837   unsigned NumBytes = CCInfo.getNextStackOffset();
2838   if (IsSibcall)
2839     // This is a sibcall. The memory operands are available in caller's
2840     // own caller's stack.
2841     NumBytes = 0;
2842   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2843            IsTailCallConvention(CallConv))
2844     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2845
2846   int FPDiff = 0;
2847   if (isTailCall && !IsSibcall && !IsMustTail) {
2848     // Lower arguments at fp - stackoffset + fpdiff.
2849     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2850
2851     FPDiff = NumBytesCallerPushed - NumBytes;
2852
2853     // Set the delta of movement of the returnaddr stackslot.
2854     // But only set if delta is greater than previous delta.
2855     if (FPDiff < X86Info->getTCReturnAddrDelta())
2856       X86Info->setTCReturnAddrDelta(FPDiff);
2857   }
2858
2859   unsigned NumBytesToPush = NumBytes;
2860   unsigned NumBytesToPop = NumBytes;
2861
2862   // If we have an inalloca argument, all stack space has already been allocated
2863   // for us and be right at the top of the stack.  We don't support multiple
2864   // arguments passed in memory when using inalloca.
2865   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2866     NumBytesToPush = 0;
2867     if (!ArgLocs.back().isMemLoc())
2868       report_fatal_error("cannot use inalloca attribute on a register "
2869                          "parameter");
2870     if (ArgLocs.back().getLocMemOffset() != 0)
2871       report_fatal_error("any parameter with the inalloca attribute must be "
2872                          "the only memory argument");
2873   }
2874
2875   if (!IsSibcall)
2876     Chain = DAG.getCALLSEQ_START(
2877         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2878
2879   SDValue RetAddrFrIdx;
2880   // Load return address for tail calls.
2881   if (isTailCall && FPDiff)
2882     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2883                                     Is64Bit, FPDiff, dl);
2884
2885   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2886   SmallVector<SDValue, 8> MemOpChains;
2887   SDValue StackPtr;
2888
2889   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2890   // of tail call optimization arguments are handle later.
2891   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2892   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2893     // Skip inalloca arguments, they have already been written.
2894     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2895     if (Flags.isInAlloca())
2896       continue;
2897
2898     CCValAssign &VA = ArgLocs[i];
2899     EVT RegVT = VA.getLocVT();
2900     SDValue Arg = OutVals[i];
2901     bool isByVal = Flags.isByVal();
2902
2903     // Promote the value if needed.
2904     switch (VA.getLocInfo()) {
2905     default: llvm_unreachable("Unknown loc info!");
2906     case CCValAssign::Full: break;
2907     case CCValAssign::SExt:
2908       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2909       break;
2910     case CCValAssign::ZExt:
2911       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2912       break;
2913     case CCValAssign::AExt:
2914       if (Arg.getValueType().isVector() &&
2915           Arg.getValueType().getScalarType() == MVT::i1)
2916         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2917       else if (RegVT.is128BitVector()) {
2918         // Special case: passing MMX values in XMM registers.
2919         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2920         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2921         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2922       } else
2923         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2924       break;
2925     case CCValAssign::BCvt:
2926       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2927       break;
2928     case CCValAssign::Indirect: {
2929       // Store the argument.
2930       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2931       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2932       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2933                            MachinePointerInfo::getFixedStack(FI),
2934                            false, false, 0);
2935       Arg = SpillSlot;
2936       break;
2937     }
2938     }
2939
2940     if (VA.isRegLoc()) {
2941       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2942       if (isVarArg && IsWin64) {
2943         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2944         // shadow reg if callee is a varargs function.
2945         unsigned ShadowReg = 0;
2946         switch (VA.getLocReg()) {
2947         case X86::XMM0: ShadowReg = X86::RCX; break;
2948         case X86::XMM1: ShadowReg = X86::RDX; break;
2949         case X86::XMM2: ShadowReg = X86::R8; break;
2950         case X86::XMM3: ShadowReg = X86::R9; break;
2951         }
2952         if (ShadowReg)
2953           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2954       }
2955     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2956       assert(VA.isMemLoc());
2957       if (!StackPtr.getNode())
2958         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2959                                       getPointerTy());
2960       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2961                                              dl, DAG, VA, Flags));
2962     }
2963   }
2964
2965   if (!MemOpChains.empty())
2966     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2967
2968   if (Subtarget->isPICStyleGOT()) {
2969     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2970     // GOT pointer.
2971     if (!isTailCall) {
2972       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2973                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2974     } else {
2975       // If we are tail calling and generating PIC/GOT style code load the
2976       // address of the callee into ECX. The value in ecx is used as target of
2977       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2978       // for tail calls on PIC/GOT architectures. Normally we would just put the
2979       // address of GOT into ebx and then call target@PLT. But for tail calls
2980       // ebx would be restored (since ebx is callee saved) before jumping to the
2981       // target@PLT.
2982
2983       // Note: The actual moving to ECX is done further down.
2984       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2985       if (G && !G->getGlobal()->hasLocalLinkage() &&
2986           G->getGlobal()->hasDefaultVisibility())
2987         Callee = LowerGlobalAddress(Callee, DAG);
2988       else if (isa<ExternalSymbolSDNode>(Callee))
2989         Callee = LowerExternalSymbol(Callee, DAG);
2990     }
2991   }
2992
2993   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2994     // From AMD64 ABI document:
2995     // For calls that may call functions that use varargs or stdargs
2996     // (prototype-less calls or calls to functions containing ellipsis (...) in
2997     // the declaration) %al is used as hidden argument to specify the number
2998     // of SSE registers used. The contents of %al do not need to match exactly
2999     // the number of registers, but must be an ubound on the number of SSE
3000     // registers used and is in the range 0 - 8 inclusive.
3001
3002     // Count the number of XMM registers allocated.
3003     static const MCPhysReg XMMArgRegs[] = {
3004       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3005       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3006     };
3007     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3008     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3009            && "SSE registers cannot be used when SSE is disabled");
3010
3011     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3012                                         DAG.getConstant(NumXMMRegs, dl,
3013                                                         MVT::i8)));
3014   }
3015
3016   if (isVarArg && IsMustTail) {
3017     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3018     for (const auto &F : Forwards) {
3019       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3020       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3021     }
3022   }
3023
3024   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3025   // don't need this because the eligibility check rejects calls that require
3026   // shuffling arguments passed in memory.
3027   if (!IsSibcall && isTailCall) {
3028     // Force all the incoming stack arguments to be loaded from the stack
3029     // before any new outgoing arguments are stored to the stack, because the
3030     // outgoing stack slots may alias the incoming argument stack slots, and
3031     // the alias isn't otherwise explicit. This is slightly more conservative
3032     // than necessary, because it means that each store effectively depends
3033     // on every argument instead of just those arguments it would clobber.
3034     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3035
3036     SmallVector<SDValue, 8> MemOpChains2;
3037     SDValue FIN;
3038     int FI = 0;
3039     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3040       CCValAssign &VA = ArgLocs[i];
3041       if (VA.isRegLoc())
3042         continue;
3043       assert(VA.isMemLoc());
3044       SDValue Arg = OutVals[i];
3045       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3046       // Skip inalloca arguments.  They don't require any work.
3047       if (Flags.isInAlloca())
3048         continue;
3049       // Create frame index.
3050       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3051       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3052       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3053       FIN = DAG.getFrameIndex(FI, getPointerTy());
3054
3055       if (Flags.isByVal()) {
3056         // Copy relative to framepointer.
3057         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3058         if (!StackPtr.getNode())
3059           StackPtr = DAG.getCopyFromReg(Chain, dl,
3060                                         RegInfo->getStackRegister(),
3061                                         getPointerTy());
3062         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3063
3064         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3065                                                          ArgChain,
3066                                                          Flags, DAG, dl));
3067       } else {
3068         // Store relative to framepointer.
3069         MemOpChains2.push_back(
3070           DAG.getStore(ArgChain, dl, Arg, FIN,
3071                        MachinePointerInfo::getFixedStack(FI),
3072                        false, false, 0));
3073       }
3074     }
3075
3076     if (!MemOpChains2.empty())
3077       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3078
3079     // Store the return address to the appropriate stack slot.
3080     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3081                                      getPointerTy(), RegInfo->getSlotSize(),
3082                                      FPDiff, dl);
3083   }
3084
3085   // Build a sequence of copy-to-reg nodes chained together with token chain
3086   // and flag operands which copy the outgoing args into registers.
3087   SDValue InFlag;
3088   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3089     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3090                              RegsToPass[i].second, InFlag);
3091     InFlag = Chain.getValue(1);
3092   }
3093
3094   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3095     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3096     // In the 64-bit large code model, we have to make all calls
3097     // through a register, since the call instruction's 32-bit
3098     // pc-relative offset may not be large enough to hold the whole
3099     // address.
3100   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3101     // If the callee is a GlobalAddress node (quite common, every direct call
3102     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3103     // it.
3104     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3105
3106     // We should use extra load for direct calls to dllimported functions in
3107     // non-JIT mode.
3108     const GlobalValue *GV = G->getGlobal();
3109     if (!GV->hasDLLImportStorageClass()) {
3110       unsigned char OpFlags = 0;
3111       bool ExtraLoad = false;
3112       unsigned WrapperKind = ISD::DELETED_NODE;
3113
3114       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3115       // external symbols most go through the PLT in PIC mode.  If the symbol
3116       // has hidden or protected visibility, or if it is static or local, then
3117       // we don't need to use the PLT - we can directly call it.
3118       if (Subtarget->isTargetELF() &&
3119           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3120           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3121         OpFlags = X86II::MO_PLT;
3122       } else if (Subtarget->isPICStyleStubAny() &&
3123                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3124                  (!Subtarget->getTargetTriple().isMacOSX() ||
3125                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3126         // PC-relative references to external symbols should go through $stub,
3127         // unless we're building with the leopard linker or later, which
3128         // automatically synthesizes these stubs.
3129         OpFlags = X86II::MO_DARWIN_STUB;
3130       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3131                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3132         // If the function is marked as non-lazy, generate an indirect call
3133         // which loads from the GOT directly. This avoids runtime overhead
3134         // at the cost of eager binding (and one extra byte of encoding).
3135         OpFlags = X86II::MO_GOTPCREL;
3136         WrapperKind = X86ISD::WrapperRIP;
3137         ExtraLoad = true;
3138       }
3139
3140       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3141                                           G->getOffset(), OpFlags);
3142
3143       // Add a wrapper if needed.
3144       if (WrapperKind != ISD::DELETED_NODE)
3145         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3146       // Add extra indirection if needed.
3147       if (ExtraLoad)
3148         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3149                              MachinePointerInfo::getGOT(),
3150                              false, false, false, 0);
3151     }
3152   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3153     unsigned char OpFlags = 0;
3154
3155     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3156     // external symbols should go through the PLT.
3157     if (Subtarget->isTargetELF() &&
3158         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3159       OpFlags = X86II::MO_PLT;
3160     } else if (Subtarget->isPICStyleStubAny() &&
3161                (!Subtarget->getTargetTriple().isMacOSX() ||
3162                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3163       // PC-relative references to external symbols should go through $stub,
3164       // unless we're building with the leopard linker or later, which
3165       // automatically synthesizes these stubs.
3166       OpFlags = X86II::MO_DARWIN_STUB;
3167     }
3168
3169     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3170                                          OpFlags);
3171   } else if (Subtarget->isTarget64BitILP32() &&
3172              Callee->getValueType(0) == MVT::i32) {
3173     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3174     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3175   }
3176
3177   // Returns a chain & a flag for retval copy to use.
3178   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3179   SmallVector<SDValue, 8> Ops;
3180
3181   if (!IsSibcall && isTailCall) {
3182     Chain = DAG.getCALLSEQ_END(Chain,
3183                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3184                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3185     InFlag = Chain.getValue(1);
3186   }
3187
3188   Ops.push_back(Chain);
3189   Ops.push_back(Callee);
3190
3191   if (isTailCall)
3192     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3193
3194   // Add argument registers to the end of the list so that they are known live
3195   // into the call.
3196   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3197     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3198                                   RegsToPass[i].second.getValueType()));
3199
3200   // Add a register mask operand representing the call-preserved registers.
3201   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3202   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3203   assert(Mask && "Missing call preserved mask for calling convention");
3204   Ops.push_back(DAG.getRegisterMask(Mask));
3205
3206   if (InFlag.getNode())
3207     Ops.push_back(InFlag);
3208
3209   if (isTailCall) {
3210     // We used to do:
3211     //// If this is the first return lowered for this function, add the regs
3212     //// to the liveout set for the function.
3213     // This isn't right, although it's probably harmless on x86; liveouts
3214     // should be computed from returns not tail calls.  Consider a void
3215     // function making a tail call to a function returning int.
3216     MF.getFrameInfo()->setHasTailCall();
3217     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3218   }
3219
3220   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3221   InFlag = Chain.getValue(1);
3222
3223   // Create the CALLSEQ_END node.
3224   unsigned NumBytesForCalleeToPop;
3225   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3226                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3227     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3228   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3229            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3230            SR == StackStructReturn)
3231     // If this is a call to a struct-return function, the callee
3232     // pops the hidden struct pointer, so we have to push it back.
3233     // This is common for Darwin/X86, Linux & Mingw32 targets.
3234     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3235     NumBytesForCalleeToPop = 4;
3236   else
3237     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3238
3239   // Returns a flag for retval copy to use.
3240   if (!IsSibcall) {
3241     Chain = DAG.getCALLSEQ_END(Chain,
3242                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3243                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3244                                                      true),
3245                                InFlag, dl);
3246     InFlag = Chain.getValue(1);
3247   }
3248
3249   // Handle result values, copying them out of physregs into vregs that we
3250   // return.
3251   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3252                          Ins, dl, DAG, InVals);
3253 }
3254
3255 //===----------------------------------------------------------------------===//
3256 //                Fast Calling Convention (tail call) implementation
3257 //===----------------------------------------------------------------------===//
3258
3259 //  Like std call, callee cleans arguments, convention except that ECX is
3260 //  reserved for storing the tail called function address. Only 2 registers are
3261 //  free for argument passing (inreg). Tail call optimization is performed
3262 //  provided:
3263 //                * tailcallopt is enabled
3264 //                * caller/callee are fastcc
3265 //  On X86_64 architecture with GOT-style position independent code only local
3266 //  (within module) calls are supported at the moment.
3267 //  To keep the stack aligned according to platform abi the function
3268 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3269 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3270 //  If a tail called function callee has more arguments than the caller the
3271 //  caller needs to make sure that there is room to move the RETADDR to. This is
3272 //  achieved by reserving an area the size of the argument delta right after the
3273 //  original RETADDR, but before the saved framepointer or the spilled registers
3274 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3275 //  stack layout:
3276 //    arg1
3277 //    arg2
3278 //    RETADDR
3279 //    [ new RETADDR
3280 //      move area ]
3281 //    (possible EBP)
3282 //    ESI
3283 //    EDI
3284 //    local1 ..
3285
3286 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3287 /// for a 16 byte align requirement.
3288 unsigned
3289 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3290                                                SelectionDAG& DAG) const {
3291   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3292   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3293   unsigned StackAlignment = TFI.getStackAlignment();
3294   uint64_t AlignMask = StackAlignment - 1;
3295   int64_t Offset = StackSize;
3296   unsigned SlotSize = RegInfo->getSlotSize();
3297   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3298     // Number smaller than 12 so just add the difference.
3299     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3300   } else {
3301     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3302     Offset = ((~AlignMask) & Offset) + StackAlignment +
3303       (StackAlignment-SlotSize);
3304   }
3305   return Offset;
3306 }
3307
3308 /// MatchingStackOffset - Return true if the given stack call argument is
3309 /// already available in the same position (relatively) of the caller's
3310 /// incoming argument stack.
3311 static
3312 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3313                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3314                          const X86InstrInfo *TII) {
3315   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3316   int FI = INT_MAX;
3317   if (Arg.getOpcode() == ISD::CopyFromReg) {
3318     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3319     if (!TargetRegisterInfo::isVirtualRegister(VR))
3320       return false;
3321     MachineInstr *Def = MRI->getVRegDef(VR);
3322     if (!Def)
3323       return false;
3324     if (!Flags.isByVal()) {
3325       if (!TII->isLoadFromStackSlot(Def, FI))
3326         return false;
3327     } else {
3328       unsigned Opcode = Def->getOpcode();
3329       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3330            Opcode == X86::LEA64_32r) &&
3331           Def->getOperand(1).isFI()) {
3332         FI = Def->getOperand(1).getIndex();
3333         Bytes = Flags.getByValSize();
3334       } else
3335         return false;
3336     }
3337   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3338     if (Flags.isByVal())
3339       // ByVal argument is passed in as a pointer but it's now being
3340       // dereferenced. e.g.
3341       // define @foo(%struct.X* %A) {
3342       //   tail call @bar(%struct.X* byval %A)
3343       // }
3344       return false;
3345     SDValue Ptr = Ld->getBasePtr();
3346     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3347     if (!FINode)
3348       return false;
3349     FI = FINode->getIndex();
3350   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3351     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3352     FI = FINode->getIndex();
3353     Bytes = Flags.getByValSize();
3354   } else
3355     return false;
3356
3357   assert(FI != INT_MAX);
3358   if (!MFI->isFixedObjectIndex(FI))
3359     return false;
3360   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3361 }
3362
3363 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3364 /// for tail call optimization. Targets which want to do tail call
3365 /// optimization should implement this function.
3366 bool
3367 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3368                                                      CallingConv::ID CalleeCC,
3369                                                      bool isVarArg,
3370                                                      bool isCalleeStructRet,
3371                                                      bool isCallerStructRet,
3372                                                      Type *RetTy,
3373                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3374                                     const SmallVectorImpl<SDValue> &OutVals,
3375                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3376                                                      SelectionDAG &DAG) const {
3377   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3378     return false;
3379
3380   // If -tailcallopt is specified, make fastcc functions tail-callable.
3381   const MachineFunction &MF = DAG.getMachineFunction();
3382   const Function *CallerF = MF.getFunction();
3383
3384   // If the function return type is x86_fp80 and the callee return type is not,
3385   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3386   // perform a tailcall optimization here.
3387   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3388     return false;
3389
3390   CallingConv::ID CallerCC = CallerF->getCallingConv();
3391   bool CCMatch = CallerCC == CalleeCC;
3392   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3393   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3394
3395   // Win64 functions have extra shadow space for argument homing. Don't do the
3396   // sibcall if the caller and callee have mismatched expectations for this
3397   // space.
3398   if (IsCalleeWin64 != IsCallerWin64)
3399     return false;
3400
3401   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3402     if (IsTailCallConvention(CalleeCC) && CCMatch)
3403       return true;
3404     return false;
3405   }
3406
3407   // Look for obvious safe cases to perform tail call optimization that do not
3408   // require ABI changes. This is what gcc calls sibcall.
3409
3410   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3411   // emit a special epilogue.
3412   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3413   if (RegInfo->needsStackRealignment(MF))
3414     return false;
3415
3416   // Also avoid sibcall optimization if either caller or callee uses struct
3417   // return semantics.
3418   if (isCalleeStructRet || isCallerStructRet)
3419     return false;
3420
3421   // An stdcall/thiscall caller is expected to clean up its arguments; the
3422   // callee isn't going to do that.
3423   // FIXME: this is more restrictive than needed. We could produce a tailcall
3424   // when the stack adjustment matches. For example, with a thiscall that takes
3425   // only one argument.
3426   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3427                    CallerCC == CallingConv::X86_ThisCall))
3428     return false;
3429
3430   // Do not sibcall optimize vararg calls unless all arguments are passed via
3431   // registers.
3432   if (isVarArg && !Outs.empty()) {
3433
3434     // Optimizing for varargs on Win64 is unlikely to be safe without
3435     // additional testing.
3436     if (IsCalleeWin64 || IsCallerWin64)
3437       return false;
3438
3439     SmallVector<CCValAssign, 16> ArgLocs;
3440     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3441                    *DAG.getContext());
3442
3443     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3444     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3445       if (!ArgLocs[i].isRegLoc())
3446         return false;
3447   }
3448
3449   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3450   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3451   // this into a sibcall.
3452   bool Unused = false;
3453   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3454     if (!Ins[i].Used) {
3455       Unused = true;
3456       break;
3457     }
3458   }
3459   if (Unused) {
3460     SmallVector<CCValAssign, 16> RVLocs;
3461     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3462                    *DAG.getContext());
3463     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3464     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3465       CCValAssign &VA = RVLocs[i];
3466       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3467         return false;
3468     }
3469   }
3470
3471   // If the calling conventions do not match, then we'd better make sure the
3472   // results are returned in the same way as what the caller expects.
3473   if (!CCMatch) {
3474     SmallVector<CCValAssign, 16> RVLocs1;
3475     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3476                     *DAG.getContext());
3477     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3478
3479     SmallVector<CCValAssign, 16> RVLocs2;
3480     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3481                     *DAG.getContext());
3482     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3483
3484     if (RVLocs1.size() != RVLocs2.size())
3485       return false;
3486     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3487       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3488         return false;
3489       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3490         return false;
3491       if (RVLocs1[i].isRegLoc()) {
3492         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3493           return false;
3494       } else {
3495         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3496           return false;
3497       }
3498     }
3499   }
3500
3501   // If the callee takes no arguments then go on to check the results of the
3502   // call.
3503   if (!Outs.empty()) {
3504     // Check if stack adjustment is needed. For now, do not do this if any
3505     // argument is passed on the stack.
3506     SmallVector<CCValAssign, 16> ArgLocs;
3507     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3508                    *DAG.getContext());
3509
3510     // Allocate shadow area for Win64
3511     if (IsCalleeWin64)
3512       CCInfo.AllocateStack(32, 8);
3513
3514     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3515     if (CCInfo.getNextStackOffset()) {
3516       MachineFunction &MF = DAG.getMachineFunction();
3517       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3518         return false;
3519
3520       // Check if the arguments are already laid out in the right way as
3521       // the caller's fixed stack objects.
3522       MachineFrameInfo *MFI = MF.getFrameInfo();
3523       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3524       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3525       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3526         CCValAssign &VA = ArgLocs[i];
3527         SDValue Arg = OutVals[i];
3528         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3529         if (VA.getLocInfo() == CCValAssign::Indirect)
3530           return false;
3531         if (!VA.isRegLoc()) {
3532           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3533                                    MFI, MRI, TII))
3534             return false;
3535         }
3536       }
3537     }
3538
3539     // If the tailcall address may be in a register, then make sure it's
3540     // possible to register allocate for it. In 32-bit, the call address can
3541     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3542     // callee-saved registers are restored. These happen to be the same
3543     // registers used to pass 'inreg' arguments so watch out for those.
3544     if (!Subtarget->is64Bit() &&
3545         ((!isa<GlobalAddressSDNode>(Callee) &&
3546           !isa<ExternalSymbolSDNode>(Callee)) ||
3547          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3548       unsigned NumInRegs = 0;
3549       // In PIC we need an extra register to formulate the address computation
3550       // for the callee.
3551       unsigned MaxInRegs =
3552         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3553
3554       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3555         CCValAssign &VA = ArgLocs[i];
3556         if (!VA.isRegLoc())
3557           continue;
3558         unsigned Reg = VA.getLocReg();
3559         switch (Reg) {
3560         default: break;
3561         case X86::EAX: case X86::EDX: case X86::ECX:
3562           if (++NumInRegs == MaxInRegs)
3563             return false;
3564           break;
3565         }
3566       }
3567     }
3568   }
3569
3570   return true;
3571 }
3572
3573 FastISel *
3574 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3575                                   const TargetLibraryInfo *libInfo) const {
3576   return X86::createFastISel(funcInfo, libInfo);
3577 }
3578
3579 //===----------------------------------------------------------------------===//
3580 //                           Other Lowering Hooks
3581 //===----------------------------------------------------------------------===//
3582
3583 static bool MayFoldLoad(SDValue Op) {
3584   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3585 }
3586
3587 static bool MayFoldIntoStore(SDValue Op) {
3588   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3589 }
3590
3591 static bool isTargetShuffle(unsigned Opcode) {
3592   switch(Opcode) {
3593   default: return false;
3594   case X86ISD::BLENDI:
3595   case X86ISD::PSHUFB:
3596   case X86ISD::PSHUFD:
3597   case X86ISD::PSHUFHW:
3598   case X86ISD::PSHUFLW:
3599   case X86ISD::SHUFP:
3600   case X86ISD::PALIGNR:
3601   case X86ISD::MOVLHPS:
3602   case X86ISD::MOVLHPD:
3603   case X86ISD::MOVHLPS:
3604   case X86ISD::MOVLPS:
3605   case X86ISD::MOVLPD:
3606   case X86ISD::MOVSHDUP:
3607   case X86ISD::MOVSLDUP:
3608   case X86ISD::MOVDDUP:
3609   case X86ISD::MOVSS:
3610   case X86ISD::MOVSD:
3611   case X86ISD::UNPCKL:
3612   case X86ISD::UNPCKH:
3613   case X86ISD::VPERMILPI:
3614   case X86ISD::VPERM2X128:
3615   case X86ISD::VPERMI:
3616     return true;
3617   }
3618 }
3619
3620 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3621                                     SDValue V1, unsigned TargetMask,
3622                                     SelectionDAG &DAG) {
3623   switch(Opc) {
3624   default: llvm_unreachable("Unknown x86 shuffle node");
3625   case X86ISD::PSHUFD:
3626   case X86ISD::PSHUFHW:
3627   case X86ISD::PSHUFLW:
3628   case X86ISD::VPERMILPI:
3629   case X86ISD::VPERMI:
3630     return DAG.getNode(Opc, dl, VT, V1,
3631                        DAG.getConstant(TargetMask, dl, MVT::i8));
3632   }
3633 }
3634
3635 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3636                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3637   switch(Opc) {
3638   default: llvm_unreachable("Unknown x86 shuffle node");
3639   case X86ISD::MOVLHPS:
3640   case X86ISD::MOVLHPD:
3641   case X86ISD::MOVHLPS:
3642   case X86ISD::MOVLPS:
3643   case X86ISD::MOVLPD:
3644   case X86ISD::MOVSS:
3645   case X86ISD::MOVSD:
3646   case X86ISD::UNPCKL:
3647   case X86ISD::UNPCKH:
3648     return DAG.getNode(Opc, dl, VT, V1, V2);
3649   }
3650 }
3651
3652 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3653   MachineFunction &MF = DAG.getMachineFunction();
3654   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3655   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3656   int ReturnAddrIndex = FuncInfo->getRAIndex();
3657
3658   if (ReturnAddrIndex == 0) {
3659     // Set up a frame object for the return address.
3660     unsigned SlotSize = RegInfo->getSlotSize();
3661     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3662                                                            -(int64_t)SlotSize,
3663                                                            false);
3664     FuncInfo->setRAIndex(ReturnAddrIndex);
3665   }
3666
3667   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3668 }
3669
3670 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3671                                        bool hasSymbolicDisplacement) {
3672   // Offset should fit into 32 bit immediate field.
3673   if (!isInt<32>(Offset))
3674     return false;
3675
3676   // If we don't have a symbolic displacement - we don't have any extra
3677   // restrictions.
3678   if (!hasSymbolicDisplacement)
3679     return true;
3680
3681   // FIXME: Some tweaks might be needed for medium code model.
3682   if (M != CodeModel::Small && M != CodeModel::Kernel)
3683     return false;
3684
3685   // For small code model we assume that latest object is 16MB before end of 31
3686   // bits boundary. We may also accept pretty large negative constants knowing
3687   // that all objects are in the positive half of address space.
3688   if (M == CodeModel::Small && Offset < 16*1024*1024)
3689     return true;
3690
3691   // For kernel code model we know that all object resist in the negative half
3692   // of 32bits address space. We may not accept negative offsets, since they may
3693   // be just off and we may accept pretty large positive ones.
3694   if (M == CodeModel::Kernel && Offset >= 0)
3695     return true;
3696
3697   return false;
3698 }
3699
3700 /// isCalleePop - Determines whether the callee is required to pop its
3701 /// own arguments. Callee pop is necessary to support tail calls.
3702 bool X86::isCalleePop(CallingConv::ID CallingConv,
3703                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3704   switch (CallingConv) {
3705   default:
3706     return false;
3707   case CallingConv::X86_StdCall:
3708   case CallingConv::X86_FastCall:
3709   case CallingConv::X86_ThisCall:
3710     return !is64Bit;
3711   case CallingConv::Fast:
3712   case CallingConv::GHC:
3713   case CallingConv::HiPE:
3714     if (IsVarArg)
3715       return false;
3716     return TailCallOpt;
3717   }
3718 }
3719
3720 /// \brief Return true if the condition is an unsigned comparison operation.
3721 static bool isX86CCUnsigned(unsigned X86CC) {
3722   switch (X86CC) {
3723   default: llvm_unreachable("Invalid integer condition!");
3724   case X86::COND_E:     return true;
3725   case X86::COND_G:     return false;
3726   case X86::COND_GE:    return false;
3727   case X86::COND_L:     return false;
3728   case X86::COND_LE:    return false;
3729   case X86::COND_NE:    return true;
3730   case X86::COND_B:     return true;
3731   case X86::COND_A:     return true;
3732   case X86::COND_BE:    return true;
3733   case X86::COND_AE:    return true;
3734   }
3735   llvm_unreachable("covered switch fell through?!");
3736 }
3737
3738 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3739 /// specific condition code, returning the condition code and the LHS/RHS of the
3740 /// comparison to make.
3741 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3742                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3743   if (!isFP) {
3744     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3745       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3746         // X > -1   -> X == 0, jump !sign.
3747         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3748         return X86::COND_NS;
3749       }
3750       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3751         // X < 0   -> X == 0, jump on sign.
3752         return X86::COND_S;
3753       }
3754       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3755         // X < 1   -> X <= 0
3756         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3757         return X86::COND_LE;
3758       }
3759     }
3760
3761     switch (SetCCOpcode) {
3762     default: llvm_unreachable("Invalid integer condition!");
3763     case ISD::SETEQ:  return X86::COND_E;
3764     case ISD::SETGT:  return X86::COND_G;
3765     case ISD::SETGE:  return X86::COND_GE;
3766     case ISD::SETLT:  return X86::COND_L;
3767     case ISD::SETLE:  return X86::COND_LE;
3768     case ISD::SETNE:  return X86::COND_NE;
3769     case ISD::SETULT: return X86::COND_B;
3770     case ISD::SETUGT: return X86::COND_A;
3771     case ISD::SETULE: return X86::COND_BE;
3772     case ISD::SETUGE: return X86::COND_AE;
3773     }
3774   }
3775
3776   // First determine if it is required or is profitable to flip the operands.
3777
3778   // If LHS is a foldable load, but RHS is not, flip the condition.
3779   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3780       !ISD::isNON_EXTLoad(RHS.getNode())) {
3781     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3782     std::swap(LHS, RHS);
3783   }
3784
3785   switch (SetCCOpcode) {
3786   default: break;
3787   case ISD::SETOLT:
3788   case ISD::SETOLE:
3789   case ISD::SETUGT:
3790   case ISD::SETUGE:
3791     std::swap(LHS, RHS);
3792     break;
3793   }
3794
3795   // On a floating point condition, the flags are set as follows:
3796   // ZF  PF  CF   op
3797   //  0 | 0 | 0 | X > Y
3798   //  0 | 0 | 1 | X < Y
3799   //  1 | 0 | 0 | X == Y
3800   //  1 | 1 | 1 | unordered
3801   switch (SetCCOpcode) {
3802   default: llvm_unreachable("Condcode should be pre-legalized away");
3803   case ISD::SETUEQ:
3804   case ISD::SETEQ:   return X86::COND_E;
3805   case ISD::SETOLT:              // flipped
3806   case ISD::SETOGT:
3807   case ISD::SETGT:   return X86::COND_A;
3808   case ISD::SETOLE:              // flipped
3809   case ISD::SETOGE:
3810   case ISD::SETGE:   return X86::COND_AE;
3811   case ISD::SETUGT:              // flipped
3812   case ISD::SETULT:
3813   case ISD::SETLT:   return X86::COND_B;
3814   case ISD::SETUGE:              // flipped
3815   case ISD::SETULE:
3816   case ISD::SETLE:   return X86::COND_BE;
3817   case ISD::SETONE:
3818   case ISD::SETNE:   return X86::COND_NE;
3819   case ISD::SETUO:   return X86::COND_P;
3820   case ISD::SETO:    return X86::COND_NP;
3821   case ISD::SETOEQ:
3822   case ISD::SETUNE:  return X86::COND_INVALID;
3823   }
3824 }
3825
3826 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3827 /// code. Current x86 isa includes the following FP cmov instructions:
3828 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3829 static bool hasFPCMov(unsigned X86CC) {
3830   switch (X86CC) {
3831   default:
3832     return false;
3833   case X86::COND_B:
3834   case X86::COND_BE:
3835   case X86::COND_E:
3836   case X86::COND_P:
3837   case X86::COND_A:
3838   case X86::COND_AE:
3839   case X86::COND_NE:
3840   case X86::COND_NP:
3841     return true;
3842   }
3843 }
3844
3845 /// isFPImmLegal - Returns true if the target can instruction select the
3846 /// specified FP immediate natively. If false, the legalizer will
3847 /// materialize the FP immediate as a load from a constant pool.
3848 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3849   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3850     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3851       return true;
3852   }
3853   return false;
3854 }
3855
3856 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3857                                               ISD::LoadExtType ExtTy,
3858                                               EVT NewVT) const {
3859   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3860   // relocation target a movq or addq instruction: don't let the load shrink.
3861   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3862   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3863     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3864       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3865   return true;
3866 }
3867
3868 /// \brief Returns true if it is beneficial to convert a load of a constant
3869 /// to just the constant itself.
3870 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3871                                                           Type *Ty) const {
3872   assert(Ty->isIntegerTy());
3873
3874   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3875   if (BitSize == 0 || BitSize > 64)
3876     return false;
3877   return true;
3878 }
3879
3880 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3881                                                 unsigned Index) const {
3882   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3883     return false;
3884
3885   return (Index == 0 || Index == ResVT.getVectorNumElements());
3886 }
3887
3888 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3889   // Speculate cttz only if we can directly use TZCNT.
3890   return Subtarget->hasBMI();
3891 }
3892
3893 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3894   // Speculate ctlz only if we can directly use LZCNT.
3895   return Subtarget->hasLZCNT();
3896 }
3897
3898 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3899 /// the specified range (L, H].
3900 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3901   return (Val < 0) || (Val >= Low && Val < Hi);
3902 }
3903
3904 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3905 /// specified value.
3906 static bool isUndefOrEqual(int Val, int CmpVal) {
3907   return (Val < 0 || Val == CmpVal);
3908 }
3909
3910 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3911 /// from position Pos and ending in Pos+Size, falls within the specified
3912 /// sequential range (Low, Low+Size]. or is undef.
3913 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3914                                        unsigned Pos, unsigned Size, int Low) {
3915   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3916     if (!isUndefOrEqual(Mask[i], Low))
3917       return false;
3918   return true;
3919 }
3920
3921 /// isVEXTRACTIndex - Return true if the specified
3922 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3923 /// suitable for instruction that extract 128 or 256 bit vectors
3924 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3925   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3926   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3927     return false;
3928
3929   // The index should be aligned on a vecWidth-bit boundary.
3930   uint64_t Index =
3931     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3932
3933   MVT VT = N->getSimpleValueType(0);
3934   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3935   bool Result = (Index * ElSize) % vecWidth == 0;
3936
3937   return Result;
3938 }
3939
3940 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3941 /// operand specifies a subvector insert that is suitable for input to
3942 /// insertion of 128 or 256-bit subvectors
3943 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3944   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3945   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3946     return false;
3947   // The index should be aligned on a vecWidth-bit boundary.
3948   uint64_t Index =
3949     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3950
3951   MVT VT = N->getSimpleValueType(0);
3952   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3953   bool Result = (Index * ElSize) % vecWidth == 0;
3954
3955   return Result;
3956 }
3957
3958 bool X86::isVINSERT128Index(SDNode *N) {
3959   return isVINSERTIndex(N, 128);
3960 }
3961
3962 bool X86::isVINSERT256Index(SDNode *N) {
3963   return isVINSERTIndex(N, 256);
3964 }
3965
3966 bool X86::isVEXTRACT128Index(SDNode *N) {
3967   return isVEXTRACTIndex(N, 128);
3968 }
3969
3970 bool X86::isVEXTRACT256Index(SDNode *N) {
3971   return isVEXTRACTIndex(N, 256);
3972 }
3973
3974 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3975   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3976   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3977     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3978
3979   uint64_t Index =
3980     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3981
3982   MVT VecVT = N->getOperand(0).getSimpleValueType();
3983   MVT ElVT = VecVT.getVectorElementType();
3984
3985   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3986   return Index / NumElemsPerChunk;
3987 }
3988
3989 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3990   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3991   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3992     llvm_unreachable("Illegal insert subvector for VINSERT");
3993
3994   uint64_t Index =
3995     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3996
3997   MVT VecVT = N->getSimpleValueType(0);
3998   MVT ElVT = VecVT.getVectorElementType();
3999
4000   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4001   return Index / NumElemsPerChunk;
4002 }
4003
4004 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4005 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4006 /// and VINSERTI128 instructions.
4007 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4008   return getExtractVEXTRACTImmediate(N, 128);
4009 }
4010
4011 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4012 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4013 /// and VINSERTI64x4 instructions.
4014 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4015   return getExtractVEXTRACTImmediate(N, 256);
4016 }
4017
4018 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4019 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4020 /// and VINSERTI128 instructions.
4021 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4022   return getInsertVINSERTImmediate(N, 128);
4023 }
4024
4025 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4026 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4027 /// and VINSERTI64x4 instructions.
4028 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4029   return getInsertVINSERTImmediate(N, 256);
4030 }
4031
4032 /// isZero - Returns true if Elt is a constant integer zero
4033 static bool isZero(SDValue V) {
4034   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4035   return C && C->isNullValue();
4036 }
4037
4038 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4039 /// constant +0.0.
4040 bool X86::isZeroNode(SDValue Elt) {
4041   if (isZero(Elt))
4042     return true;
4043   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4044     return CFP->getValueAPF().isPosZero();
4045   return false;
4046 }
4047
4048 /// getZeroVector - Returns a vector of specified type with all zero elements.
4049 ///
4050 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4051                              SelectionDAG &DAG, SDLoc dl) {
4052   assert(VT.isVector() && "Expected a vector type");
4053
4054   // Always build SSE zero vectors as <4 x i32> bitcasted
4055   // to their dest type. This ensures they get CSE'd.
4056   SDValue Vec;
4057   if (VT.is128BitVector()) {  // SSE
4058     if (Subtarget->hasSSE2()) {  // SSE2
4059       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4060       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4061     } else { // SSE1
4062       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4063       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4064     }
4065   } else if (VT.is256BitVector()) { // AVX
4066     if (Subtarget->hasInt256()) { // AVX2
4067       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4068       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4069       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4070     } else {
4071       // 256-bit logic and arithmetic instructions in AVX are all
4072       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4073       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4074       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4075       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4076     }
4077   } else if (VT.is512BitVector()) { // AVX-512
4078       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4079       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4080                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4081       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4082   } else if (VT.getScalarType() == MVT::i1) {
4083
4084     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4085             && "Unexpected vector type");
4086     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4087             && "Unexpected vector type");
4088     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4089     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4090     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4091   } else
4092     llvm_unreachable("Unexpected vector type");
4093
4094   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4095 }
4096
4097 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4098                                 SelectionDAG &DAG, SDLoc dl,
4099                                 unsigned vectorWidth) {
4100   assert((vectorWidth == 128 || vectorWidth == 256) &&
4101          "Unsupported vector width");
4102   EVT VT = Vec.getValueType();
4103   EVT ElVT = VT.getVectorElementType();
4104   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4105   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4106                                   VT.getVectorNumElements()/Factor);
4107
4108   // Extract from UNDEF is UNDEF.
4109   if (Vec.getOpcode() == ISD::UNDEF)
4110     return DAG.getUNDEF(ResultVT);
4111
4112   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4113   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4114
4115   // This is the index of the first element of the vectorWidth-bit chunk
4116   // we want.
4117   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4118                                * ElemsPerChunk);
4119
4120   // If the input is a buildvector just emit a smaller one.
4121   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4122     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4123                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4124                                     ElemsPerChunk));
4125
4126   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4127   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4128 }
4129
4130 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4131 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4132 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4133 /// instructions or a simple subregister reference. Idx is an index in the
4134 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4135 /// lowering EXTRACT_VECTOR_ELT operations easier.
4136 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4137                                    SelectionDAG &DAG, SDLoc dl) {
4138   assert((Vec.getValueType().is256BitVector() ||
4139           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4140   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4141 }
4142
4143 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4144 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4145                                    SelectionDAG &DAG, SDLoc dl) {
4146   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4147   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4148 }
4149
4150 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4151                                unsigned IdxVal, SelectionDAG &DAG,
4152                                SDLoc dl, unsigned vectorWidth) {
4153   assert((vectorWidth == 128 || vectorWidth == 256) &&
4154          "Unsupported vector width");
4155   // Inserting UNDEF is Result
4156   if (Vec.getOpcode() == ISD::UNDEF)
4157     return Result;
4158   EVT VT = Vec.getValueType();
4159   EVT ElVT = VT.getVectorElementType();
4160   EVT ResultVT = Result.getValueType();
4161
4162   // Insert the relevant vectorWidth bits.
4163   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4164
4165   // This is the index of the first element of the vectorWidth-bit chunk
4166   // we want.
4167   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4168                                * ElemsPerChunk);
4169
4170   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4171   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4172 }
4173
4174 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4175 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4176 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4177 /// simple superregister reference.  Idx is an index in the 128 bits
4178 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4179 /// lowering INSERT_VECTOR_ELT operations easier.
4180 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4181                                   SelectionDAG &DAG, SDLoc dl) {
4182   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4183
4184   // For insertion into the zero index (low half) of a 256-bit vector, it is
4185   // more efficient to generate a blend with immediate instead of an insert*128.
4186   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4187   // extend the subvector to the size of the result vector. Make sure that
4188   // we are not recursing on that node by checking for undef here.
4189   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4190       Result.getOpcode() != ISD::UNDEF) {
4191     EVT ResultVT = Result.getValueType();
4192     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4193     SDValue Undef = DAG.getUNDEF(ResultVT);
4194     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4195                                  Vec, ZeroIndex);
4196
4197     // The blend instruction, and therefore its mask, depend on the data type.
4198     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4199     if (ScalarType.isFloatingPoint()) {
4200       // Choose either vblendps (float) or vblendpd (double).
4201       unsigned ScalarSize = ScalarType.getSizeInBits();
4202       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4203       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4204       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4205       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4206     }
4207
4208     const X86Subtarget &Subtarget =
4209     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4210
4211     // AVX2 is needed for 256-bit integer blend support.
4212     // Integers must be cast to 32-bit because there is only vpblendd;
4213     // vpblendw can't be used for this because it has a handicapped mask.
4214
4215     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4216     // is still more efficient than using the wrong domain vinsertf128 that
4217     // will be created by InsertSubVector().
4218     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4219
4220     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4221     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4222     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4223     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4224   }
4225
4226   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4227 }
4228
4229 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4230                                   SelectionDAG &DAG, SDLoc dl) {
4231   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4232   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4233 }
4234
4235 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4236 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4237 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4238 /// large BUILD_VECTORS.
4239 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4240                                    unsigned NumElems, SelectionDAG &DAG,
4241                                    SDLoc dl) {
4242   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4243   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4244 }
4245
4246 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4247                                    unsigned NumElems, SelectionDAG &DAG,
4248                                    SDLoc dl) {
4249   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4250   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4251 }
4252
4253 /// getOnesVector - Returns a vector of specified type with all bits set.
4254 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4255 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4256 /// Then bitcast to their original type, ensuring they get CSE'd.
4257 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4258                              SDLoc dl) {
4259   assert(VT.isVector() && "Expected a vector type");
4260
4261   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4262   SDValue Vec;
4263   if (VT.is256BitVector()) {
4264     if (HasInt256) { // AVX2
4265       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4266       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4267     } else { // AVX
4268       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4269       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4270     }
4271   } else if (VT.is128BitVector()) {
4272     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4273   } else
4274     llvm_unreachable("Unexpected vector type");
4275
4276   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4277 }
4278
4279 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4280 /// operation of specified width.
4281 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4282                        SDValue V2) {
4283   unsigned NumElems = VT.getVectorNumElements();
4284   SmallVector<int, 8> Mask;
4285   Mask.push_back(NumElems);
4286   for (unsigned i = 1; i != NumElems; ++i)
4287     Mask.push_back(i);
4288   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4289 }
4290
4291 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4292 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4293                           SDValue V2) {
4294   unsigned NumElems = VT.getVectorNumElements();
4295   SmallVector<int, 8> Mask;
4296   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4297     Mask.push_back(i);
4298     Mask.push_back(i + NumElems);
4299   }
4300   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4301 }
4302
4303 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4304 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4305                           SDValue V2) {
4306   unsigned NumElems = VT.getVectorNumElements();
4307   SmallVector<int, 8> Mask;
4308   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4309     Mask.push_back(i + Half);
4310     Mask.push_back(i + NumElems + Half);
4311   }
4312   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4313 }
4314
4315 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4316 /// vector of zero or undef vector.  This produces a shuffle where the low
4317 /// element of V2 is swizzled into the zero/undef vector, landing at element
4318 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4319 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4320                                            bool IsZero,
4321                                            const X86Subtarget *Subtarget,
4322                                            SelectionDAG &DAG) {
4323   MVT VT = V2.getSimpleValueType();
4324   SDValue V1 = IsZero
4325     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4326   unsigned NumElems = VT.getVectorNumElements();
4327   SmallVector<int, 16> MaskVec;
4328   for (unsigned i = 0; i != NumElems; ++i)
4329     // If this is the insertion idx, put the low elt of V2 here.
4330     MaskVec.push_back(i == Idx ? NumElems : i);
4331   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4332 }
4333
4334 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4335 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4336 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4337 /// shuffles which use a single input multiple times, and in those cases it will
4338 /// adjust the mask to only have indices within that single input.
4339 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4340                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4341   unsigned NumElems = VT.getVectorNumElements();
4342   SDValue ImmN;
4343
4344   IsUnary = false;
4345   bool IsFakeUnary = false;
4346   switch(N->getOpcode()) {
4347   case X86ISD::BLENDI:
4348     ImmN = N->getOperand(N->getNumOperands()-1);
4349     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4350     break;
4351   case X86ISD::SHUFP:
4352     ImmN = N->getOperand(N->getNumOperands()-1);
4353     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4354     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4355     break;
4356   case X86ISD::UNPCKH:
4357     DecodeUNPCKHMask(VT, Mask);
4358     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4359     break;
4360   case X86ISD::UNPCKL:
4361     DecodeUNPCKLMask(VT, Mask);
4362     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4363     break;
4364   case X86ISD::MOVHLPS:
4365     DecodeMOVHLPSMask(NumElems, Mask);
4366     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4367     break;
4368   case X86ISD::MOVLHPS:
4369     DecodeMOVLHPSMask(NumElems, Mask);
4370     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4371     break;
4372   case X86ISD::PALIGNR:
4373     ImmN = N->getOperand(N->getNumOperands()-1);
4374     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4375     break;
4376   case X86ISD::PSHUFD:
4377   case X86ISD::VPERMILPI:
4378     ImmN = N->getOperand(N->getNumOperands()-1);
4379     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4380     IsUnary = true;
4381     break;
4382   case X86ISD::PSHUFHW:
4383     ImmN = N->getOperand(N->getNumOperands()-1);
4384     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4385     IsUnary = true;
4386     break;
4387   case X86ISD::PSHUFLW:
4388     ImmN = N->getOperand(N->getNumOperands()-1);
4389     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4390     IsUnary = true;
4391     break;
4392   case X86ISD::PSHUFB: {
4393     IsUnary = true;
4394     SDValue MaskNode = N->getOperand(1);
4395     while (MaskNode->getOpcode() == ISD::BITCAST)
4396       MaskNode = MaskNode->getOperand(0);
4397
4398     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4399       // If we have a build-vector, then things are easy.
4400       EVT VT = MaskNode.getValueType();
4401       assert(VT.isVector() &&
4402              "Can't produce a non-vector with a build_vector!");
4403       if (!VT.isInteger())
4404         return false;
4405
4406       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4407
4408       SmallVector<uint64_t, 32> RawMask;
4409       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4410         SDValue Op = MaskNode->getOperand(i);
4411         if (Op->getOpcode() == ISD::UNDEF) {
4412           RawMask.push_back((uint64_t)SM_SentinelUndef);
4413           continue;
4414         }
4415         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4416         if (!CN)
4417           return false;
4418         APInt MaskElement = CN->getAPIntValue();
4419
4420         // We now have to decode the element which could be any integer size and
4421         // extract each byte of it.
4422         for (int j = 0; j < NumBytesPerElement; ++j) {
4423           // Note that this is x86 and so always little endian: the low byte is
4424           // the first byte of the mask.
4425           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4426           MaskElement = MaskElement.lshr(8);
4427         }
4428       }
4429       DecodePSHUFBMask(RawMask, Mask);
4430       break;
4431     }
4432
4433     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4434     if (!MaskLoad)
4435       return false;
4436
4437     SDValue Ptr = MaskLoad->getBasePtr();
4438     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4439         Ptr->getOpcode() == X86ISD::WrapperRIP)
4440       Ptr = Ptr->getOperand(0);
4441
4442     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4443     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4444       return false;
4445
4446     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4447       DecodePSHUFBMask(C, Mask);
4448       if (Mask.empty())
4449         return false;
4450       break;
4451     }
4452
4453     return false;
4454   }
4455   case X86ISD::VPERMI:
4456     ImmN = N->getOperand(N->getNumOperands()-1);
4457     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4458     IsUnary = true;
4459     break;
4460   case X86ISD::MOVSS:
4461   case X86ISD::MOVSD:
4462     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4463     break;
4464   case X86ISD::VPERM2X128:
4465     ImmN = N->getOperand(N->getNumOperands()-1);
4466     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4467     if (Mask.empty()) return false;
4468     break;
4469   case X86ISD::MOVSLDUP:
4470     DecodeMOVSLDUPMask(VT, Mask);
4471     IsUnary = true;
4472     break;
4473   case X86ISD::MOVSHDUP:
4474     DecodeMOVSHDUPMask(VT, Mask);
4475     IsUnary = true;
4476     break;
4477   case X86ISD::MOVDDUP:
4478     DecodeMOVDDUPMask(VT, Mask);
4479     IsUnary = true;
4480     break;
4481   case X86ISD::MOVLHPD:
4482   case X86ISD::MOVLPD:
4483   case X86ISD::MOVLPS:
4484     // Not yet implemented
4485     return false;
4486   default: llvm_unreachable("unknown target shuffle node");
4487   }
4488
4489   // If we have a fake unary shuffle, the shuffle mask is spread across two
4490   // inputs that are actually the same node. Re-map the mask to always point
4491   // into the first input.
4492   if (IsFakeUnary)
4493     for (int &M : Mask)
4494       if (M >= (int)Mask.size())
4495         M -= Mask.size();
4496
4497   return true;
4498 }
4499
4500 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4501 /// element of the result of the vector shuffle.
4502 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4503                                    unsigned Depth) {
4504   if (Depth == 6)
4505     return SDValue();  // Limit search depth.
4506
4507   SDValue V = SDValue(N, 0);
4508   EVT VT = V.getValueType();
4509   unsigned Opcode = V.getOpcode();
4510
4511   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4512   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4513     int Elt = SV->getMaskElt(Index);
4514
4515     if (Elt < 0)
4516       return DAG.getUNDEF(VT.getVectorElementType());
4517
4518     unsigned NumElems = VT.getVectorNumElements();
4519     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4520                                          : SV->getOperand(1);
4521     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4522   }
4523
4524   // Recurse into target specific vector shuffles to find scalars.
4525   if (isTargetShuffle(Opcode)) {
4526     MVT ShufVT = V.getSimpleValueType();
4527     unsigned NumElems = ShufVT.getVectorNumElements();
4528     SmallVector<int, 16> ShuffleMask;
4529     bool IsUnary;
4530
4531     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4532       return SDValue();
4533
4534     int Elt = ShuffleMask[Index];
4535     if (Elt < 0)
4536       return DAG.getUNDEF(ShufVT.getVectorElementType());
4537
4538     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4539                                          : N->getOperand(1);
4540     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4541                                Depth+1);
4542   }
4543
4544   // Actual nodes that may contain scalar elements
4545   if (Opcode == ISD::BITCAST) {
4546     V = V.getOperand(0);
4547     EVT SrcVT = V.getValueType();
4548     unsigned NumElems = VT.getVectorNumElements();
4549
4550     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4551       return SDValue();
4552   }
4553
4554   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4555     return (Index == 0) ? V.getOperand(0)
4556                         : DAG.getUNDEF(VT.getVectorElementType());
4557
4558   if (V.getOpcode() == ISD::BUILD_VECTOR)
4559     return V.getOperand(Index);
4560
4561   return SDValue();
4562 }
4563
4564 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4565 ///
4566 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4567                                        unsigned NumNonZero, unsigned NumZero,
4568                                        SelectionDAG &DAG,
4569                                        const X86Subtarget* Subtarget,
4570                                        const TargetLowering &TLI) {
4571   if (NumNonZero > 8)
4572     return SDValue();
4573
4574   SDLoc dl(Op);
4575   SDValue V;
4576   bool First = true;
4577
4578   // SSE4.1 - use PINSRB to insert each byte directly.
4579   if (Subtarget->hasSSE41()) {
4580     for (unsigned i = 0; i < 16; ++i) {
4581       bool isNonZero = (NonZeros & (1 << i)) != 0;
4582       if (isNonZero) {
4583         if (First) {
4584           if (NumZero)
4585             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4586           else
4587             V = DAG.getUNDEF(MVT::v16i8);
4588           First = false;
4589         }
4590         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4591                         MVT::v16i8, V, Op.getOperand(i),
4592                         DAG.getIntPtrConstant(i, dl));
4593       }
4594     }
4595
4596     return V;
4597   }
4598
4599   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4600   for (unsigned i = 0; i < 16; ++i) {
4601     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4602     if (ThisIsNonZero && First) {
4603       if (NumZero)
4604         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4605       else
4606         V = DAG.getUNDEF(MVT::v8i16);
4607       First = false;
4608     }
4609
4610     if ((i & 1) != 0) {
4611       SDValue ThisElt, LastElt;
4612       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4613       if (LastIsNonZero) {
4614         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4615                               MVT::i16, Op.getOperand(i-1));
4616       }
4617       if (ThisIsNonZero) {
4618         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4619         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4620                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4621         if (LastIsNonZero)
4622           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4623       } else
4624         ThisElt = LastElt;
4625
4626       if (ThisElt.getNode())
4627         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4628                         DAG.getIntPtrConstant(i/2, dl));
4629     }
4630   }
4631
4632   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4633 }
4634
4635 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4636 ///
4637 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4638                                      unsigned NumNonZero, unsigned NumZero,
4639                                      SelectionDAG &DAG,
4640                                      const X86Subtarget* Subtarget,
4641                                      const TargetLowering &TLI) {
4642   if (NumNonZero > 4)
4643     return SDValue();
4644
4645   SDLoc dl(Op);
4646   SDValue V;
4647   bool First = true;
4648   for (unsigned i = 0; i < 8; ++i) {
4649     bool isNonZero = (NonZeros & (1 << i)) != 0;
4650     if (isNonZero) {
4651       if (First) {
4652         if (NumZero)
4653           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4654         else
4655           V = DAG.getUNDEF(MVT::v8i16);
4656         First = false;
4657       }
4658       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4659                       MVT::v8i16, V, Op.getOperand(i),
4660                       DAG.getIntPtrConstant(i, dl));
4661     }
4662   }
4663
4664   return V;
4665 }
4666
4667 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4668 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4669                                      const X86Subtarget *Subtarget,
4670                                      const TargetLowering &TLI) {
4671   // Find all zeroable elements.
4672   std::bitset<4> Zeroable;
4673   for (int i=0; i < 4; ++i) {
4674     SDValue Elt = Op->getOperand(i);
4675     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4676   }
4677   assert(Zeroable.size() - Zeroable.count() > 1 &&
4678          "We expect at least two non-zero elements!");
4679
4680   // We only know how to deal with build_vector nodes where elements are either
4681   // zeroable or extract_vector_elt with constant index.
4682   SDValue FirstNonZero;
4683   unsigned FirstNonZeroIdx;
4684   for (unsigned i=0; i < 4; ++i) {
4685     if (Zeroable[i])
4686       continue;
4687     SDValue Elt = Op->getOperand(i);
4688     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4689         !isa<ConstantSDNode>(Elt.getOperand(1)))
4690       return SDValue();
4691     // Make sure that this node is extracting from a 128-bit vector.
4692     MVT VT = Elt.getOperand(0).getSimpleValueType();
4693     if (!VT.is128BitVector())
4694       return SDValue();
4695     if (!FirstNonZero.getNode()) {
4696       FirstNonZero = Elt;
4697       FirstNonZeroIdx = i;
4698     }
4699   }
4700
4701   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4702   SDValue V1 = FirstNonZero.getOperand(0);
4703   MVT VT = V1.getSimpleValueType();
4704
4705   // See if this build_vector can be lowered as a blend with zero.
4706   SDValue Elt;
4707   unsigned EltMaskIdx, EltIdx;
4708   int Mask[4];
4709   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4710     if (Zeroable[EltIdx]) {
4711       // The zero vector will be on the right hand side.
4712       Mask[EltIdx] = EltIdx+4;
4713       continue;
4714     }
4715
4716     Elt = Op->getOperand(EltIdx);
4717     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4718     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4719     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4720       break;
4721     Mask[EltIdx] = EltIdx;
4722   }
4723
4724   if (EltIdx == 4) {
4725     // Let the shuffle legalizer deal with blend operations.
4726     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4727     if (V1.getSimpleValueType() != VT)
4728       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4729     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4730   }
4731
4732   // See if we can lower this build_vector to a INSERTPS.
4733   if (!Subtarget->hasSSE41())
4734     return SDValue();
4735
4736   SDValue V2 = Elt.getOperand(0);
4737   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4738     V1 = SDValue();
4739
4740   bool CanFold = true;
4741   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4742     if (Zeroable[i])
4743       continue;
4744
4745     SDValue Current = Op->getOperand(i);
4746     SDValue SrcVector = Current->getOperand(0);
4747     if (!V1.getNode())
4748       V1 = SrcVector;
4749     CanFold = SrcVector == V1 &&
4750       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4751   }
4752
4753   if (!CanFold)
4754     return SDValue();
4755
4756   assert(V1.getNode() && "Expected at least two non-zero elements!");
4757   if (V1.getSimpleValueType() != MVT::v4f32)
4758     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4759   if (V2.getSimpleValueType() != MVT::v4f32)
4760     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4761
4762   // Ok, we can emit an INSERTPS instruction.
4763   unsigned ZMask = Zeroable.to_ulong();
4764
4765   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4766   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4767   SDLoc DL(Op);
4768   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4769                                DAG.getIntPtrConstant(InsertPSMask, DL));
4770   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4771 }
4772
4773 /// Return a vector logical shift node.
4774 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4775                          unsigned NumBits, SelectionDAG &DAG,
4776                          const TargetLowering &TLI, SDLoc dl) {
4777   assert(VT.is128BitVector() && "Unknown type for VShift");
4778   MVT ShVT = MVT::v2i64;
4779   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4780   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4781   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4782   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4783   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4784   return DAG.getNode(ISD::BITCAST, dl, VT,
4785                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4786 }
4787
4788 static SDValue
4789 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4790
4791   // Check if the scalar load can be widened into a vector load. And if
4792   // the address is "base + cst" see if the cst can be "absorbed" into
4793   // the shuffle mask.
4794   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4795     SDValue Ptr = LD->getBasePtr();
4796     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4797       return SDValue();
4798     EVT PVT = LD->getValueType(0);
4799     if (PVT != MVT::i32 && PVT != MVT::f32)
4800       return SDValue();
4801
4802     int FI = -1;
4803     int64_t Offset = 0;
4804     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4805       FI = FINode->getIndex();
4806       Offset = 0;
4807     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4808                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4809       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4810       Offset = Ptr.getConstantOperandVal(1);
4811       Ptr = Ptr.getOperand(0);
4812     } else {
4813       return SDValue();
4814     }
4815
4816     // FIXME: 256-bit vector instructions don't require a strict alignment,
4817     // improve this code to support it better.
4818     unsigned RequiredAlign = VT.getSizeInBits()/8;
4819     SDValue Chain = LD->getChain();
4820     // Make sure the stack object alignment is at least 16 or 32.
4821     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4822     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4823       if (MFI->isFixedObjectIndex(FI)) {
4824         // Can't change the alignment. FIXME: It's possible to compute
4825         // the exact stack offset and reference FI + adjust offset instead.
4826         // If someone *really* cares about this. That's the way to implement it.
4827         return SDValue();
4828       } else {
4829         MFI->setObjectAlignment(FI, RequiredAlign);
4830       }
4831     }
4832
4833     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4834     // Ptr + (Offset & ~15).
4835     if (Offset < 0)
4836       return SDValue();
4837     if ((Offset % RequiredAlign) & 3)
4838       return SDValue();
4839     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4840     if (StartOffset) {
4841       SDLoc DL(Ptr);
4842       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4843                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4844     }
4845
4846     int EltNo = (Offset - StartOffset) >> 2;
4847     unsigned NumElems = VT.getVectorNumElements();
4848
4849     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4850     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4851                              LD->getPointerInfo().getWithOffset(StartOffset),
4852                              false, false, false, 0);
4853
4854     SmallVector<int, 8> Mask(NumElems, EltNo);
4855
4856     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4857   }
4858
4859   return SDValue();
4860 }
4861
4862 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4863 /// elements can be replaced by a single large load which has the same value as
4864 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4865 ///
4866 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4867 ///
4868 /// FIXME: we'd also like to handle the case where the last elements are zero
4869 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4870 /// There's even a handy isZeroNode for that purpose.
4871 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4872                                         SDLoc &DL, SelectionDAG &DAG,
4873                                         bool isAfterLegalize) {
4874   unsigned NumElems = Elts.size();
4875
4876   LoadSDNode *LDBase = nullptr;
4877   unsigned LastLoadedElt = -1U;
4878
4879   // For each element in the initializer, see if we've found a load or an undef.
4880   // If we don't find an initial load element, or later load elements are
4881   // non-consecutive, bail out.
4882   for (unsigned i = 0; i < NumElems; ++i) {
4883     SDValue Elt = Elts[i];
4884     // Look through a bitcast.
4885     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4886       Elt = Elt.getOperand(0);
4887     if (!Elt.getNode() ||
4888         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4889       return SDValue();
4890     if (!LDBase) {
4891       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4892         return SDValue();
4893       LDBase = cast<LoadSDNode>(Elt.getNode());
4894       LastLoadedElt = i;
4895       continue;
4896     }
4897     if (Elt.getOpcode() == ISD::UNDEF)
4898       continue;
4899
4900     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4901     EVT LdVT = Elt.getValueType();
4902     // Each loaded element must be the correct fractional portion of the
4903     // requested vector load.
4904     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4905       return SDValue();
4906     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4907       return SDValue();
4908     LastLoadedElt = i;
4909   }
4910
4911   // If we have found an entire vector of loads and undefs, then return a large
4912   // load of the entire vector width starting at the base pointer.  If we found
4913   // consecutive loads for the low half, generate a vzext_load node.
4914   if (LastLoadedElt == NumElems - 1) {
4915     assert(LDBase && "Did not find base load for merging consecutive loads");
4916     EVT EltVT = LDBase->getValueType(0);
4917     // Ensure that the input vector size for the merged loads matches the
4918     // cumulative size of the input elements.
4919     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4920       return SDValue();
4921
4922     if (isAfterLegalize &&
4923         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4924       return SDValue();
4925
4926     SDValue NewLd = SDValue();
4927
4928     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4929                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4930                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4931                         LDBase->getAlignment());
4932
4933     if (LDBase->hasAnyUseOfValue(1)) {
4934       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4935                                      SDValue(LDBase, 1),
4936                                      SDValue(NewLd.getNode(), 1));
4937       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4938       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4939                              SDValue(NewLd.getNode(), 1));
4940     }
4941
4942     return NewLd;
4943   }
4944
4945   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4946   //of a v4i32 / v4f32. It's probably worth generalizing.
4947   EVT EltVT = VT.getVectorElementType();
4948   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4949       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4950     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4951     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4952     SDValue ResNode =
4953         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4954                                 LDBase->getPointerInfo(),
4955                                 LDBase->getAlignment(),
4956                                 false/*isVolatile*/, true/*ReadMem*/,
4957                                 false/*WriteMem*/);
4958
4959     // Make sure the newly-created LOAD is in the same position as LDBase in
4960     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4961     // update uses of LDBase's output chain to use the TokenFactor.
4962     if (LDBase->hasAnyUseOfValue(1)) {
4963       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4964                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4965       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4966       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4967                              SDValue(ResNode.getNode(), 1));
4968     }
4969
4970     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4971   }
4972   return SDValue();
4973 }
4974
4975 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4976 /// to generate a splat value for the following cases:
4977 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4978 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4979 /// a scalar load, or a constant.
4980 /// The VBROADCAST node is returned when a pattern is found,
4981 /// or SDValue() otherwise.
4982 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4983                                     SelectionDAG &DAG) {
4984   // VBROADCAST requires AVX.
4985   // TODO: Splats could be generated for non-AVX CPUs using SSE
4986   // instructions, but there's less potential gain for only 128-bit vectors.
4987   if (!Subtarget->hasAVX())
4988     return SDValue();
4989
4990   MVT VT = Op.getSimpleValueType();
4991   SDLoc dl(Op);
4992
4993   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4994          "Unsupported vector type for broadcast.");
4995
4996   SDValue Ld;
4997   bool ConstSplatVal;
4998
4999   switch (Op.getOpcode()) {
5000     default:
5001       // Unknown pattern found.
5002       return SDValue();
5003
5004     case ISD::BUILD_VECTOR: {
5005       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5006       BitVector UndefElements;
5007       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5008
5009       // We need a splat of a single value to use broadcast, and it doesn't
5010       // make any sense if the value is only in one element of the vector.
5011       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5012         return SDValue();
5013
5014       Ld = Splat;
5015       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5016                        Ld.getOpcode() == ISD::ConstantFP);
5017
5018       // Make sure that all of the users of a non-constant load are from the
5019       // BUILD_VECTOR node.
5020       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5021         return SDValue();
5022       break;
5023     }
5024
5025     case ISD::VECTOR_SHUFFLE: {
5026       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5027
5028       // Shuffles must have a splat mask where the first element is
5029       // broadcasted.
5030       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5031         return SDValue();
5032
5033       SDValue Sc = Op.getOperand(0);
5034       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5035           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5036
5037         if (!Subtarget->hasInt256())
5038           return SDValue();
5039
5040         // Use the register form of the broadcast instruction available on AVX2.
5041         if (VT.getSizeInBits() >= 256)
5042           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5043         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5044       }
5045
5046       Ld = Sc.getOperand(0);
5047       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5048                        Ld.getOpcode() == ISD::ConstantFP);
5049
5050       // The scalar_to_vector node and the suspected
5051       // load node must have exactly one user.
5052       // Constants may have multiple users.
5053
5054       // AVX-512 has register version of the broadcast
5055       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5056         Ld.getValueType().getSizeInBits() >= 32;
5057       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5058           !hasRegVer))
5059         return SDValue();
5060       break;
5061     }
5062   }
5063
5064   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5065   bool IsGE256 = (VT.getSizeInBits() >= 256);
5066
5067   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5068   // instruction to save 8 or more bytes of constant pool data.
5069   // TODO: If multiple splats are generated to load the same constant,
5070   // it may be detrimental to overall size. There needs to be a way to detect
5071   // that condition to know if this is truly a size win.
5072   const Function *F = DAG.getMachineFunction().getFunction();
5073   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5074
5075   // Handle broadcasting a single constant scalar from the constant pool
5076   // into a vector.
5077   // On Sandybridge (no AVX2), it is still better to load a constant vector
5078   // from the constant pool and not to broadcast it from a scalar.
5079   // But override that restriction when optimizing for size.
5080   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5081   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5082     EVT CVT = Ld.getValueType();
5083     assert(!CVT.isVector() && "Must not broadcast a vector type");
5084
5085     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5086     // For size optimization, also splat v2f64 and v2i64, and for size opt
5087     // with AVX2, also splat i8 and i16.
5088     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5089     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5090         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5091       const Constant *C = nullptr;
5092       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5093         C = CI->getConstantIntValue();
5094       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5095         C = CF->getConstantFPValue();
5096
5097       assert(C && "Invalid constant type");
5098
5099       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5100       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5101       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5102       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5103                        MachinePointerInfo::getConstantPool(),
5104                        false, false, false, Alignment);
5105
5106       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5107     }
5108   }
5109
5110   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5111
5112   // Handle AVX2 in-register broadcasts.
5113   if (!IsLoad && Subtarget->hasInt256() &&
5114       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5115     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5116
5117   // The scalar source must be a normal load.
5118   if (!IsLoad)
5119     return SDValue();
5120
5121   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5122       (Subtarget->hasVLX() && ScalarSize == 64))
5123     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5124
5125   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5126   // double since there is no vbroadcastsd xmm
5127   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5128     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5129       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5130   }
5131
5132   // Unsupported broadcast.
5133   return SDValue();
5134 }
5135
5136 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5137 /// underlying vector and index.
5138 ///
5139 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5140 /// index.
5141 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5142                                          SDValue ExtIdx) {
5143   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5144   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5145     return Idx;
5146
5147   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5148   // lowered this:
5149   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5150   // to:
5151   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5152   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5153   //                           undef)
5154   //                       Constant<0>)
5155   // In this case the vector is the extract_subvector expression and the index
5156   // is 2, as specified by the shuffle.
5157   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5158   SDValue ShuffleVec = SVOp->getOperand(0);
5159   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5160   assert(ShuffleVecVT.getVectorElementType() ==
5161          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5162
5163   int ShuffleIdx = SVOp->getMaskElt(Idx);
5164   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5165     ExtractedFromVec = ShuffleVec;
5166     return ShuffleIdx;
5167   }
5168   return Idx;
5169 }
5170
5171 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5172   MVT VT = Op.getSimpleValueType();
5173
5174   // Skip if insert_vec_elt is not supported.
5175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5176   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5177     return SDValue();
5178
5179   SDLoc DL(Op);
5180   unsigned NumElems = Op.getNumOperands();
5181
5182   SDValue VecIn1;
5183   SDValue VecIn2;
5184   SmallVector<unsigned, 4> InsertIndices;
5185   SmallVector<int, 8> Mask(NumElems, -1);
5186
5187   for (unsigned i = 0; i != NumElems; ++i) {
5188     unsigned Opc = Op.getOperand(i).getOpcode();
5189
5190     if (Opc == ISD::UNDEF)
5191       continue;
5192
5193     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5194       // Quit if more than 1 elements need inserting.
5195       if (InsertIndices.size() > 1)
5196         return SDValue();
5197
5198       InsertIndices.push_back(i);
5199       continue;
5200     }
5201
5202     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5203     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5204     // Quit if non-constant index.
5205     if (!isa<ConstantSDNode>(ExtIdx))
5206       return SDValue();
5207     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5208
5209     // Quit if extracted from vector of different type.
5210     if (ExtractedFromVec.getValueType() != VT)
5211       return SDValue();
5212
5213     if (!VecIn1.getNode())
5214       VecIn1 = ExtractedFromVec;
5215     else if (VecIn1 != ExtractedFromVec) {
5216       if (!VecIn2.getNode())
5217         VecIn2 = ExtractedFromVec;
5218       else if (VecIn2 != ExtractedFromVec)
5219         // Quit if more than 2 vectors to shuffle
5220         return SDValue();
5221     }
5222
5223     if (ExtractedFromVec == VecIn1)
5224       Mask[i] = Idx;
5225     else if (ExtractedFromVec == VecIn2)
5226       Mask[i] = Idx + NumElems;
5227   }
5228
5229   if (!VecIn1.getNode())
5230     return SDValue();
5231
5232   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5233   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5234   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5235     unsigned Idx = InsertIndices[i];
5236     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5237                      DAG.getIntPtrConstant(Idx, DL));
5238   }
5239
5240   return NV;
5241 }
5242
5243 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5244   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5245          Op.getScalarValueSizeInBits() == 1 &&
5246          "Can not convert non-constant vector");
5247   uint64_t Immediate = 0;
5248   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5249     SDValue In = Op.getOperand(idx);
5250     if (In.getOpcode() != ISD::UNDEF)
5251       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5252   }
5253   SDLoc dl(Op);
5254   MVT VT =
5255    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5256   return DAG.getConstant(Immediate, dl, VT);
5257 }
5258 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5259 SDValue
5260 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5261
5262   MVT VT = Op.getSimpleValueType();
5263   assert((VT.getVectorElementType() == MVT::i1) &&
5264          "Unexpected type in LowerBUILD_VECTORvXi1!");
5265
5266   SDLoc dl(Op);
5267   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5268     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5269     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5270     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5271   }
5272
5273   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5274     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5275     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5276     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5277   }
5278
5279   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5280     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5281     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5282       return DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5283     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5284     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5285                         DAG.getIntPtrConstant(0, dl));
5286   }
5287
5288   // Vector has one or more non-const elements
5289   uint64_t Immediate = 0;
5290   SmallVector<unsigned, 16> NonConstIdx;
5291   bool IsSplat = true;
5292   bool HasConstElts = false;
5293   int SplatIdx = -1;
5294   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5295     SDValue In = Op.getOperand(idx);
5296     if (In.getOpcode() == ISD::UNDEF)
5297       continue;
5298     if (!isa<ConstantSDNode>(In)) 
5299       NonConstIdx.push_back(idx);
5300     else {
5301       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5302       HasConstElts = true;
5303     }
5304     if (SplatIdx == -1)
5305       SplatIdx = idx;
5306     else if (In != Op.getOperand(SplatIdx))
5307       IsSplat = false;
5308   }
5309
5310   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5311   if (IsSplat)
5312     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5313                        DAG.getConstant(1, dl, VT),
5314                        DAG.getConstant(0, dl, VT));
5315
5316   // insert elements one by one
5317   SDValue DstVec;
5318   SDValue Imm;
5319   if (Immediate) {
5320     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5321     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5322   }
5323   else if (HasConstElts)
5324     Imm = DAG.getConstant(0, dl, VT);
5325   else 
5326     Imm = DAG.getUNDEF(VT);
5327   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5328     DstVec = DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5329   else {
5330     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5331     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5332                          DAG.getIntPtrConstant(0, dl));
5333   }
5334
5335   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5336     unsigned InsertIdx = NonConstIdx[i];
5337     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5338                          Op.getOperand(InsertIdx),
5339                          DAG.getIntPtrConstant(InsertIdx, dl));
5340   }
5341   return DstVec;
5342 }
5343
5344 /// \brief Return true if \p N implements a horizontal binop and return the
5345 /// operands for the horizontal binop into V0 and V1.
5346 ///
5347 /// This is a helper function of LowerToHorizontalOp().
5348 /// This function checks that the build_vector \p N in input implements a
5349 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5350 /// operation to match.
5351 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5352 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5353 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5354 /// arithmetic sub.
5355 ///
5356 /// This function only analyzes elements of \p N whose indices are
5357 /// in range [BaseIdx, LastIdx).
5358 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5359                               SelectionDAG &DAG,
5360                               unsigned BaseIdx, unsigned LastIdx,
5361                               SDValue &V0, SDValue &V1) {
5362   EVT VT = N->getValueType(0);
5363
5364   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5365   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5366          "Invalid Vector in input!");
5367
5368   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5369   bool CanFold = true;
5370   unsigned ExpectedVExtractIdx = BaseIdx;
5371   unsigned NumElts = LastIdx - BaseIdx;
5372   V0 = DAG.getUNDEF(VT);
5373   V1 = DAG.getUNDEF(VT);
5374
5375   // Check if N implements a horizontal binop.
5376   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5377     SDValue Op = N->getOperand(i + BaseIdx);
5378
5379     // Skip UNDEFs.
5380     if (Op->getOpcode() == ISD::UNDEF) {
5381       // Update the expected vector extract index.
5382       if (i * 2 == NumElts)
5383         ExpectedVExtractIdx = BaseIdx;
5384       ExpectedVExtractIdx += 2;
5385       continue;
5386     }
5387
5388     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5389
5390     if (!CanFold)
5391       break;
5392
5393     SDValue Op0 = Op.getOperand(0);
5394     SDValue Op1 = Op.getOperand(1);
5395
5396     // Try to match the following pattern:
5397     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5398     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5399         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5400         Op0.getOperand(0) == Op1.getOperand(0) &&
5401         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5402         isa<ConstantSDNode>(Op1.getOperand(1)));
5403     if (!CanFold)
5404       break;
5405
5406     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5407     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5408
5409     if (i * 2 < NumElts) {
5410       if (V0.getOpcode() == ISD::UNDEF) {
5411         V0 = Op0.getOperand(0);
5412         if (V0.getValueType() != VT)
5413           return false;
5414       }
5415     } else {
5416       if (V1.getOpcode() == ISD::UNDEF) {
5417         V1 = Op0.getOperand(0);
5418         if (V1.getValueType() != VT)
5419           return false;
5420       }
5421       if (i * 2 == NumElts)
5422         ExpectedVExtractIdx = BaseIdx;
5423     }
5424
5425     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5426     if (I0 == ExpectedVExtractIdx)
5427       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5428     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5429       // Try to match the following dag sequence:
5430       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5431       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5432     } else
5433       CanFold = false;
5434
5435     ExpectedVExtractIdx += 2;
5436   }
5437
5438   return CanFold;
5439 }
5440
5441 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5442 /// a concat_vector.
5443 ///
5444 /// This is a helper function of LowerToHorizontalOp().
5445 /// This function expects two 256-bit vectors called V0 and V1.
5446 /// At first, each vector is split into two separate 128-bit vectors.
5447 /// Then, the resulting 128-bit vectors are used to implement two
5448 /// horizontal binary operations.
5449 ///
5450 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5451 ///
5452 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5453 /// the two new horizontal binop.
5454 /// When Mode is set, the first horizontal binop dag node would take as input
5455 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5456 /// horizontal binop dag node would take as input the lower 128-bit of V1
5457 /// and the upper 128-bit of V1.
5458 ///   Example:
5459 ///     HADD V0_LO, V0_HI
5460 ///     HADD V1_LO, V1_HI
5461 ///
5462 /// Otherwise, the first horizontal binop dag node takes as input the lower
5463 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5464 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5465 ///   Example:
5466 ///     HADD V0_LO, V1_LO
5467 ///     HADD V0_HI, V1_HI
5468 ///
5469 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5470 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5471 /// the upper 128-bits of the result.
5472 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5473                                      SDLoc DL, SelectionDAG &DAG,
5474                                      unsigned X86Opcode, bool Mode,
5475                                      bool isUndefLO, bool isUndefHI) {
5476   EVT VT = V0.getValueType();
5477   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5478          "Invalid nodes in input!");
5479
5480   unsigned NumElts = VT.getVectorNumElements();
5481   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5482   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5483   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5484   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5485   EVT NewVT = V0_LO.getValueType();
5486
5487   SDValue LO = DAG.getUNDEF(NewVT);
5488   SDValue HI = DAG.getUNDEF(NewVT);
5489
5490   if (Mode) {
5491     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5492     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5493       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5494     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5495       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5496   } else {
5497     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5498     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5499                        V1_LO->getOpcode() != ISD::UNDEF))
5500       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5501
5502     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5503                        V1_HI->getOpcode() != ISD::UNDEF))
5504       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5505   }
5506
5507   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5508 }
5509
5510 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5511 /// node.
5512 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5513                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5514   EVT VT = BV->getValueType(0);
5515   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5516       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5517     return SDValue();
5518
5519   SDLoc DL(BV);
5520   unsigned NumElts = VT.getVectorNumElements();
5521   SDValue InVec0 = DAG.getUNDEF(VT);
5522   SDValue InVec1 = DAG.getUNDEF(VT);
5523
5524   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5525           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5526
5527   // Odd-numbered elements in the input build vector are obtained from
5528   // adding two integer/float elements.
5529   // Even-numbered elements in the input build vector are obtained from
5530   // subtracting two integer/float elements.
5531   unsigned ExpectedOpcode = ISD::FSUB;
5532   unsigned NextExpectedOpcode = ISD::FADD;
5533   bool AddFound = false;
5534   bool SubFound = false;
5535
5536   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5537     SDValue Op = BV->getOperand(i);
5538
5539     // Skip 'undef' values.
5540     unsigned Opcode = Op.getOpcode();
5541     if (Opcode == ISD::UNDEF) {
5542       std::swap(ExpectedOpcode, NextExpectedOpcode);
5543       continue;
5544     }
5545
5546     // Early exit if we found an unexpected opcode.
5547     if (Opcode != ExpectedOpcode)
5548       return SDValue();
5549
5550     SDValue Op0 = Op.getOperand(0);
5551     SDValue Op1 = Op.getOperand(1);
5552
5553     // Try to match the following pattern:
5554     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5555     // Early exit if we cannot match that sequence.
5556     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5557         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5558         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5559         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5560         Op0.getOperand(1) != Op1.getOperand(1))
5561       return SDValue();
5562
5563     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5564     if (I0 != i)
5565       return SDValue();
5566
5567     // We found a valid add/sub node. Update the information accordingly.
5568     if (i & 1)
5569       AddFound = true;
5570     else
5571       SubFound = true;
5572
5573     // Update InVec0 and InVec1.
5574     if (InVec0.getOpcode() == ISD::UNDEF) {
5575       InVec0 = Op0.getOperand(0);
5576       if (InVec0.getValueType() != VT)
5577         return SDValue();
5578     }
5579     if (InVec1.getOpcode() == ISD::UNDEF) {
5580       InVec1 = Op1.getOperand(0);
5581       if (InVec1.getValueType() != VT)
5582         return SDValue();
5583     }
5584
5585     // Make sure that operands in input to each add/sub node always
5586     // come from a same pair of vectors.
5587     if (InVec0 != Op0.getOperand(0)) {
5588       if (ExpectedOpcode == ISD::FSUB)
5589         return SDValue();
5590
5591       // FADD is commutable. Try to commute the operands
5592       // and then test again.
5593       std::swap(Op0, Op1);
5594       if (InVec0 != Op0.getOperand(0))
5595         return SDValue();
5596     }
5597
5598     if (InVec1 != Op1.getOperand(0))
5599       return SDValue();
5600
5601     // Update the pair of expected opcodes.
5602     std::swap(ExpectedOpcode, NextExpectedOpcode);
5603   }
5604
5605   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5606   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5607       InVec1.getOpcode() != ISD::UNDEF)
5608     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5609
5610   return SDValue();
5611 }
5612
5613 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5614 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5615                                    const X86Subtarget *Subtarget,
5616                                    SelectionDAG &DAG) {
5617   EVT VT = BV->getValueType(0);
5618   unsigned NumElts = VT.getVectorNumElements();
5619   unsigned NumUndefsLO = 0;
5620   unsigned NumUndefsHI = 0;
5621   unsigned Half = NumElts/2;
5622
5623   // Count the number of UNDEF operands in the build_vector in input.
5624   for (unsigned i = 0, e = Half; i != e; ++i)
5625     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5626       NumUndefsLO++;
5627
5628   for (unsigned i = Half, e = NumElts; i != e; ++i)
5629     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5630       NumUndefsHI++;
5631
5632   // Early exit if this is either a build_vector of all UNDEFs or all the
5633   // operands but one are UNDEF.
5634   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5635     return SDValue();
5636
5637   SDLoc DL(BV);
5638   SDValue InVec0, InVec1;
5639   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5640     // Try to match an SSE3 float HADD/HSUB.
5641     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5642       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5643
5644     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5645       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5646   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5647     // Try to match an SSSE3 integer HADD/HSUB.
5648     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5649       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5650
5651     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5652       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5653   }
5654
5655   if (!Subtarget->hasAVX())
5656     return SDValue();
5657
5658   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5659     // Try to match an AVX horizontal add/sub of packed single/double
5660     // precision floating point values from 256-bit vectors.
5661     SDValue InVec2, InVec3;
5662     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5663         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5664         ((InVec0.getOpcode() == ISD::UNDEF ||
5665           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5666         ((InVec1.getOpcode() == ISD::UNDEF ||
5667           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5668       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5669
5670     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5671         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5672         ((InVec0.getOpcode() == ISD::UNDEF ||
5673           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5674         ((InVec1.getOpcode() == ISD::UNDEF ||
5675           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5676       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5677   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5678     // Try to match an AVX2 horizontal add/sub of signed integers.
5679     SDValue InVec2, InVec3;
5680     unsigned X86Opcode;
5681     bool CanFold = true;
5682
5683     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5684         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5685         ((InVec0.getOpcode() == ISD::UNDEF ||
5686           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5687         ((InVec1.getOpcode() == ISD::UNDEF ||
5688           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5689       X86Opcode = X86ISD::HADD;
5690     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5691         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5692         ((InVec0.getOpcode() == ISD::UNDEF ||
5693           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5694         ((InVec1.getOpcode() == ISD::UNDEF ||
5695           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5696       X86Opcode = X86ISD::HSUB;
5697     else
5698       CanFold = false;
5699
5700     if (CanFold) {
5701       // Fold this build_vector into a single horizontal add/sub.
5702       // Do this only if the target has AVX2.
5703       if (Subtarget->hasAVX2())
5704         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5705
5706       // Do not try to expand this build_vector into a pair of horizontal
5707       // add/sub if we can emit a pair of scalar add/sub.
5708       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5709         return SDValue();
5710
5711       // Convert this build_vector into a pair of horizontal binop followed by
5712       // a concat vector.
5713       bool isUndefLO = NumUndefsLO == Half;
5714       bool isUndefHI = NumUndefsHI == Half;
5715       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5716                                    isUndefLO, isUndefHI);
5717     }
5718   }
5719
5720   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5721        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5722     unsigned X86Opcode;
5723     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5724       X86Opcode = X86ISD::HADD;
5725     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5726       X86Opcode = X86ISD::HSUB;
5727     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5728       X86Opcode = X86ISD::FHADD;
5729     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5730       X86Opcode = X86ISD::FHSUB;
5731     else
5732       return SDValue();
5733
5734     // Don't try to expand this build_vector into a pair of horizontal add/sub
5735     // if we can simply emit a pair of scalar add/sub.
5736     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5737       return SDValue();
5738
5739     // Convert this build_vector into two horizontal add/sub followed by
5740     // a concat vector.
5741     bool isUndefLO = NumUndefsLO == Half;
5742     bool isUndefHI = NumUndefsHI == Half;
5743     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5744                                  isUndefLO, isUndefHI);
5745   }
5746
5747   return SDValue();
5748 }
5749
5750 SDValue
5751 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5752   SDLoc dl(Op);
5753
5754   MVT VT = Op.getSimpleValueType();
5755   MVT ExtVT = VT.getVectorElementType();
5756   unsigned NumElems = Op.getNumOperands();
5757
5758   // Generate vectors for predicate vectors.
5759   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5760     return LowerBUILD_VECTORvXi1(Op, DAG);
5761
5762   // Vectors containing all zeros can be matched by pxor and xorps later
5763   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5764     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5765     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5766     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5767       return Op;
5768
5769     return getZeroVector(VT, Subtarget, DAG, dl);
5770   }
5771
5772   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5773   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5774   // vpcmpeqd on 256-bit vectors.
5775   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5776     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5777       return Op;
5778
5779     if (!VT.is512BitVector())
5780       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5781   }
5782
5783   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5784   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5785     return AddSub;
5786   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5787     return HorizontalOp;
5788   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5789     return Broadcast;
5790
5791   unsigned EVTBits = ExtVT.getSizeInBits();
5792
5793   unsigned NumZero  = 0;
5794   unsigned NumNonZero = 0;
5795   unsigned NonZeros = 0;
5796   bool IsAllConstants = true;
5797   SmallSet<SDValue, 8> Values;
5798   for (unsigned i = 0; i < NumElems; ++i) {
5799     SDValue Elt = Op.getOperand(i);
5800     if (Elt.getOpcode() == ISD::UNDEF)
5801       continue;
5802     Values.insert(Elt);
5803     if (Elt.getOpcode() != ISD::Constant &&
5804         Elt.getOpcode() != ISD::ConstantFP)
5805       IsAllConstants = false;
5806     if (X86::isZeroNode(Elt))
5807       NumZero++;
5808     else {
5809       NonZeros |= (1 << i);
5810       NumNonZero++;
5811     }
5812   }
5813
5814   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5815   if (NumNonZero == 0)
5816     return DAG.getUNDEF(VT);
5817
5818   // Special case for single non-zero, non-undef, element.
5819   if (NumNonZero == 1) {
5820     unsigned Idx = countTrailingZeros(NonZeros);
5821     SDValue Item = Op.getOperand(Idx);
5822
5823     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5824     // the value are obviously zero, truncate the value to i32 and do the
5825     // insertion that way.  Only do this if the value is non-constant or if the
5826     // value is a constant being inserted into element 0.  It is cheaper to do
5827     // a constant pool load than it is to do a movd + shuffle.
5828     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5829         (!IsAllConstants || Idx == 0)) {
5830       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5831         // Handle SSE only.
5832         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5833         EVT VecVT = MVT::v4i32;
5834
5835         // Truncate the value (which may itself be a constant) to i32, and
5836         // convert it to a vector with movd (S2V+shuffle to zero extend).
5837         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5838         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5839         return DAG.getNode(
5840             ISD::BITCAST, dl, VT,
5841             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5842       }
5843     }
5844
5845     // If we have a constant or non-constant insertion into the low element of
5846     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5847     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5848     // depending on what the source datatype is.
5849     if (Idx == 0) {
5850       if (NumZero == 0)
5851         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5852
5853       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5854           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5855         if (VT.is512BitVector()) {
5856           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5857           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5858                              Item, DAG.getIntPtrConstant(0, dl));
5859         }
5860         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5861                "Expected an SSE value type!");
5862         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5863         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5864         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5865       }
5866
5867       // We can't directly insert an i8 or i16 into a vector, so zero extend
5868       // it to i32 first.
5869       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5870         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5871         if (VT.is256BitVector()) {
5872           if (Subtarget->hasAVX()) {
5873             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5874             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5875           } else {
5876             // Without AVX, we need to extend to a 128-bit vector and then
5877             // insert into the 256-bit vector.
5878             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5879             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5880             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5881           }
5882         } else {
5883           assert(VT.is128BitVector() && "Expected an SSE value type!");
5884           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5885           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5886         }
5887         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5888       }
5889     }
5890
5891     // Is it a vector logical left shift?
5892     if (NumElems == 2 && Idx == 1 &&
5893         X86::isZeroNode(Op.getOperand(0)) &&
5894         !X86::isZeroNode(Op.getOperand(1))) {
5895       unsigned NumBits = VT.getSizeInBits();
5896       return getVShift(true, VT,
5897                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5898                                    VT, Op.getOperand(1)),
5899                        NumBits/2, DAG, *this, dl);
5900     }
5901
5902     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5903       return SDValue();
5904
5905     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5906     // is a non-constant being inserted into an element other than the low one,
5907     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5908     // movd/movss) to move this into the low element, then shuffle it into
5909     // place.
5910     if (EVTBits == 32) {
5911       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5912       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5913     }
5914   }
5915
5916   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5917   if (Values.size() == 1) {
5918     if (EVTBits == 32) {
5919       // Instead of a shuffle like this:
5920       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5921       // Check if it's possible to issue this instead.
5922       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5923       unsigned Idx = countTrailingZeros(NonZeros);
5924       SDValue Item = Op.getOperand(Idx);
5925       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5926         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5927     }
5928     return SDValue();
5929   }
5930
5931   // A vector full of immediates; various special cases are already
5932   // handled, so this is best done with a single constant-pool load.
5933   if (IsAllConstants)
5934     return SDValue();
5935
5936   // For AVX-length vectors, see if we can use a vector load to get all of the
5937   // elements, otherwise build the individual 128-bit pieces and use
5938   // shuffles to put them in place.
5939   if (VT.is256BitVector() || VT.is512BitVector()) {
5940     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5941
5942     // Check for a build vector of consecutive loads.
5943     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5944       return LD;
5945
5946     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5947
5948     // Build both the lower and upper subvector.
5949     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5950                                 makeArrayRef(&V[0], NumElems/2));
5951     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5952                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5953
5954     // Recreate the wider vector with the lower and upper part.
5955     if (VT.is256BitVector())
5956       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5957     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5958   }
5959
5960   // Let legalizer expand 2-wide build_vectors.
5961   if (EVTBits == 64) {
5962     if (NumNonZero == 1) {
5963       // One half is zero or undef.
5964       unsigned Idx = countTrailingZeros(NonZeros);
5965       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5966                                  Op.getOperand(Idx));
5967       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5968     }
5969     return SDValue();
5970   }
5971
5972   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5973   if (EVTBits == 8 && NumElems == 16)
5974     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5975                                         Subtarget, *this))
5976       return V;
5977
5978   if (EVTBits == 16 && NumElems == 8)
5979     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5980                                       Subtarget, *this))
5981       return V;
5982
5983   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5984   if (EVTBits == 32 && NumElems == 4)
5985     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5986       return V;
5987
5988   // If element VT is == 32 bits, turn it into a number of shuffles.
5989   SmallVector<SDValue, 8> V(NumElems);
5990   if (NumElems == 4 && NumZero > 0) {
5991     for (unsigned i = 0; i < 4; ++i) {
5992       bool isZero = !(NonZeros & (1 << i));
5993       if (isZero)
5994         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5995       else
5996         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5997     }
5998
5999     for (unsigned i = 0; i < 2; ++i) {
6000       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6001         default: break;
6002         case 0:
6003           V[i] = V[i*2];  // Must be a zero vector.
6004           break;
6005         case 1:
6006           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6007           break;
6008         case 2:
6009           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6010           break;
6011         case 3:
6012           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6013           break;
6014       }
6015     }
6016
6017     bool Reverse1 = (NonZeros & 0x3) == 2;
6018     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6019     int MaskVec[] = {
6020       Reverse1 ? 1 : 0,
6021       Reverse1 ? 0 : 1,
6022       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6023       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6024     };
6025     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6026   }
6027
6028   if (Values.size() > 1 && VT.is128BitVector()) {
6029     // Check for a build vector of consecutive loads.
6030     for (unsigned i = 0; i < NumElems; ++i)
6031       V[i] = Op.getOperand(i);
6032
6033     // Check for elements which are consecutive loads.
6034     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6035       return LD;
6036
6037     // Check for a build vector from mostly shuffle plus few inserting.
6038     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6039       return Sh;
6040
6041     // For SSE 4.1, use insertps to put the high elements into the low element.
6042     if (Subtarget->hasSSE41()) {
6043       SDValue Result;
6044       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6045         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6046       else
6047         Result = DAG.getUNDEF(VT);
6048
6049       for (unsigned i = 1; i < NumElems; ++i) {
6050         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6051         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6052                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6053       }
6054       return Result;
6055     }
6056
6057     // Otherwise, expand into a number of unpckl*, start by extending each of
6058     // our (non-undef) elements to the full vector width with the element in the
6059     // bottom slot of the vector (which generates no code for SSE).
6060     for (unsigned i = 0; i < NumElems; ++i) {
6061       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6062         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6063       else
6064         V[i] = DAG.getUNDEF(VT);
6065     }
6066
6067     // Next, we iteratively mix elements, e.g. for v4f32:
6068     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6069     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6070     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6071     unsigned EltStride = NumElems >> 1;
6072     while (EltStride != 0) {
6073       for (unsigned i = 0; i < EltStride; ++i) {
6074         // If V[i+EltStride] is undef and this is the first round of mixing,
6075         // then it is safe to just drop this shuffle: V[i] is already in the
6076         // right place, the one element (since it's the first round) being
6077         // inserted as undef can be dropped.  This isn't safe for successive
6078         // rounds because they will permute elements within both vectors.
6079         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6080             EltStride == NumElems/2)
6081           continue;
6082
6083         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6084       }
6085       EltStride >>= 1;
6086     }
6087     return V[0];
6088   }
6089   return SDValue();
6090 }
6091
6092 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6093 // to create 256-bit vectors from two other 128-bit ones.
6094 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6095   SDLoc dl(Op);
6096   MVT ResVT = Op.getSimpleValueType();
6097
6098   assert((ResVT.is256BitVector() ||
6099           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6100
6101   SDValue V1 = Op.getOperand(0);
6102   SDValue V2 = Op.getOperand(1);
6103   unsigned NumElems = ResVT.getVectorNumElements();
6104   if (ResVT.is256BitVector())
6105     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6106
6107   if (Op.getNumOperands() == 4) {
6108     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6109                                 ResVT.getVectorNumElements()/2);
6110     SDValue V3 = Op.getOperand(2);
6111     SDValue V4 = Op.getOperand(3);
6112     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6113       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6114   }
6115   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6116 }
6117
6118 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6119                                        const X86Subtarget *Subtarget,
6120                                        SelectionDAG & DAG) {
6121   SDLoc dl(Op);
6122   MVT ResVT = Op.getSimpleValueType();
6123   unsigned NumOfOperands = Op.getNumOperands();
6124
6125   assert(isPowerOf2_32(NumOfOperands) &&
6126          "Unexpected number of operands in CONCAT_VECTORS");
6127
6128   if (NumOfOperands > 2) {
6129     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6130                                   ResVT.getVectorNumElements()/2);
6131     SmallVector<SDValue, 2> Ops;
6132     for (unsigned i = 0; i < NumOfOperands/2; i++)
6133       Ops.push_back(Op.getOperand(i));
6134     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6135     Ops.clear();
6136     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6137       Ops.push_back(Op.getOperand(i));
6138     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6139     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6140   }
6141
6142   SDValue V1 = Op.getOperand(0);
6143   SDValue V2 = Op.getOperand(1);
6144   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6145   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6146
6147   if (IsZeroV1 && IsZeroV2)
6148     return getZeroVector(ResVT, Subtarget, DAG, dl);
6149
6150   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6151   SDValue Undef = DAG.getUNDEF(ResVT);
6152   unsigned NumElems = ResVT.getVectorNumElements();
6153   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6154
6155   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6156   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6157   if (IsZeroV1)
6158     return V2;
6159
6160   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6161   // Zero the upper bits of V1
6162   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6163   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6164   if (IsZeroV2)
6165     return V1;
6166   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6167 }
6168
6169 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6170                                    const X86Subtarget *Subtarget,
6171                                    SelectionDAG &DAG) {
6172   MVT VT = Op.getSimpleValueType();
6173   if (VT.getVectorElementType() == MVT::i1)
6174     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6175
6176   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6177          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6178           Op.getNumOperands() == 4)));
6179
6180   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6181   // from two other 128-bit ones.
6182
6183   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6184   return LowerAVXCONCAT_VECTORS(Op, DAG);
6185 }
6186
6187
6188 //===----------------------------------------------------------------------===//
6189 // Vector shuffle lowering
6190 //
6191 // This is an experimental code path for lowering vector shuffles on x86. It is
6192 // designed to handle arbitrary vector shuffles and blends, gracefully
6193 // degrading performance as necessary. It works hard to recognize idiomatic
6194 // shuffles and lower them to optimal instruction patterns without leaving
6195 // a framework that allows reasonably efficient handling of all vector shuffle
6196 // patterns.
6197 //===----------------------------------------------------------------------===//
6198
6199 /// \brief Tiny helper function to identify a no-op mask.
6200 ///
6201 /// This is a somewhat boring predicate function. It checks whether the mask
6202 /// array input, which is assumed to be a single-input shuffle mask of the kind
6203 /// used by the X86 shuffle instructions (not a fully general
6204 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6205 /// in-place shuffle are 'no-op's.
6206 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6207   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6208     if (Mask[i] != -1 && Mask[i] != i)
6209       return false;
6210   return true;
6211 }
6212
6213 /// \brief Helper function to classify a mask as a single-input mask.
6214 ///
6215 /// This isn't a generic single-input test because in the vector shuffle
6216 /// lowering we canonicalize single inputs to be the first input operand. This
6217 /// means we can more quickly test for a single input by only checking whether
6218 /// an input from the second operand exists. We also assume that the size of
6219 /// mask corresponds to the size of the input vectors which isn't true in the
6220 /// fully general case.
6221 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6222   for (int M : Mask)
6223     if (M >= (int)Mask.size())
6224       return false;
6225   return true;
6226 }
6227
6228 /// \brief Test whether there are elements crossing 128-bit lanes in this
6229 /// shuffle mask.
6230 ///
6231 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6232 /// and we routinely test for these.
6233 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6234   int LaneSize = 128 / VT.getScalarSizeInBits();
6235   int Size = Mask.size();
6236   for (int i = 0; i < Size; ++i)
6237     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6238       return true;
6239   return false;
6240 }
6241
6242 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6243 ///
6244 /// This checks a shuffle mask to see if it is performing the same
6245 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6246 /// that it is also not lane-crossing. It may however involve a blend from the
6247 /// same lane of a second vector.
6248 ///
6249 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6250 /// non-trivial to compute in the face of undef lanes. The representation is
6251 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6252 /// entries from both V1 and V2 inputs to the wider mask.
6253 static bool
6254 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6255                                 SmallVectorImpl<int> &RepeatedMask) {
6256   int LaneSize = 128 / VT.getScalarSizeInBits();
6257   RepeatedMask.resize(LaneSize, -1);
6258   int Size = Mask.size();
6259   for (int i = 0; i < Size; ++i) {
6260     if (Mask[i] < 0)
6261       continue;
6262     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6263       // This entry crosses lanes, so there is no way to model this shuffle.
6264       return false;
6265
6266     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6267     if (RepeatedMask[i % LaneSize] == -1)
6268       // This is the first non-undef entry in this slot of a 128-bit lane.
6269       RepeatedMask[i % LaneSize] =
6270           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6271     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6272       // Found a mismatch with the repeated mask.
6273       return false;
6274   }
6275   return true;
6276 }
6277
6278 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6279 /// arguments.
6280 ///
6281 /// This is a fast way to test a shuffle mask against a fixed pattern:
6282 ///
6283 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6284 ///
6285 /// It returns true if the mask is exactly as wide as the argument list, and
6286 /// each element of the mask is either -1 (signifying undef) or the value given
6287 /// in the argument.
6288 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6289                                 ArrayRef<int> ExpectedMask) {
6290   if (Mask.size() != ExpectedMask.size())
6291     return false;
6292
6293   int Size = Mask.size();
6294
6295   // If the values are build vectors, we can look through them to find
6296   // equivalent inputs that make the shuffles equivalent.
6297   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6298   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6299
6300   for (int i = 0; i < Size; ++i)
6301     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6302       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6303       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6304       if (!MaskBV || !ExpectedBV ||
6305           MaskBV->getOperand(Mask[i] % Size) !=
6306               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6307         return false;
6308     }
6309
6310   return true;
6311 }
6312
6313 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6314 ///
6315 /// This helper function produces an 8-bit shuffle immediate corresponding to
6316 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6317 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6318 /// example.
6319 ///
6320 /// NB: We rely heavily on "undef" masks preserving the input lane.
6321 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6322                                           SelectionDAG &DAG) {
6323   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6324   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6325   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6326   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6327   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6328
6329   unsigned Imm = 0;
6330   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6331   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6332   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6333   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6334   return DAG.getConstant(Imm, DL, MVT::i8);
6335 }
6336
6337 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6338 ///
6339 /// This is used as a fallback approach when first class blend instructions are
6340 /// unavailable. Currently it is only suitable for integer vectors, but could
6341 /// be generalized for floating point vectors if desirable.
6342 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6343                                             SDValue V2, ArrayRef<int> Mask,
6344                                             SelectionDAG &DAG) {
6345   assert(VT.isInteger() && "Only supports integer vector types!");
6346   MVT EltVT = VT.getScalarType();
6347   int NumEltBits = EltVT.getSizeInBits();
6348   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6349   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6350                                     EltVT);
6351   SmallVector<SDValue, 16> MaskOps;
6352   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6353     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6354       return SDValue(); // Shuffled input!
6355     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6356   }
6357
6358   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6359   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6360   // We have to cast V2 around.
6361   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6362   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6363                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6364                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6365                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6366   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6367 }
6368
6369 /// \brief Try to emit a blend instruction for a shuffle.
6370 ///
6371 /// This doesn't do any checks for the availability of instructions for blending
6372 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6373 /// be matched in the backend with the type given. What it does check for is
6374 /// that the shuffle mask is in fact a blend.
6375 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6376                                          SDValue V2, ArrayRef<int> Mask,
6377                                          const X86Subtarget *Subtarget,
6378                                          SelectionDAG &DAG) {
6379   unsigned BlendMask = 0;
6380   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6381     if (Mask[i] >= Size) {
6382       if (Mask[i] != i + Size)
6383         return SDValue(); // Shuffled V2 input!
6384       BlendMask |= 1u << i;
6385       continue;
6386     }
6387     if (Mask[i] >= 0 && Mask[i] != i)
6388       return SDValue(); // Shuffled V1 input!
6389   }
6390   switch (VT.SimpleTy) {
6391   case MVT::v2f64:
6392   case MVT::v4f32:
6393   case MVT::v4f64:
6394   case MVT::v8f32:
6395     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6396                        DAG.getConstant(BlendMask, DL, MVT::i8));
6397
6398   case MVT::v4i64:
6399   case MVT::v8i32:
6400     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6401     // FALLTHROUGH
6402   case MVT::v2i64:
6403   case MVT::v4i32:
6404     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6405     // that instruction.
6406     if (Subtarget->hasAVX2()) {
6407       // Scale the blend by the number of 32-bit dwords per element.
6408       int Scale =  VT.getScalarSizeInBits() / 32;
6409       BlendMask = 0;
6410       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6411         if (Mask[i] >= Size)
6412           for (int j = 0; j < Scale; ++j)
6413             BlendMask |= 1u << (i * Scale + j);
6414
6415       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6416       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6417       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6418       return DAG.getNode(ISD::BITCAST, DL, VT,
6419                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6420                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6421     }
6422     // FALLTHROUGH
6423   case MVT::v8i16: {
6424     // For integer shuffles we need to expand the mask and cast the inputs to
6425     // v8i16s prior to blending.
6426     int Scale = 8 / VT.getVectorNumElements();
6427     BlendMask = 0;
6428     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6429       if (Mask[i] >= Size)
6430         for (int j = 0; j < Scale; ++j)
6431           BlendMask |= 1u << (i * Scale + j);
6432
6433     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6434     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6435     return DAG.getNode(ISD::BITCAST, DL, VT,
6436                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6437                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6438   }
6439
6440   case MVT::v16i16: {
6441     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6442     SmallVector<int, 8> RepeatedMask;
6443     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6444       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6445       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6446       BlendMask = 0;
6447       for (int i = 0; i < 8; ++i)
6448         if (RepeatedMask[i] >= 16)
6449           BlendMask |= 1u << i;
6450       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6451                          DAG.getConstant(BlendMask, DL, MVT::i8));
6452     }
6453   }
6454     // FALLTHROUGH
6455   case MVT::v16i8:
6456   case MVT::v32i8: {
6457     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6458            "256-bit byte-blends require AVX2 support!");
6459
6460     // Scale the blend by the number of bytes per element.
6461     int Scale = VT.getScalarSizeInBits() / 8;
6462
6463     // This form of blend is always done on bytes. Compute the byte vector
6464     // type.
6465     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6466
6467     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6468     // mix of LLVM's code generator and the x86 backend. We tell the code
6469     // generator that boolean values in the elements of an x86 vector register
6470     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6471     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6472     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6473     // of the element (the remaining are ignored) and 0 in that high bit would
6474     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6475     // the LLVM model for boolean values in vector elements gets the relevant
6476     // bit set, it is set backwards and over constrained relative to x86's
6477     // actual model.
6478     SmallVector<SDValue, 32> VSELECTMask;
6479     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6480       for (int j = 0; j < Scale; ++j)
6481         VSELECTMask.push_back(
6482             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6483                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6484                                           MVT::i8));
6485
6486     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6487     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6488     return DAG.getNode(
6489         ISD::BITCAST, DL, VT,
6490         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6491                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6492                     V1, V2));
6493   }
6494
6495   default:
6496     llvm_unreachable("Not a supported integer vector type!");
6497   }
6498 }
6499
6500 /// \brief Try to lower as a blend of elements from two inputs followed by
6501 /// a single-input permutation.
6502 ///
6503 /// This matches the pattern where we can blend elements from two inputs and
6504 /// then reduce the shuffle to a single-input permutation.
6505 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6506                                                    SDValue V2,
6507                                                    ArrayRef<int> Mask,
6508                                                    SelectionDAG &DAG) {
6509   // We build up the blend mask while checking whether a blend is a viable way
6510   // to reduce the shuffle.
6511   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6512   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6513
6514   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6515     if (Mask[i] < 0)
6516       continue;
6517
6518     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6519
6520     if (BlendMask[Mask[i] % Size] == -1)
6521       BlendMask[Mask[i] % Size] = Mask[i];
6522     else if (BlendMask[Mask[i] % Size] != Mask[i])
6523       return SDValue(); // Can't blend in the needed input!
6524
6525     PermuteMask[i] = Mask[i] % Size;
6526   }
6527
6528   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6529   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6530 }
6531
6532 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6533 /// blends and permutes.
6534 ///
6535 /// This matches the extremely common pattern for handling combined
6536 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6537 /// operations. It will try to pick the best arrangement of shuffles and
6538 /// blends.
6539 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6540                                                           SDValue V1,
6541                                                           SDValue V2,
6542                                                           ArrayRef<int> Mask,
6543                                                           SelectionDAG &DAG) {
6544   // Shuffle the input elements into the desired positions in V1 and V2 and
6545   // blend them together.
6546   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6547   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6548   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6549   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6550     if (Mask[i] >= 0 && Mask[i] < Size) {
6551       V1Mask[i] = Mask[i];
6552       BlendMask[i] = i;
6553     } else if (Mask[i] >= Size) {
6554       V2Mask[i] = Mask[i] - Size;
6555       BlendMask[i] = i + Size;
6556     }
6557
6558   // Try to lower with the simpler initial blend strategy unless one of the
6559   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6560   // shuffle may be able to fold with a load or other benefit. However, when
6561   // we'll have to do 2x as many shuffles in order to achieve this, blending
6562   // first is a better strategy.
6563   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6564     if (SDValue BlendPerm =
6565             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6566       return BlendPerm;
6567
6568   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6569   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6570   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6571 }
6572
6573 /// \brief Try to lower a vector shuffle as a byte rotation.
6574 ///
6575 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6576 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6577 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6578 /// try to generically lower a vector shuffle through such an pattern. It
6579 /// does not check for the profitability of lowering either as PALIGNR or
6580 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6581 /// This matches shuffle vectors that look like:
6582 ///
6583 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6584 ///
6585 /// Essentially it concatenates V1 and V2, shifts right by some number of
6586 /// elements, and takes the low elements as the result. Note that while this is
6587 /// specified as a *right shift* because x86 is little-endian, it is a *left
6588 /// rotate* of the vector lanes.
6589 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6590                                               SDValue V2,
6591                                               ArrayRef<int> Mask,
6592                                               const X86Subtarget *Subtarget,
6593                                               SelectionDAG &DAG) {
6594   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6595
6596   int NumElts = Mask.size();
6597   int NumLanes = VT.getSizeInBits() / 128;
6598   int NumLaneElts = NumElts / NumLanes;
6599
6600   // We need to detect various ways of spelling a rotation:
6601   //   [11, 12, 13, 14, 15,  0,  1,  2]
6602   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6603   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6604   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6605   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6606   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6607   int Rotation = 0;
6608   SDValue Lo, Hi;
6609   for (int l = 0; l < NumElts; l += NumLaneElts) {
6610     for (int i = 0; i < NumLaneElts; ++i) {
6611       if (Mask[l + i] == -1)
6612         continue;
6613       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6614
6615       // Get the mod-Size index and lane correct it.
6616       int LaneIdx = (Mask[l + i] % NumElts) - l;
6617       // Make sure it was in this lane.
6618       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6619         return SDValue();
6620
6621       // Determine where a rotated vector would have started.
6622       int StartIdx = i - LaneIdx;
6623       if (StartIdx == 0)
6624         // The identity rotation isn't interesting, stop.
6625         return SDValue();
6626
6627       // If we found the tail of a vector the rotation must be the missing
6628       // front. If we found the head of a vector, it must be how much of the
6629       // head.
6630       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6631
6632       if (Rotation == 0)
6633         Rotation = CandidateRotation;
6634       else if (Rotation != CandidateRotation)
6635         // The rotations don't match, so we can't match this mask.
6636         return SDValue();
6637
6638       // Compute which value this mask is pointing at.
6639       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6640
6641       // Compute which of the two target values this index should be assigned
6642       // to. This reflects whether the high elements are remaining or the low
6643       // elements are remaining.
6644       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6645
6646       // Either set up this value if we've not encountered it before, or check
6647       // that it remains consistent.
6648       if (!TargetV)
6649         TargetV = MaskV;
6650       else if (TargetV != MaskV)
6651         // This may be a rotation, but it pulls from the inputs in some
6652         // unsupported interleaving.
6653         return SDValue();
6654     }
6655   }
6656
6657   // Check that we successfully analyzed the mask, and normalize the results.
6658   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6659   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6660   if (!Lo)
6661     Lo = Hi;
6662   else if (!Hi)
6663     Hi = Lo;
6664
6665   // The actual rotate instruction rotates bytes, so we need to scale the
6666   // rotation based on how many bytes are in the vector lane.
6667   int Scale = 16 / NumLaneElts;
6668
6669   // SSSE3 targets can use the palignr instruction.
6670   if (Subtarget->hasSSSE3()) {
6671     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6672     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6673     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6674     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6675
6676     return DAG.getNode(ISD::BITCAST, DL, VT,
6677                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6678                                    DAG.getConstant(Rotation * Scale, DL,
6679                                                    MVT::i8)));
6680   }
6681
6682   assert(VT.getSizeInBits() == 128 &&
6683          "Rotate-based lowering only supports 128-bit lowering!");
6684   assert(Mask.size() <= 16 &&
6685          "Can shuffle at most 16 bytes in a 128-bit vector!");
6686
6687   // Default SSE2 implementation
6688   int LoByteShift = 16 - Rotation * Scale;
6689   int HiByteShift = Rotation * Scale;
6690
6691   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6692   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6693   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6694
6695   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6696                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6697   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6698                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6699   return DAG.getNode(ISD::BITCAST, DL, VT,
6700                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6701 }
6702
6703 /// \brief Compute whether each element of a shuffle is zeroable.
6704 ///
6705 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6706 /// Either it is an undef element in the shuffle mask, the element of the input
6707 /// referenced is undef, or the element of the input referenced is known to be
6708 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6709 /// as many lanes with this technique as possible to simplify the remaining
6710 /// shuffle.
6711 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6712                                                      SDValue V1, SDValue V2) {
6713   SmallBitVector Zeroable(Mask.size(), false);
6714
6715   while (V1.getOpcode() == ISD::BITCAST)
6716     V1 = V1->getOperand(0);
6717   while (V2.getOpcode() == ISD::BITCAST)
6718     V2 = V2->getOperand(0);
6719
6720   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6721   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6722
6723   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6724     int M = Mask[i];
6725     // Handle the easy cases.
6726     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6727       Zeroable[i] = true;
6728       continue;
6729     }
6730
6731     // If this is an index into a build_vector node (which has the same number
6732     // of elements), dig out the input value and use it.
6733     SDValue V = M < Size ? V1 : V2;
6734     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6735       continue;
6736
6737     SDValue Input = V.getOperand(M % Size);
6738     // The UNDEF opcode check really should be dead code here, but not quite
6739     // worth asserting on (it isn't invalid, just unexpected).
6740     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6741       Zeroable[i] = true;
6742   }
6743
6744   return Zeroable;
6745 }
6746
6747 /// \brief Try to emit a bitmask instruction for a shuffle.
6748 ///
6749 /// This handles cases where we can model a blend exactly as a bitmask due to
6750 /// one of the inputs being zeroable.
6751 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6752                                            SDValue V2, ArrayRef<int> Mask,
6753                                            SelectionDAG &DAG) {
6754   MVT EltVT = VT.getScalarType();
6755   int NumEltBits = EltVT.getSizeInBits();
6756   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6757   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6758   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6759                                     IntEltVT);
6760   if (EltVT.isFloatingPoint()) {
6761     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6762     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6763   }
6764   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6765   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6766   SDValue V;
6767   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6768     if (Zeroable[i])
6769       continue;
6770     if (Mask[i] % Size != i)
6771       return SDValue(); // Not a blend.
6772     if (!V)
6773       V = Mask[i] < Size ? V1 : V2;
6774     else if (V != (Mask[i] < Size ? V1 : V2))
6775       return SDValue(); // Can only let one input through the mask.
6776
6777     VMaskOps[i] = AllOnes;
6778   }
6779   if (!V)
6780     return SDValue(); // No non-zeroable elements!
6781
6782   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6783   V = DAG.getNode(VT.isFloatingPoint()
6784                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6785                   DL, VT, V, VMask);
6786   return V;
6787 }
6788
6789 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6790 ///
6791 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6792 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6793 /// matches elements from one of the input vectors shuffled to the left or
6794 /// right with zeroable elements 'shifted in'. It handles both the strictly
6795 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6796 /// quad word lane.
6797 ///
6798 /// PSHL : (little-endian) left bit shift.
6799 /// [ zz, 0, zz,  2 ]
6800 /// [ -1, 4, zz, -1 ]
6801 /// PSRL : (little-endian) right bit shift.
6802 /// [  1, zz,  3, zz]
6803 /// [ -1, -1,  7, zz]
6804 /// PSLLDQ : (little-endian) left byte shift
6805 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6806 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6807 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6808 /// PSRLDQ : (little-endian) right byte shift
6809 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6810 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6811 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6812 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6813                                          SDValue V2, ArrayRef<int> Mask,
6814                                          SelectionDAG &DAG) {
6815   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6816
6817   int Size = Mask.size();
6818   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6819
6820   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6821     for (int i = 0; i < Size; i += Scale)
6822       for (int j = 0; j < Shift; ++j)
6823         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6824           return false;
6825
6826     return true;
6827   };
6828
6829   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6830     for (int i = 0; i != Size; i += Scale) {
6831       unsigned Pos = Left ? i + Shift : i;
6832       unsigned Low = Left ? i : i + Shift;
6833       unsigned Len = Scale - Shift;
6834       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6835                                       Low + (V == V1 ? 0 : Size)))
6836         return SDValue();
6837     }
6838
6839     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6840     bool ByteShift = ShiftEltBits > 64;
6841     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6842                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6843     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6844
6845     // Normalize the scale for byte shifts to still produce an i64 element
6846     // type.
6847     Scale = ByteShift ? Scale / 2 : Scale;
6848
6849     // We need to round trip through the appropriate type for the shift.
6850     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6851     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6852     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6853            "Illegal integer vector type");
6854     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6855
6856     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6857                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6858     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6859   };
6860
6861   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6862   // keep doubling the size of the integer elements up to that. We can
6863   // then shift the elements of the integer vector by whole multiples of
6864   // their width within the elements of the larger integer vector. Test each
6865   // multiple to see if we can find a match with the moved element indices
6866   // and that the shifted in elements are all zeroable.
6867   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6868     for (int Shift = 1; Shift != Scale; ++Shift)
6869       for (bool Left : {true, false})
6870         if (CheckZeros(Shift, Scale, Left))
6871           for (SDValue V : {V1, V2})
6872             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6873               return Match;
6874
6875   // no match
6876   return SDValue();
6877 }
6878
6879 /// \brief Lower a vector shuffle as a zero or any extension.
6880 ///
6881 /// Given a specific number of elements, element bit width, and extension
6882 /// stride, produce either a zero or any extension based on the available
6883 /// features of the subtarget.
6884 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6885     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6886     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6887   assert(Scale > 1 && "Need a scale to extend.");
6888   int NumElements = VT.getVectorNumElements();
6889   int EltBits = VT.getScalarSizeInBits();
6890   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6891          "Only 8, 16, and 32 bit elements can be extended.");
6892   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6893
6894   // Found a valid zext mask! Try various lowering strategies based on the
6895   // input type and available ISA extensions.
6896   if (Subtarget->hasSSE41()) {
6897     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6898                                  NumElements / Scale);
6899     return DAG.getNode(ISD::BITCAST, DL, VT,
6900                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6901   }
6902
6903   // For any extends we can cheat for larger element sizes and use shuffle
6904   // instructions that can fold with a load and/or copy.
6905   if (AnyExt && EltBits == 32) {
6906     int PSHUFDMask[4] = {0, -1, 1, -1};
6907     return DAG.getNode(
6908         ISD::BITCAST, DL, VT,
6909         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6910                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6911                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6912   }
6913   if (AnyExt && EltBits == 16 && Scale > 2) {
6914     int PSHUFDMask[4] = {0, -1, 0, -1};
6915     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6916                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6917                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6918     int PSHUFHWMask[4] = {1, -1, -1, -1};
6919     return DAG.getNode(
6920         ISD::BITCAST, DL, VT,
6921         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6922                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6923                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6924   }
6925
6926   // If this would require more than 2 unpack instructions to expand, use
6927   // pshufb when available. We can only use more than 2 unpack instructions
6928   // when zero extending i8 elements which also makes it easier to use pshufb.
6929   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6930     assert(NumElements == 16 && "Unexpected byte vector width!");
6931     SDValue PSHUFBMask[16];
6932     for (int i = 0; i < 16; ++i)
6933       PSHUFBMask[i] =
6934           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6935     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6936     return DAG.getNode(ISD::BITCAST, DL, VT,
6937                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6938                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6939                                                MVT::v16i8, PSHUFBMask)));
6940   }
6941
6942   // Otherwise emit a sequence of unpacks.
6943   do {
6944     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6945     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6946                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6947     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6948     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6949     Scale /= 2;
6950     EltBits *= 2;
6951     NumElements /= 2;
6952   } while (Scale > 1);
6953   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6954 }
6955
6956 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6957 ///
6958 /// This routine will try to do everything in its power to cleverly lower
6959 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6960 /// check for the profitability of this lowering,  it tries to aggressively
6961 /// match this pattern. It will use all of the micro-architectural details it
6962 /// can to emit an efficient lowering. It handles both blends with all-zero
6963 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6964 /// masking out later).
6965 ///
6966 /// The reason we have dedicated lowering for zext-style shuffles is that they
6967 /// are both incredibly common and often quite performance sensitive.
6968 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6969     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6970     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6971   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6972
6973   int Bits = VT.getSizeInBits();
6974   int NumElements = VT.getVectorNumElements();
6975   assert(VT.getScalarSizeInBits() <= 32 &&
6976          "Exceeds 32-bit integer zero extension limit");
6977   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6978
6979   // Define a helper function to check a particular ext-scale and lower to it if
6980   // valid.
6981   auto Lower = [&](int Scale) -> SDValue {
6982     SDValue InputV;
6983     bool AnyExt = true;
6984     for (int i = 0; i < NumElements; ++i) {
6985       if (Mask[i] == -1)
6986         continue; // Valid anywhere but doesn't tell us anything.
6987       if (i % Scale != 0) {
6988         // Each of the extended elements need to be zeroable.
6989         if (!Zeroable[i])
6990           return SDValue();
6991
6992         // We no longer are in the anyext case.
6993         AnyExt = false;
6994         continue;
6995       }
6996
6997       // Each of the base elements needs to be consecutive indices into the
6998       // same input vector.
6999       SDValue V = Mask[i] < NumElements ? V1 : V2;
7000       if (!InputV)
7001         InputV = V;
7002       else if (InputV != V)
7003         return SDValue(); // Flip-flopping inputs.
7004
7005       if (Mask[i] % NumElements != i / Scale)
7006         return SDValue(); // Non-consecutive strided elements.
7007     }
7008
7009     // If we fail to find an input, we have a zero-shuffle which should always
7010     // have already been handled.
7011     // FIXME: Maybe handle this here in case during blending we end up with one?
7012     if (!InputV)
7013       return SDValue();
7014
7015     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7016         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
7017   };
7018
7019   // The widest scale possible for extending is to a 64-bit integer.
7020   assert(Bits % 64 == 0 &&
7021          "The number of bits in a vector must be divisible by 64 on x86!");
7022   int NumExtElements = Bits / 64;
7023
7024   // Each iteration, try extending the elements half as much, but into twice as
7025   // many elements.
7026   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7027     assert(NumElements % NumExtElements == 0 &&
7028            "The input vector size must be divisible by the extended size.");
7029     if (SDValue V = Lower(NumElements / NumExtElements))
7030       return V;
7031   }
7032
7033   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7034   if (Bits != 128)
7035     return SDValue();
7036
7037   // Returns one of the source operands if the shuffle can be reduced to a
7038   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7039   auto CanZExtLowHalf = [&]() {
7040     for (int i = NumElements / 2; i != NumElements; ++i)
7041       if (!Zeroable[i])
7042         return SDValue();
7043     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7044       return V1;
7045     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7046       return V2;
7047     return SDValue();
7048   };
7049
7050   if (SDValue V = CanZExtLowHalf()) {
7051     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
7052     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7053     return DAG.getNode(ISD::BITCAST, DL, VT, V);
7054   }
7055
7056   // No viable ext lowering found.
7057   return SDValue();
7058 }
7059
7060 /// \brief Try to get a scalar value for a specific element of a vector.
7061 ///
7062 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7063 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7064                                               SelectionDAG &DAG) {
7065   MVT VT = V.getSimpleValueType();
7066   MVT EltVT = VT.getVectorElementType();
7067   while (V.getOpcode() == ISD::BITCAST)
7068     V = V.getOperand(0);
7069   // If the bitcasts shift the element size, we can't extract an equivalent
7070   // element from it.
7071   MVT NewVT = V.getSimpleValueType();
7072   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7073     return SDValue();
7074
7075   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7076       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7077     // Ensure the scalar operand is the same size as the destination.
7078     // FIXME: Add support for scalar truncation where possible.
7079     SDValue S = V.getOperand(Idx);
7080     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7081       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7082   }
7083
7084   return SDValue();
7085 }
7086
7087 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7088 ///
7089 /// This is particularly important because the set of instructions varies
7090 /// significantly based on whether the operand is a load or not.
7091 static bool isShuffleFoldableLoad(SDValue V) {
7092   while (V.getOpcode() == ISD::BITCAST)
7093     V = V.getOperand(0);
7094
7095   return ISD::isNON_EXTLoad(V.getNode());
7096 }
7097
7098 /// \brief Try to lower insertion of a single element into a zero vector.
7099 ///
7100 /// This is a common pattern that we have especially efficient patterns to lower
7101 /// across all subtarget feature sets.
7102 static SDValue lowerVectorShuffleAsElementInsertion(
7103     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7104     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7105   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7106   MVT ExtVT = VT;
7107   MVT EltVT = VT.getVectorElementType();
7108
7109   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7110                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7111                 Mask.begin();
7112   bool IsV1Zeroable = true;
7113   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7114     if (i != V2Index && !Zeroable[i]) {
7115       IsV1Zeroable = false;
7116       break;
7117     }
7118
7119   // Check for a single input from a SCALAR_TO_VECTOR node.
7120   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7121   // all the smarts here sunk into that routine. However, the current
7122   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7123   // vector shuffle lowering is dead.
7124   if (SDValue V2S = getScalarValueForVectorElement(
7125           V2, Mask[V2Index] - Mask.size(), DAG)) {
7126     // We need to zext the scalar if it is smaller than an i32.
7127     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7128     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7129       // Using zext to expand a narrow element won't work for non-zero
7130       // insertions.
7131       if (!IsV1Zeroable)
7132         return SDValue();
7133
7134       // Zero-extend directly to i32.
7135       ExtVT = MVT::v4i32;
7136       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7137     }
7138     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7139   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7140              EltVT == MVT::i16) {
7141     // Either not inserting from the low element of the input or the input
7142     // element size is too small to use VZEXT_MOVL to clear the high bits.
7143     return SDValue();
7144   }
7145
7146   if (!IsV1Zeroable) {
7147     // If V1 can't be treated as a zero vector we have fewer options to lower
7148     // this. We can't support integer vectors or non-zero targets cheaply, and
7149     // the V1 elements can't be permuted in any way.
7150     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7151     if (!VT.isFloatingPoint() || V2Index != 0)
7152       return SDValue();
7153     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7154     V1Mask[V2Index] = -1;
7155     if (!isNoopShuffleMask(V1Mask))
7156       return SDValue();
7157     // This is essentially a special case blend operation, but if we have
7158     // general purpose blend operations, they are always faster. Bail and let
7159     // the rest of the lowering handle these as blends.
7160     if (Subtarget->hasSSE41())
7161       return SDValue();
7162
7163     // Otherwise, use MOVSD or MOVSS.
7164     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7165            "Only two types of floating point element types to handle!");
7166     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7167                        ExtVT, V1, V2);
7168   }
7169
7170   // This lowering only works for the low element with floating point vectors.
7171   if (VT.isFloatingPoint() && V2Index != 0)
7172     return SDValue();
7173
7174   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7175   if (ExtVT != VT)
7176     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7177
7178   if (V2Index != 0) {
7179     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7180     // the desired position. Otherwise it is more efficient to do a vector
7181     // shift left. We know that we can do a vector shift left because all
7182     // the inputs are zero.
7183     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7184       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7185       V2Shuffle[V2Index] = 0;
7186       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7187     } else {
7188       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7189       V2 = DAG.getNode(
7190           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7191           DAG.getConstant(
7192               V2Index * EltVT.getSizeInBits()/8, DL,
7193               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7194       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7195     }
7196   }
7197   return V2;
7198 }
7199
7200 /// \brief Try to lower broadcast of a single element.
7201 ///
7202 /// For convenience, this code also bundles all of the subtarget feature set
7203 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7204 /// a convenient way to factor it out.
7205 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7206                                              ArrayRef<int> Mask,
7207                                              const X86Subtarget *Subtarget,
7208                                              SelectionDAG &DAG) {
7209   if (!Subtarget->hasAVX())
7210     return SDValue();
7211   if (VT.isInteger() && !Subtarget->hasAVX2())
7212     return SDValue();
7213
7214   // Check that the mask is a broadcast.
7215   int BroadcastIdx = -1;
7216   for (int M : Mask)
7217     if (M >= 0 && BroadcastIdx == -1)
7218       BroadcastIdx = M;
7219     else if (M >= 0 && M != BroadcastIdx)
7220       return SDValue();
7221
7222   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7223                                             "a sorted mask where the broadcast "
7224                                             "comes from V1.");
7225
7226   // Go up the chain of (vector) values to find a scalar load that we can
7227   // combine with the broadcast.
7228   for (;;) {
7229     switch (V.getOpcode()) {
7230     case ISD::CONCAT_VECTORS: {
7231       int OperandSize = Mask.size() / V.getNumOperands();
7232       V = V.getOperand(BroadcastIdx / OperandSize);
7233       BroadcastIdx %= OperandSize;
7234       continue;
7235     }
7236
7237     case ISD::INSERT_SUBVECTOR: {
7238       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7239       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7240       if (!ConstantIdx)
7241         break;
7242
7243       int BeginIdx = (int)ConstantIdx->getZExtValue();
7244       int EndIdx =
7245           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7246       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7247         BroadcastIdx -= BeginIdx;
7248         V = VInner;
7249       } else {
7250         V = VOuter;
7251       }
7252       continue;
7253     }
7254     }
7255     break;
7256   }
7257
7258   // Check if this is a broadcast of a scalar. We special case lowering
7259   // for scalars so that we can more effectively fold with loads.
7260   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7261       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7262     V = V.getOperand(BroadcastIdx);
7263
7264     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7265     // Only AVX2 has register broadcasts.
7266     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7267       return SDValue();
7268   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7269     // We can't broadcast from a vector register without AVX2, and we can only
7270     // broadcast from the zero-element of a vector register.
7271     return SDValue();
7272   }
7273
7274   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7275 }
7276
7277 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7278 // INSERTPS when the V1 elements are already in the correct locations
7279 // because otherwise we can just always use two SHUFPS instructions which
7280 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7281 // perform INSERTPS if a single V1 element is out of place and all V2
7282 // elements are zeroable.
7283 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7284                                             ArrayRef<int> Mask,
7285                                             SelectionDAG &DAG) {
7286   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7287   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7288   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7289   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7290
7291   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7292
7293   unsigned ZMask = 0;
7294   int V1DstIndex = -1;
7295   int V2DstIndex = -1;
7296   bool V1UsedInPlace = false;
7297
7298   for (int i = 0; i < 4; ++i) {
7299     // Synthesize a zero mask from the zeroable elements (includes undefs).
7300     if (Zeroable[i]) {
7301       ZMask |= 1 << i;
7302       continue;
7303     }
7304
7305     // Flag if we use any V1 inputs in place.
7306     if (i == Mask[i]) {
7307       V1UsedInPlace = true;
7308       continue;
7309     }
7310
7311     // We can only insert a single non-zeroable element.
7312     if (V1DstIndex != -1 || V2DstIndex != -1)
7313       return SDValue();
7314
7315     if (Mask[i] < 4) {
7316       // V1 input out of place for insertion.
7317       V1DstIndex = i;
7318     } else {
7319       // V2 input for insertion.
7320       V2DstIndex = i;
7321     }
7322   }
7323
7324   // Don't bother if we have no (non-zeroable) element for insertion.
7325   if (V1DstIndex == -1 && V2DstIndex == -1)
7326     return SDValue();
7327
7328   // Determine element insertion src/dst indices. The src index is from the
7329   // start of the inserted vector, not the start of the concatenated vector.
7330   unsigned V2SrcIndex = 0;
7331   if (V1DstIndex != -1) {
7332     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7333     // and don't use the original V2 at all.
7334     V2SrcIndex = Mask[V1DstIndex];
7335     V2DstIndex = V1DstIndex;
7336     V2 = V1;
7337   } else {
7338     V2SrcIndex = Mask[V2DstIndex] - 4;
7339   }
7340
7341   // If no V1 inputs are used in place, then the result is created only from
7342   // the zero mask and the V2 insertion - so remove V1 dependency.
7343   if (!V1UsedInPlace)
7344     V1 = DAG.getUNDEF(MVT::v4f32);
7345
7346   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7347   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7348
7349   // Insert the V2 element into the desired position.
7350   SDLoc DL(Op);
7351   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7352                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7353 }
7354
7355 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7356 /// UNPCK instruction.
7357 ///
7358 /// This specifically targets cases where we end up with alternating between
7359 /// the two inputs, and so can permute them into something that feeds a single
7360 /// UNPCK instruction. Note that this routine only targets integer vectors
7361 /// because for floating point vectors we have a generalized SHUFPS lowering
7362 /// strategy that handles everything that doesn't *exactly* match an unpack,
7363 /// making this clever lowering unnecessary.
7364 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7365                                           SDValue V2, ArrayRef<int> Mask,
7366                                           SelectionDAG &DAG) {
7367   assert(!VT.isFloatingPoint() &&
7368          "This routine only supports integer vectors.");
7369   assert(!isSingleInputShuffleMask(Mask) &&
7370          "This routine should only be used when blending two inputs.");
7371   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7372
7373   int Size = Mask.size();
7374
7375   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7376     return M >= 0 && M % Size < Size / 2;
7377   });
7378   int NumHiInputs = std::count_if(
7379       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7380
7381   bool UnpackLo = NumLoInputs >= NumHiInputs;
7382
7383   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7384     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7385     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7386
7387     for (int i = 0; i < Size; ++i) {
7388       if (Mask[i] < 0)
7389         continue;
7390
7391       // Each element of the unpack contains Scale elements from this mask.
7392       int UnpackIdx = i / Scale;
7393
7394       // We only handle the case where V1 feeds the first slots of the unpack.
7395       // We rely on canonicalization to ensure this is the case.
7396       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7397         return SDValue();
7398
7399       // Setup the mask for this input. The indexing is tricky as we have to
7400       // handle the unpack stride.
7401       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7402       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7403           Mask[i] % Size;
7404     }
7405
7406     // If we will have to shuffle both inputs to use the unpack, check whether
7407     // we can just unpack first and shuffle the result. If so, skip this unpack.
7408     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7409         !isNoopShuffleMask(V2Mask))
7410       return SDValue();
7411
7412     // Shuffle the inputs into place.
7413     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7414     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7415
7416     // Cast the inputs to the type we will use to unpack them.
7417     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7418     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7419
7420     // Unpack the inputs and cast the result back to the desired type.
7421     return DAG.getNode(ISD::BITCAST, DL, VT,
7422                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7423                                    DL, UnpackVT, V1, V2));
7424   };
7425
7426   // We try each unpack from the largest to the smallest to try and find one
7427   // that fits this mask.
7428   int OrigNumElements = VT.getVectorNumElements();
7429   int OrigScalarSize = VT.getScalarSizeInBits();
7430   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7431     int Scale = ScalarSize / OrigScalarSize;
7432     int NumElements = OrigNumElements / Scale;
7433     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7434     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7435       return Unpack;
7436   }
7437
7438   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7439   // initial unpack.
7440   if (NumLoInputs == 0 || NumHiInputs == 0) {
7441     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7442            "We have to have *some* inputs!");
7443     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7444
7445     // FIXME: We could consider the total complexity of the permute of each
7446     // possible unpacking. Or at the least we should consider how many
7447     // half-crossings are created.
7448     // FIXME: We could consider commuting the unpacks.
7449
7450     SmallVector<int, 32> PermMask;
7451     PermMask.assign(Size, -1);
7452     for (int i = 0; i < Size; ++i) {
7453       if (Mask[i] < 0)
7454         continue;
7455
7456       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7457
7458       PermMask[i] =
7459           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7460     }
7461     return DAG.getVectorShuffle(
7462         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7463                             DL, VT, V1, V2),
7464         DAG.getUNDEF(VT), PermMask);
7465   }
7466
7467   return SDValue();
7468 }
7469
7470 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7471 ///
7472 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7473 /// support for floating point shuffles but not integer shuffles. These
7474 /// instructions will incur a domain crossing penalty on some chips though so
7475 /// it is better to avoid lowering through this for integer vectors where
7476 /// possible.
7477 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7478                                        const X86Subtarget *Subtarget,
7479                                        SelectionDAG &DAG) {
7480   SDLoc DL(Op);
7481   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7482   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7483   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7484   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7485   ArrayRef<int> Mask = SVOp->getMask();
7486   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7487
7488   if (isSingleInputShuffleMask(Mask)) {
7489     // Use low duplicate instructions for masks that match their pattern.
7490     if (Subtarget->hasSSE3())
7491       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7492         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7493
7494     // Straight shuffle of a single input vector. Simulate this by using the
7495     // single input as both of the "inputs" to this instruction..
7496     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7497
7498     if (Subtarget->hasAVX()) {
7499       // If we have AVX, we can use VPERMILPS which will allow folding a load
7500       // into the shuffle.
7501       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7502                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7503     }
7504
7505     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7506                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7507   }
7508   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7509   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7510
7511   // If we have a single input, insert that into V1 if we can do so cheaply.
7512   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7513     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7514             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7515       return Insertion;
7516     // Try inverting the insertion since for v2 masks it is easy to do and we
7517     // can't reliably sort the mask one way or the other.
7518     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7519                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7520     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7521             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7522       return Insertion;
7523   }
7524
7525   // Try to use one of the special instruction patterns to handle two common
7526   // blend patterns if a zero-blend above didn't work.
7527   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7528       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7529     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7530       // We can either use a special instruction to load over the low double or
7531       // to move just the low double.
7532       return DAG.getNode(
7533           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7534           DL, MVT::v2f64, V2,
7535           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7536
7537   if (Subtarget->hasSSE41())
7538     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7539                                                   Subtarget, DAG))
7540       return Blend;
7541
7542   // Use dedicated unpack instructions for masks that match their pattern.
7543   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7544     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7545   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7546     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7547
7548   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7549   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7550                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7551 }
7552
7553 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7554 ///
7555 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7556 /// the integer unit to minimize domain crossing penalties. However, for blends
7557 /// it falls back to the floating point shuffle operation with appropriate bit
7558 /// casting.
7559 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7560                                        const X86Subtarget *Subtarget,
7561                                        SelectionDAG &DAG) {
7562   SDLoc DL(Op);
7563   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7564   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7565   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7566   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7567   ArrayRef<int> Mask = SVOp->getMask();
7568   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7569
7570   if (isSingleInputShuffleMask(Mask)) {
7571     // Check for being able to broadcast a single element.
7572     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7573                                                           Mask, Subtarget, DAG))
7574       return Broadcast;
7575
7576     // Straight shuffle of a single input vector. For everything from SSE2
7577     // onward this has a single fast instruction with no scary immediates.
7578     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7579     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7580     int WidenedMask[4] = {
7581         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7582         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7583     return DAG.getNode(
7584         ISD::BITCAST, DL, MVT::v2i64,
7585         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7586                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7587   }
7588   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7589   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7590   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7591   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7592
7593   // If we have a blend of two PACKUS operations an the blend aligns with the
7594   // low and half halves, we can just merge the PACKUS operations. This is
7595   // particularly important as it lets us merge shuffles that this routine itself
7596   // creates.
7597   auto GetPackNode = [](SDValue V) {
7598     while (V.getOpcode() == ISD::BITCAST)
7599       V = V.getOperand(0);
7600
7601     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7602   };
7603   if (SDValue V1Pack = GetPackNode(V1))
7604     if (SDValue V2Pack = GetPackNode(V2))
7605       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7606                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7607                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7608                                                   : V1Pack.getOperand(1),
7609                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7610                                                   : V2Pack.getOperand(1)));
7611
7612   // Try to use shift instructions.
7613   if (SDValue Shift =
7614           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7615     return Shift;
7616
7617   // When loading a scalar and then shuffling it into a vector we can often do
7618   // the insertion cheaply.
7619   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7620           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7621     return Insertion;
7622   // Try inverting the insertion since for v2 masks it is easy to do and we
7623   // can't reliably sort the mask one way or the other.
7624   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7625   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7626           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7627     return Insertion;
7628
7629   // We have different paths for blend lowering, but they all must use the
7630   // *exact* same predicate.
7631   bool IsBlendSupported = Subtarget->hasSSE41();
7632   if (IsBlendSupported)
7633     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7634                                                   Subtarget, DAG))
7635       return Blend;
7636
7637   // Use dedicated unpack instructions for masks that match their pattern.
7638   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7639     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7640   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7641     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7642
7643   // Try to use byte rotation instructions.
7644   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7645   if (Subtarget->hasSSSE3())
7646     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7647             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7648       return Rotate;
7649
7650   // If we have direct support for blends, we should lower by decomposing into
7651   // a permute. That will be faster than the domain cross.
7652   if (IsBlendSupported)
7653     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7654                                                       Mask, DAG);
7655
7656   // We implement this with SHUFPD which is pretty lame because it will likely
7657   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7658   // However, all the alternatives are still more cycles and newer chips don't
7659   // have this problem. It would be really nice if x86 had better shuffles here.
7660   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7661   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7662   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7663                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7664 }
7665
7666 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7667 ///
7668 /// This is used to disable more specialized lowerings when the shufps lowering
7669 /// will happen to be efficient.
7670 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7671   // This routine only handles 128-bit shufps.
7672   assert(Mask.size() == 4 && "Unsupported mask size!");
7673
7674   // To lower with a single SHUFPS we need to have the low half and high half
7675   // each requiring a single input.
7676   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7677     return false;
7678   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7679     return false;
7680
7681   return true;
7682 }
7683
7684 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7685 ///
7686 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7687 /// It makes no assumptions about whether this is the *best* lowering, it simply
7688 /// uses it.
7689 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7690                                             ArrayRef<int> Mask, SDValue V1,
7691                                             SDValue V2, SelectionDAG &DAG) {
7692   SDValue LowV = V1, HighV = V2;
7693   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7694
7695   int NumV2Elements =
7696       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7697
7698   if (NumV2Elements == 1) {
7699     int V2Index =
7700         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7701         Mask.begin();
7702
7703     // Compute the index adjacent to V2Index and in the same half by toggling
7704     // the low bit.
7705     int V2AdjIndex = V2Index ^ 1;
7706
7707     if (Mask[V2AdjIndex] == -1) {
7708       // Handles all the cases where we have a single V2 element and an undef.
7709       // This will only ever happen in the high lanes because we commute the
7710       // vector otherwise.
7711       if (V2Index < 2)
7712         std::swap(LowV, HighV);
7713       NewMask[V2Index] -= 4;
7714     } else {
7715       // Handle the case where the V2 element ends up adjacent to a V1 element.
7716       // To make this work, blend them together as the first step.
7717       int V1Index = V2AdjIndex;
7718       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7719       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7720                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7721
7722       // Now proceed to reconstruct the final blend as we have the necessary
7723       // high or low half formed.
7724       if (V2Index < 2) {
7725         LowV = V2;
7726         HighV = V1;
7727       } else {
7728         HighV = V2;
7729       }
7730       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7731       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7732     }
7733   } else if (NumV2Elements == 2) {
7734     if (Mask[0] < 4 && Mask[1] < 4) {
7735       // Handle the easy case where we have V1 in the low lanes and V2 in the
7736       // high lanes.
7737       NewMask[2] -= 4;
7738       NewMask[3] -= 4;
7739     } else if (Mask[2] < 4 && Mask[3] < 4) {
7740       // We also handle the reversed case because this utility may get called
7741       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7742       // arrange things in the right direction.
7743       NewMask[0] -= 4;
7744       NewMask[1] -= 4;
7745       HighV = V1;
7746       LowV = V2;
7747     } else {
7748       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7749       // trying to place elements directly, just blend them and set up the final
7750       // shuffle to place them.
7751
7752       // The first two blend mask elements are for V1, the second two are for
7753       // V2.
7754       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7755                           Mask[2] < 4 ? Mask[2] : Mask[3],
7756                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7757                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7758       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7759                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7760
7761       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7762       // a blend.
7763       LowV = HighV = V1;
7764       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7765       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7766       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7767       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7768     }
7769   }
7770   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7771                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7772 }
7773
7774 /// \brief Lower 4-lane 32-bit floating point shuffles.
7775 ///
7776 /// Uses instructions exclusively from the floating point unit to minimize
7777 /// domain crossing penalties, as these are sufficient to implement all v4f32
7778 /// shuffles.
7779 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7780                                        const X86Subtarget *Subtarget,
7781                                        SelectionDAG &DAG) {
7782   SDLoc DL(Op);
7783   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7784   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7785   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7786   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7787   ArrayRef<int> Mask = SVOp->getMask();
7788   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7789
7790   int NumV2Elements =
7791       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7792
7793   if (NumV2Elements == 0) {
7794     // Check for being able to broadcast a single element.
7795     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7796                                                           Mask, Subtarget, DAG))
7797       return Broadcast;
7798
7799     // Use even/odd duplicate instructions for masks that match their pattern.
7800     if (Subtarget->hasSSE3()) {
7801       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7802         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7803       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7804         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7805     }
7806
7807     if (Subtarget->hasAVX()) {
7808       // If we have AVX, we can use VPERMILPS which will allow folding a load
7809       // into the shuffle.
7810       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7811                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7812     }
7813
7814     // Otherwise, use a straight shuffle of a single input vector. We pass the
7815     // input vector to both operands to simulate this with a SHUFPS.
7816     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7817                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7818   }
7819
7820   // There are special ways we can lower some single-element blends. However, we
7821   // have custom ways we can lower more complex single-element blends below that
7822   // we defer to if both this and BLENDPS fail to match, so restrict this to
7823   // when the V2 input is targeting element 0 of the mask -- that is the fast
7824   // case here.
7825   if (NumV2Elements == 1 && Mask[0] >= 4)
7826     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7827                                                          Mask, Subtarget, DAG))
7828       return V;
7829
7830   if (Subtarget->hasSSE41()) {
7831     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7832                                                   Subtarget, DAG))
7833       return Blend;
7834
7835     // Use INSERTPS if we can complete the shuffle efficiently.
7836     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7837       return V;
7838
7839     if (!isSingleSHUFPSMask(Mask))
7840       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7841               DL, MVT::v4f32, V1, V2, Mask, DAG))
7842         return BlendPerm;
7843   }
7844
7845   // Use dedicated unpack instructions for masks that match their pattern.
7846   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7847     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7848   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7849     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7850   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7851     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7852   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7853     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7854
7855   // Otherwise fall back to a SHUFPS lowering strategy.
7856   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7857 }
7858
7859 /// \brief Lower 4-lane i32 vector shuffles.
7860 ///
7861 /// We try to handle these with integer-domain shuffles where we can, but for
7862 /// blends we use the floating point domain blend instructions.
7863 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7864                                        const X86Subtarget *Subtarget,
7865                                        SelectionDAG &DAG) {
7866   SDLoc DL(Op);
7867   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7868   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7869   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7870   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7871   ArrayRef<int> Mask = SVOp->getMask();
7872   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7873
7874   // Whenever we can lower this as a zext, that instruction is strictly faster
7875   // than any alternative. It also allows us to fold memory operands into the
7876   // shuffle in many cases.
7877   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7878                                                          Mask, Subtarget, DAG))
7879     return ZExt;
7880
7881   int NumV2Elements =
7882       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7883
7884   if (NumV2Elements == 0) {
7885     // Check for being able to broadcast a single element.
7886     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7887                                                           Mask, Subtarget, DAG))
7888       return Broadcast;
7889
7890     // Straight shuffle of a single input vector. For everything from SSE2
7891     // onward this has a single fast instruction with no scary immediates.
7892     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7893     // but we aren't actually going to use the UNPCK instruction because doing
7894     // so prevents folding a load into this instruction or making a copy.
7895     const int UnpackLoMask[] = {0, 0, 1, 1};
7896     const int UnpackHiMask[] = {2, 2, 3, 3};
7897     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7898       Mask = UnpackLoMask;
7899     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7900       Mask = UnpackHiMask;
7901
7902     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7903                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7904   }
7905
7906   // Try to use shift instructions.
7907   if (SDValue Shift =
7908           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7909     return Shift;
7910
7911   // There are special ways we can lower some single-element blends.
7912   if (NumV2Elements == 1)
7913     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7914                                                          Mask, Subtarget, DAG))
7915       return V;
7916
7917   // We have different paths for blend lowering, but they all must use the
7918   // *exact* same predicate.
7919   bool IsBlendSupported = Subtarget->hasSSE41();
7920   if (IsBlendSupported)
7921     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7922                                                   Subtarget, DAG))
7923       return Blend;
7924
7925   if (SDValue Masked =
7926           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7927     return Masked;
7928
7929   // Use dedicated unpack instructions for masks that match their pattern.
7930   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7931     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7932   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7933     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7934   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7935     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7936   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7937     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7938
7939   // Try to use byte rotation instructions.
7940   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7941   if (Subtarget->hasSSSE3())
7942     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7943             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7944       return Rotate;
7945
7946   // If we have direct support for blends, we should lower by decomposing into
7947   // a permute. That will be faster than the domain cross.
7948   if (IsBlendSupported)
7949     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7950                                                       Mask, DAG);
7951
7952   // Try to lower by permuting the inputs into an unpack instruction.
7953   if (SDValue Unpack =
7954           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7955     return Unpack;
7956
7957   // We implement this with SHUFPS because it can blend from two vectors.
7958   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7959   // up the inputs, bypassing domain shift penalties that we would encur if we
7960   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7961   // relevant.
7962   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7963                      DAG.getVectorShuffle(
7964                          MVT::v4f32, DL,
7965                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7966                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7967 }
7968
7969 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7970 /// shuffle lowering, and the most complex part.
7971 ///
7972 /// The lowering strategy is to try to form pairs of input lanes which are
7973 /// targeted at the same half of the final vector, and then use a dword shuffle
7974 /// to place them onto the right half, and finally unpack the paired lanes into
7975 /// their final position.
7976 ///
7977 /// The exact breakdown of how to form these dword pairs and align them on the
7978 /// correct sides is really tricky. See the comments within the function for
7979 /// more of the details.
7980 ///
7981 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7982 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7983 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7984 /// vector, form the analogous 128-bit 8-element Mask.
7985 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7986     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7987     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7988   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7989   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7990
7991   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7992   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7993   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7994
7995   SmallVector<int, 4> LoInputs;
7996   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7997                [](int M) { return M >= 0; });
7998   std::sort(LoInputs.begin(), LoInputs.end());
7999   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8000   SmallVector<int, 4> HiInputs;
8001   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8002                [](int M) { return M >= 0; });
8003   std::sort(HiInputs.begin(), HiInputs.end());
8004   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8005   int NumLToL =
8006       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8007   int NumHToL = LoInputs.size() - NumLToL;
8008   int NumLToH =
8009       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8010   int NumHToH = HiInputs.size() - NumLToH;
8011   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8012   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8013   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8014   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8015
8016   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8017   // such inputs we can swap two of the dwords across the half mark and end up
8018   // with <=2 inputs to each half in each half. Once there, we can fall through
8019   // to the generic code below. For example:
8020   //
8021   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8022   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8023   //
8024   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8025   // and an existing 2-into-2 on the other half. In this case we may have to
8026   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8027   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8028   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8029   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8030   // half than the one we target for fixing) will be fixed when we re-enter this
8031   // path. We will also combine away any sequence of PSHUFD instructions that
8032   // result into a single instruction. Here is an example of the tricky case:
8033   //
8034   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8035   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8036   //
8037   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8038   //
8039   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8040   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8041   //
8042   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8043   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8044   //
8045   // The result is fine to be handled by the generic logic.
8046   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8047                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8048                           int AOffset, int BOffset) {
8049     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8050            "Must call this with A having 3 or 1 inputs from the A half.");
8051     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8052            "Must call this with B having 1 or 3 inputs from the B half.");
8053     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8054            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8055
8056     // Compute the index of dword with only one word among the three inputs in
8057     // a half by taking the sum of the half with three inputs and subtracting
8058     // the sum of the actual three inputs. The difference is the remaining
8059     // slot.
8060     int ADWord, BDWord;
8061     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8062     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8063     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8064     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8065     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8066     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8067     int TripleNonInputIdx =
8068         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8069     TripleDWord = TripleNonInputIdx / 2;
8070
8071     // We use xor with one to compute the adjacent DWord to whichever one the
8072     // OneInput is in.
8073     OneInputDWord = (OneInput / 2) ^ 1;
8074
8075     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8076     // and BToA inputs. If there is also such a problem with the BToB and AToB
8077     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8078     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8079     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8080     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8081       // Compute how many inputs will be flipped by swapping these DWords. We
8082       // need
8083       // to balance this to ensure we don't form a 3-1 shuffle in the other
8084       // half.
8085       int NumFlippedAToBInputs =
8086           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8087           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8088       int NumFlippedBToBInputs =
8089           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8090           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8091       if ((NumFlippedAToBInputs == 1 &&
8092            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8093           (NumFlippedBToBInputs == 1 &&
8094            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8095         // We choose whether to fix the A half or B half based on whether that
8096         // half has zero flipped inputs. At zero, we may not be able to fix it
8097         // with that half. We also bias towards fixing the B half because that
8098         // will more commonly be the high half, and we have to bias one way.
8099         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8100                                                        ArrayRef<int> Inputs) {
8101           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8102           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8103                                          PinnedIdx ^ 1) != Inputs.end();
8104           // Determine whether the free index is in the flipped dword or the
8105           // unflipped dword based on where the pinned index is. We use this bit
8106           // in an xor to conditionally select the adjacent dword.
8107           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8108           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8109                                              FixFreeIdx) != Inputs.end();
8110           if (IsFixIdxInput == IsFixFreeIdxInput)
8111             FixFreeIdx += 1;
8112           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8113                                         FixFreeIdx) != Inputs.end();
8114           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8115                  "We need to be changing the number of flipped inputs!");
8116           int PSHUFHalfMask[] = {0, 1, 2, 3};
8117           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8118           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8119                           MVT::v8i16, V,
8120                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8121
8122           for (int &M : Mask)
8123             if (M != -1 && M == FixIdx)
8124               M = FixFreeIdx;
8125             else if (M != -1 && M == FixFreeIdx)
8126               M = FixIdx;
8127         };
8128         if (NumFlippedBToBInputs != 0) {
8129           int BPinnedIdx =
8130               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8131           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8132         } else {
8133           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8134           int APinnedIdx =
8135               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8136           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8137         }
8138       }
8139     }
8140
8141     int PSHUFDMask[] = {0, 1, 2, 3};
8142     PSHUFDMask[ADWord] = BDWord;
8143     PSHUFDMask[BDWord] = ADWord;
8144     V = DAG.getNode(ISD::BITCAST, DL, VT,
8145                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8146                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8147                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8148                                                            DAG)));
8149
8150     // Adjust the mask to match the new locations of A and B.
8151     for (int &M : Mask)
8152       if (M != -1 && M/2 == ADWord)
8153         M = 2 * BDWord + M % 2;
8154       else if (M != -1 && M/2 == BDWord)
8155         M = 2 * ADWord + M % 2;
8156
8157     // Recurse back into this routine to re-compute state now that this isn't
8158     // a 3 and 1 problem.
8159     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8160                                                      DAG);
8161   };
8162   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8163     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8164   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8165     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8166
8167   // At this point there are at most two inputs to the low and high halves from
8168   // each half. That means the inputs can always be grouped into dwords and
8169   // those dwords can then be moved to the correct half with a dword shuffle.
8170   // We use at most one low and one high word shuffle to collect these paired
8171   // inputs into dwords, and finally a dword shuffle to place them.
8172   int PSHUFLMask[4] = {-1, -1, -1, -1};
8173   int PSHUFHMask[4] = {-1, -1, -1, -1};
8174   int PSHUFDMask[4] = {-1, -1, -1, -1};
8175
8176   // First fix the masks for all the inputs that are staying in their
8177   // original halves. This will then dictate the targets of the cross-half
8178   // shuffles.
8179   auto fixInPlaceInputs =
8180       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8181                     MutableArrayRef<int> SourceHalfMask,
8182                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8183     if (InPlaceInputs.empty())
8184       return;
8185     if (InPlaceInputs.size() == 1) {
8186       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8187           InPlaceInputs[0] - HalfOffset;
8188       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8189       return;
8190     }
8191     if (IncomingInputs.empty()) {
8192       // Just fix all of the in place inputs.
8193       for (int Input : InPlaceInputs) {
8194         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8195         PSHUFDMask[Input / 2] = Input / 2;
8196       }
8197       return;
8198     }
8199
8200     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8201     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8202         InPlaceInputs[0] - HalfOffset;
8203     // Put the second input next to the first so that they are packed into
8204     // a dword. We find the adjacent index by toggling the low bit.
8205     int AdjIndex = InPlaceInputs[0] ^ 1;
8206     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8207     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8208     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8209   };
8210   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8211   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8212
8213   // Now gather the cross-half inputs and place them into a free dword of
8214   // their target half.
8215   // FIXME: This operation could almost certainly be simplified dramatically to
8216   // look more like the 3-1 fixing operation.
8217   auto moveInputsToRightHalf = [&PSHUFDMask](
8218       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8219       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8220       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8221       int DestOffset) {
8222     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8223       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8224     };
8225     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8226                                                int Word) {
8227       int LowWord = Word & ~1;
8228       int HighWord = Word | 1;
8229       return isWordClobbered(SourceHalfMask, LowWord) ||
8230              isWordClobbered(SourceHalfMask, HighWord);
8231     };
8232
8233     if (IncomingInputs.empty())
8234       return;
8235
8236     if (ExistingInputs.empty()) {
8237       // Map any dwords with inputs from them into the right half.
8238       for (int Input : IncomingInputs) {
8239         // If the source half mask maps over the inputs, turn those into
8240         // swaps and use the swapped lane.
8241         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8242           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8243             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8244                 Input - SourceOffset;
8245             // We have to swap the uses in our half mask in one sweep.
8246             for (int &M : HalfMask)
8247               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8248                 M = Input;
8249               else if (M == Input)
8250                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8251           } else {
8252             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8253                        Input - SourceOffset &&
8254                    "Previous placement doesn't match!");
8255           }
8256           // Note that this correctly re-maps both when we do a swap and when
8257           // we observe the other side of the swap above. We rely on that to
8258           // avoid swapping the members of the input list directly.
8259           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8260         }
8261
8262         // Map the input's dword into the correct half.
8263         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8264           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8265         else
8266           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8267                      Input / 2 &&
8268                  "Previous placement doesn't match!");
8269       }
8270
8271       // And just directly shift any other-half mask elements to be same-half
8272       // as we will have mirrored the dword containing the element into the
8273       // same position within that half.
8274       for (int &M : HalfMask)
8275         if (M >= SourceOffset && M < SourceOffset + 4) {
8276           M = M - SourceOffset + DestOffset;
8277           assert(M >= 0 && "This should never wrap below zero!");
8278         }
8279       return;
8280     }
8281
8282     // Ensure we have the input in a viable dword of its current half. This
8283     // is particularly tricky because the original position may be clobbered
8284     // by inputs being moved and *staying* in that half.
8285     if (IncomingInputs.size() == 1) {
8286       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8287         int InputFixed = std::find(std::begin(SourceHalfMask),
8288                                    std::end(SourceHalfMask), -1) -
8289                          std::begin(SourceHalfMask) + SourceOffset;
8290         SourceHalfMask[InputFixed - SourceOffset] =
8291             IncomingInputs[0] - SourceOffset;
8292         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8293                      InputFixed);
8294         IncomingInputs[0] = InputFixed;
8295       }
8296     } else if (IncomingInputs.size() == 2) {
8297       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8298           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8299         // We have two non-adjacent or clobbered inputs we need to extract from
8300         // the source half. To do this, we need to map them into some adjacent
8301         // dword slot in the source mask.
8302         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8303                               IncomingInputs[1] - SourceOffset};
8304
8305         // If there is a free slot in the source half mask adjacent to one of
8306         // the inputs, place the other input in it. We use (Index XOR 1) to
8307         // compute an adjacent index.
8308         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8309             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8310           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8311           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8312           InputsFixed[1] = InputsFixed[0] ^ 1;
8313         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8314                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8315           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8316           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8317           InputsFixed[0] = InputsFixed[1] ^ 1;
8318         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8319                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8320           // The two inputs are in the same DWord but it is clobbered and the
8321           // adjacent DWord isn't used at all. Move both inputs to the free
8322           // slot.
8323           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8324           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8325           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8326           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8327         } else {
8328           // The only way we hit this point is if there is no clobbering
8329           // (because there are no off-half inputs to this half) and there is no
8330           // free slot adjacent to one of the inputs. In this case, we have to
8331           // swap an input with a non-input.
8332           for (int i = 0; i < 4; ++i)
8333             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8334                    "We can't handle any clobbers here!");
8335           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8336                  "Cannot have adjacent inputs here!");
8337
8338           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8339           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8340
8341           // We also have to update the final source mask in this case because
8342           // it may need to undo the above swap.
8343           for (int &M : FinalSourceHalfMask)
8344             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8345               M = InputsFixed[1] + SourceOffset;
8346             else if (M == InputsFixed[1] + SourceOffset)
8347               M = (InputsFixed[0] ^ 1) + SourceOffset;
8348
8349           InputsFixed[1] = InputsFixed[0] ^ 1;
8350         }
8351
8352         // Point everything at the fixed inputs.
8353         for (int &M : HalfMask)
8354           if (M == IncomingInputs[0])
8355             M = InputsFixed[0] + SourceOffset;
8356           else if (M == IncomingInputs[1])
8357             M = InputsFixed[1] + SourceOffset;
8358
8359         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8360         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8361       }
8362     } else {
8363       llvm_unreachable("Unhandled input size!");
8364     }
8365
8366     // Now hoist the DWord down to the right half.
8367     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8368     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8369     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8370     for (int &M : HalfMask)
8371       for (int Input : IncomingInputs)
8372         if (M == Input)
8373           M = FreeDWord * 2 + Input % 2;
8374   };
8375   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8376                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8377   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8378                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8379
8380   // Now enact all the shuffles we've computed to move the inputs into their
8381   // target half.
8382   if (!isNoopShuffleMask(PSHUFLMask))
8383     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8384                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8385   if (!isNoopShuffleMask(PSHUFHMask))
8386     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8387                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8388   if (!isNoopShuffleMask(PSHUFDMask))
8389     V = DAG.getNode(ISD::BITCAST, DL, VT,
8390                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8391                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8392                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8393                                                            DAG)));
8394
8395   // At this point, each half should contain all its inputs, and we can then
8396   // just shuffle them into their final position.
8397   assert(std::count_if(LoMask.begin(), LoMask.end(),
8398                        [](int M) { return M >= 4; }) == 0 &&
8399          "Failed to lift all the high half inputs to the low mask!");
8400   assert(std::count_if(HiMask.begin(), HiMask.end(),
8401                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8402          "Failed to lift all the low half inputs to the high mask!");
8403
8404   // Do a half shuffle for the low mask.
8405   if (!isNoopShuffleMask(LoMask))
8406     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8407                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8408
8409   // Do a half shuffle with the high mask after shifting its values down.
8410   for (int &M : HiMask)
8411     if (M >= 0)
8412       M -= 4;
8413   if (!isNoopShuffleMask(HiMask))
8414     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8415                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8416
8417   return V;
8418 }
8419
8420 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8421 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8422                                           SDValue V2, ArrayRef<int> Mask,
8423                                           SelectionDAG &DAG, bool &V1InUse,
8424                                           bool &V2InUse) {
8425   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8426   SDValue V1Mask[16];
8427   SDValue V2Mask[16];
8428   V1InUse = false;
8429   V2InUse = false;
8430
8431   int Size = Mask.size();
8432   int Scale = 16 / Size;
8433   for (int i = 0; i < 16; ++i) {
8434     if (Mask[i / Scale] == -1) {
8435       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8436     } else {
8437       const int ZeroMask = 0x80;
8438       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8439                                           : ZeroMask;
8440       int V2Idx = Mask[i / Scale] < Size
8441                       ? ZeroMask
8442                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8443       if (Zeroable[i / Scale])
8444         V1Idx = V2Idx = ZeroMask;
8445       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8446       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8447       V1InUse |= (ZeroMask != V1Idx);
8448       V2InUse |= (ZeroMask != V2Idx);
8449     }
8450   }
8451
8452   if (V1InUse)
8453     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8454                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8455                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8456   if (V2InUse)
8457     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8458                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8459                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8460
8461   // If we need shuffled inputs from both, blend the two.
8462   SDValue V;
8463   if (V1InUse && V2InUse)
8464     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8465   else
8466     V = V1InUse ? V1 : V2;
8467
8468   // Cast the result back to the correct type.
8469   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8470 }
8471
8472 /// \brief Generic lowering of 8-lane i16 shuffles.
8473 ///
8474 /// This handles both single-input shuffles and combined shuffle/blends with
8475 /// two inputs. The single input shuffles are immediately delegated to
8476 /// a dedicated lowering routine.
8477 ///
8478 /// The blends are lowered in one of three fundamental ways. If there are few
8479 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8480 /// of the input is significantly cheaper when lowered as an interleaving of
8481 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8482 /// halves of the inputs separately (making them have relatively few inputs)
8483 /// and then concatenate them.
8484 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8485                                        const X86Subtarget *Subtarget,
8486                                        SelectionDAG &DAG) {
8487   SDLoc DL(Op);
8488   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8489   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8490   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8491   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8492   ArrayRef<int> OrigMask = SVOp->getMask();
8493   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8494                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8495   MutableArrayRef<int> Mask(MaskStorage);
8496
8497   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8498
8499   // Whenever we can lower this as a zext, that instruction is strictly faster
8500   // than any alternative.
8501   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8502           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8503     return ZExt;
8504
8505   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8506   (void)isV1;
8507   auto isV2 = [](int M) { return M >= 8; };
8508
8509   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8510
8511   if (NumV2Inputs == 0) {
8512     // Check for being able to broadcast a single element.
8513     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8514                                                           Mask, Subtarget, DAG))
8515       return Broadcast;
8516
8517     // Try to use shift instructions.
8518     if (SDValue Shift =
8519             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8520       return Shift;
8521
8522     // Use dedicated unpack instructions for masks that match their pattern.
8523     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8524       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8525     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8526       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8527
8528     // Try to use byte rotation instructions.
8529     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8530                                                         Mask, Subtarget, DAG))
8531       return Rotate;
8532
8533     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8534                                                      Subtarget, DAG);
8535   }
8536
8537   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8538          "All single-input shuffles should be canonicalized to be V1-input "
8539          "shuffles.");
8540
8541   // Try to use shift instructions.
8542   if (SDValue Shift =
8543           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8544     return Shift;
8545
8546   // There are special ways we can lower some single-element blends.
8547   if (NumV2Inputs == 1)
8548     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8549                                                          Mask, Subtarget, DAG))
8550       return V;
8551
8552   // We have different paths for blend lowering, but they all must use the
8553   // *exact* same predicate.
8554   bool IsBlendSupported = Subtarget->hasSSE41();
8555   if (IsBlendSupported)
8556     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8557                                                   Subtarget, DAG))
8558       return Blend;
8559
8560   if (SDValue Masked =
8561           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8562     return Masked;
8563
8564   // Use dedicated unpack instructions for masks that match their pattern.
8565   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8566     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8567   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8568     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8569
8570   // Try to use byte rotation instructions.
8571   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8572           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8573     return Rotate;
8574
8575   if (SDValue BitBlend =
8576           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8577     return BitBlend;
8578
8579   if (SDValue Unpack =
8580           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8581     return Unpack;
8582
8583   // If we can't directly blend but can use PSHUFB, that will be better as it
8584   // can both shuffle and set up the inefficient blend.
8585   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8586     bool V1InUse, V2InUse;
8587     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8588                                       V1InUse, V2InUse);
8589   }
8590
8591   // We can always bit-blend if we have to so the fallback strategy is to
8592   // decompose into single-input permutes and blends.
8593   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8594                                                       Mask, DAG);
8595 }
8596
8597 /// \brief Check whether a compaction lowering can be done by dropping even
8598 /// elements and compute how many times even elements must be dropped.
8599 ///
8600 /// This handles shuffles which take every Nth element where N is a power of
8601 /// two. Example shuffle masks:
8602 ///
8603 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8604 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8605 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8606 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8607 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8608 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8609 ///
8610 /// Any of these lanes can of course be undef.
8611 ///
8612 /// This routine only supports N <= 3.
8613 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8614 /// for larger N.
8615 ///
8616 /// \returns N above, or the number of times even elements must be dropped if
8617 /// there is such a number. Otherwise returns zero.
8618 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8619   // Figure out whether we're looping over two inputs or just one.
8620   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8621
8622   // The modulus for the shuffle vector entries is based on whether this is
8623   // a single input or not.
8624   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8625   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8626          "We should only be called with masks with a power-of-2 size!");
8627
8628   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8629
8630   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8631   // and 2^3 simultaneously. This is because we may have ambiguity with
8632   // partially undef inputs.
8633   bool ViableForN[3] = {true, true, true};
8634
8635   for (int i = 0, e = Mask.size(); i < e; ++i) {
8636     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8637     // want.
8638     if (Mask[i] == -1)
8639       continue;
8640
8641     bool IsAnyViable = false;
8642     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8643       if (ViableForN[j]) {
8644         uint64_t N = j + 1;
8645
8646         // The shuffle mask must be equal to (i * 2^N) % M.
8647         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8648           IsAnyViable = true;
8649         else
8650           ViableForN[j] = false;
8651       }
8652     // Early exit if we exhaust the possible powers of two.
8653     if (!IsAnyViable)
8654       break;
8655   }
8656
8657   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8658     if (ViableForN[j])
8659       return j + 1;
8660
8661   // Return 0 as there is no viable power of two.
8662   return 0;
8663 }
8664
8665 /// \brief Generic lowering of v16i8 shuffles.
8666 ///
8667 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8668 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8669 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8670 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8671 /// back together.
8672 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8673                                        const X86Subtarget *Subtarget,
8674                                        SelectionDAG &DAG) {
8675   SDLoc DL(Op);
8676   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8677   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8678   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8679   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8680   ArrayRef<int> Mask = SVOp->getMask();
8681   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8682
8683   // Try to use shift instructions.
8684   if (SDValue Shift =
8685           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8686     return Shift;
8687
8688   // Try to use byte rotation instructions.
8689   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8690           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8691     return Rotate;
8692
8693   // Try to use a zext lowering.
8694   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8695           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8696     return ZExt;
8697
8698   int NumV2Elements =
8699       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8700
8701   // For single-input shuffles, there are some nicer lowering tricks we can use.
8702   if (NumV2Elements == 0) {
8703     // Check for being able to broadcast a single element.
8704     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8705                                                           Mask, Subtarget, DAG))
8706       return Broadcast;
8707
8708     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8709     // Notably, this handles splat and partial-splat shuffles more efficiently.
8710     // However, it only makes sense if the pre-duplication shuffle simplifies
8711     // things significantly. Currently, this means we need to be able to
8712     // express the pre-duplication shuffle as an i16 shuffle.
8713     //
8714     // FIXME: We should check for other patterns which can be widened into an
8715     // i16 shuffle as well.
8716     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8717       for (int i = 0; i < 16; i += 2)
8718         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8719           return false;
8720
8721       return true;
8722     };
8723     auto tryToWidenViaDuplication = [&]() -> SDValue {
8724       if (!canWidenViaDuplication(Mask))
8725         return SDValue();
8726       SmallVector<int, 4> LoInputs;
8727       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8728                    [](int M) { return M >= 0 && M < 8; });
8729       std::sort(LoInputs.begin(), LoInputs.end());
8730       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8731                      LoInputs.end());
8732       SmallVector<int, 4> HiInputs;
8733       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8734                    [](int M) { return M >= 8; });
8735       std::sort(HiInputs.begin(), HiInputs.end());
8736       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8737                      HiInputs.end());
8738
8739       bool TargetLo = LoInputs.size() >= HiInputs.size();
8740       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8741       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8742
8743       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8744       SmallDenseMap<int, int, 8> LaneMap;
8745       for (int I : InPlaceInputs) {
8746         PreDupI16Shuffle[I/2] = I/2;
8747         LaneMap[I] = I;
8748       }
8749       int j = TargetLo ? 0 : 4, je = j + 4;
8750       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8751         // Check if j is already a shuffle of this input. This happens when
8752         // there are two adjacent bytes after we move the low one.
8753         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8754           // If we haven't yet mapped the input, search for a slot into which
8755           // we can map it.
8756           while (j < je && PreDupI16Shuffle[j] != -1)
8757             ++j;
8758
8759           if (j == je)
8760             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8761             return SDValue();
8762
8763           // Map this input with the i16 shuffle.
8764           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8765         }
8766
8767         // Update the lane map based on the mapping we ended up with.
8768         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8769       }
8770       V1 = DAG.getNode(
8771           ISD::BITCAST, DL, MVT::v16i8,
8772           DAG.getVectorShuffle(MVT::v8i16, DL,
8773                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8774                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8775
8776       // Unpack the bytes to form the i16s that will be shuffled into place.
8777       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8778                        MVT::v16i8, V1, V1);
8779
8780       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8781       for (int i = 0; i < 16; ++i)
8782         if (Mask[i] != -1) {
8783           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8784           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8785           if (PostDupI16Shuffle[i / 2] == -1)
8786             PostDupI16Shuffle[i / 2] = MappedMask;
8787           else
8788             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8789                    "Conflicting entrties in the original shuffle!");
8790         }
8791       return DAG.getNode(
8792           ISD::BITCAST, DL, MVT::v16i8,
8793           DAG.getVectorShuffle(MVT::v8i16, DL,
8794                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8795                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8796     };
8797     if (SDValue V = tryToWidenViaDuplication())
8798       return V;
8799   }
8800
8801   // Use dedicated unpack instructions for masks that match their pattern.
8802   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8803                                          0, 16, 1, 17, 2, 18, 3, 19,
8804                                          // High half.
8805                                          4, 20, 5, 21, 6, 22, 7, 23}))
8806     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8807   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8808                                          8, 24, 9, 25, 10, 26, 11, 27,
8809                                          // High half.
8810                                          12, 28, 13, 29, 14, 30, 15, 31}))
8811     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8812
8813   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8814   // with PSHUFB. It is important to do this before we attempt to generate any
8815   // blends but after all of the single-input lowerings. If the single input
8816   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8817   // want to preserve that and we can DAG combine any longer sequences into
8818   // a PSHUFB in the end. But once we start blending from multiple inputs,
8819   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8820   // and there are *very* few patterns that would actually be faster than the
8821   // PSHUFB approach because of its ability to zero lanes.
8822   //
8823   // FIXME: The only exceptions to the above are blends which are exact
8824   // interleavings with direct instructions supporting them. We currently don't
8825   // handle those well here.
8826   if (Subtarget->hasSSSE3()) {
8827     bool V1InUse = false;
8828     bool V2InUse = false;
8829
8830     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8831                                                 DAG, V1InUse, V2InUse);
8832
8833     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8834     // do so. This avoids using them to handle blends-with-zero which is
8835     // important as a single pshufb is significantly faster for that.
8836     if (V1InUse && V2InUse) {
8837       if (Subtarget->hasSSE41())
8838         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8839                                                       Mask, Subtarget, DAG))
8840           return Blend;
8841
8842       // We can use an unpack to do the blending rather than an or in some
8843       // cases. Even though the or may be (very minorly) more efficient, we
8844       // preference this lowering because there are common cases where part of
8845       // the complexity of the shuffles goes away when we do the final blend as
8846       // an unpack.
8847       // FIXME: It might be worth trying to detect if the unpack-feeding
8848       // shuffles will both be pshufb, in which case we shouldn't bother with
8849       // this.
8850       if (SDValue Unpack =
8851               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8852         return Unpack;
8853     }
8854
8855     return PSHUFB;
8856   }
8857
8858   // There are special ways we can lower some single-element blends.
8859   if (NumV2Elements == 1)
8860     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8861                                                          Mask, Subtarget, DAG))
8862       return V;
8863
8864   if (SDValue BitBlend =
8865           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8866     return BitBlend;
8867
8868   // Check whether a compaction lowering can be done. This handles shuffles
8869   // which take every Nth element for some even N. See the helper function for
8870   // details.
8871   //
8872   // We special case these as they can be particularly efficiently handled with
8873   // the PACKUSB instruction on x86 and they show up in common patterns of
8874   // rearranging bytes to truncate wide elements.
8875   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8876     // NumEvenDrops is the power of two stride of the elements. Another way of
8877     // thinking about it is that we need to drop the even elements this many
8878     // times to get the original input.
8879     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8880
8881     // First we need to zero all the dropped bytes.
8882     assert(NumEvenDrops <= 3 &&
8883            "No support for dropping even elements more than 3 times.");
8884     // We use the mask type to pick which bytes are preserved based on how many
8885     // elements are dropped.
8886     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8887     SDValue ByteClearMask =
8888         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8889                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8890     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8891     if (!IsSingleInput)
8892       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8893
8894     // Now pack things back together.
8895     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8896     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8897     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8898     for (int i = 1; i < NumEvenDrops; ++i) {
8899       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8900       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8901     }
8902
8903     return Result;
8904   }
8905
8906   // Handle multi-input cases by blending single-input shuffles.
8907   if (NumV2Elements > 0)
8908     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8909                                                       Mask, DAG);
8910
8911   // The fallback path for single-input shuffles widens this into two v8i16
8912   // vectors with unpacks, shuffles those, and then pulls them back together
8913   // with a pack.
8914   SDValue V = V1;
8915
8916   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8917   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8918   for (int i = 0; i < 16; ++i)
8919     if (Mask[i] >= 0)
8920       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8921
8922   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8923
8924   SDValue VLoHalf, VHiHalf;
8925   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8926   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8927   // i16s.
8928   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8929                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8930       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8931                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8932     // Use a mask to drop the high bytes.
8933     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8934     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8935                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8936
8937     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8938     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8939
8940     // Squash the masks to point directly into VLoHalf.
8941     for (int &M : LoBlendMask)
8942       if (M >= 0)
8943         M /= 2;
8944     for (int &M : HiBlendMask)
8945       if (M >= 0)
8946         M /= 2;
8947   } else {
8948     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8949     // VHiHalf so that we can blend them as i16s.
8950     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8951                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8952     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8953                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8954   }
8955
8956   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8957   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8958
8959   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8960 }
8961
8962 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8963 ///
8964 /// This routine breaks down the specific type of 128-bit shuffle and
8965 /// dispatches to the lowering routines accordingly.
8966 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8967                                         MVT VT, const X86Subtarget *Subtarget,
8968                                         SelectionDAG &DAG) {
8969   switch (VT.SimpleTy) {
8970   case MVT::v2i64:
8971     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8972   case MVT::v2f64:
8973     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8974   case MVT::v4i32:
8975     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8976   case MVT::v4f32:
8977     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8978   case MVT::v8i16:
8979     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8980   case MVT::v16i8:
8981     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8982
8983   default:
8984     llvm_unreachable("Unimplemented!");
8985   }
8986 }
8987
8988 /// \brief Helper function to test whether a shuffle mask could be
8989 /// simplified by widening the elements being shuffled.
8990 ///
8991 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8992 /// leaves it in an unspecified state.
8993 ///
8994 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8995 /// shuffle masks. The latter have the special property of a '-2' representing
8996 /// a zero-ed lane of a vector.
8997 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8998                                     SmallVectorImpl<int> &WidenedMask) {
8999   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9000     // If both elements are undef, its trivial.
9001     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9002       WidenedMask.push_back(SM_SentinelUndef);
9003       continue;
9004     }
9005
9006     // Check for an undef mask and a mask value properly aligned to fit with
9007     // a pair of values. If we find such a case, use the non-undef mask's value.
9008     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9009       WidenedMask.push_back(Mask[i + 1] / 2);
9010       continue;
9011     }
9012     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9013       WidenedMask.push_back(Mask[i] / 2);
9014       continue;
9015     }
9016
9017     // When zeroing, we need to spread the zeroing across both lanes to widen.
9018     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9019       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9020           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9021         WidenedMask.push_back(SM_SentinelZero);
9022         continue;
9023       }
9024       return false;
9025     }
9026
9027     // Finally check if the two mask values are adjacent and aligned with
9028     // a pair.
9029     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9030       WidenedMask.push_back(Mask[i] / 2);
9031       continue;
9032     }
9033
9034     // Otherwise we can't safely widen the elements used in this shuffle.
9035     return false;
9036   }
9037   assert(WidenedMask.size() == Mask.size() / 2 &&
9038          "Incorrect size of mask after widening the elements!");
9039
9040   return true;
9041 }
9042
9043 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9044 ///
9045 /// This routine just extracts two subvectors, shuffles them independently, and
9046 /// then concatenates them back together. This should work effectively with all
9047 /// AVX vector shuffle types.
9048 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9049                                           SDValue V2, ArrayRef<int> Mask,
9050                                           SelectionDAG &DAG) {
9051   assert(VT.getSizeInBits() >= 256 &&
9052          "Only for 256-bit or wider vector shuffles!");
9053   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9054   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9055
9056   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9057   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9058
9059   int NumElements = VT.getVectorNumElements();
9060   int SplitNumElements = NumElements / 2;
9061   MVT ScalarVT = VT.getScalarType();
9062   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9063
9064   // Rather than splitting build-vectors, just build two narrower build
9065   // vectors. This helps shuffling with splats and zeros.
9066   auto SplitVector = [&](SDValue V) {
9067     while (V.getOpcode() == ISD::BITCAST)
9068       V = V->getOperand(0);
9069
9070     MVT OrigVT = V.getSimpleValueType();
9071     int OrigNumElements = OrigVT.getVectorNumElements();
9072     int OrigSplitNumElements = OrigNumElements / 2;
9073     MVT OrigScalarVT = OrigVT.getScalarType();
9074     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9075
9076     SDValue LoV, HiV;
9077
9078     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9079     if (!BV) {
9080       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9081                         DAG.getIntPtrConstant(0, DL));
9082       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9083                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9084     } else {
9085
9086       SmallVector<SDValue, 16> LoOps, HiOps;
9087       for (int i = 0; i < OrigSplitNumElements; ++i) {
9088         LoOps.push_back(BV->getOperand(i));
9089         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9090       }
9091       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9092       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9093     }
9094     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9095                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9096   };
9097
9098   SDValue LoV1, HiV1, LoV2, HiV2;
9099   std::tie(LoV1, HiV1) = SplitVector(V1);
9100   std::tie(LoV2, HiV2) = SplitVector(V2);
9101
9102   // Now create two 4-way blends of these half-width vectors.
9103   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9104     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9105     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9106     for (int i = 0; i < SplitNumElements; ++i) {
9107       int M = HalfMask[i];
9108       if (M >= NumElements) {
9109         if (M >= NumElements + SplitNumElements)
9110           UseHiV2 = true;
9111         else
9112           UseLoV2 = true;
9113         V2BlendMask.push_back(M - NumElements);
9114         V1BlendMask.push_back(-1);
9115         BlendMask.push_back(SplitNumElements + i);
9116       } else if (M >= 0) {
9117         if (M >= SplitNumElements)
9118           UseHiV1 = true;
9119         else
9120           UseLoV1 = true;
9121         V2BlendMask.push_back(-1);
9122         V1BlendMask.push_back(M);
9123         BlendMask.push_back(i);
9124       } else {
9125         V2BlendMask.push_back(-1);
9126         V1BlendMask.push_back(-1);
9127         BlendMask.push_back(-1);
9128       }
9129     }
9130
9131     // Because the lowering happens after all combining takes place, we need to
9132     // manually combine these blend masks as much as possible so that we create
9133     // a minimal number of high-level vector shuffle nodes.
9134
9135     // First try just blending the halves of V1 or V2.
9136     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9137       return DAG.getUNDEF(SplitVT);
9138     if (!UseLoV2 && !UseHiV2)
9139       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9140     if (!UseLoV1 && !UseHiV1)
9141       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9142
9143     SDValue V1Blend, V2Blend;
9144     if (UseLoV1 && UseHiV1) {
9145       V1Blend =
9146         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9147     } else {
9148       // We only use half of V1 so map the usage down into the final blend mask.
9149       V1Blend = UseLoV1 ? LoV1 : HiV1;
9150       for (int i = 0; i < SplitNumElements; ++i)
9151         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9152           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9153     }
9154     if (UseLoV2 && UseHiV2) {
9155       V2Blend =
9156         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9157     } else {
9158       // We only use half of V2 so map the usage down into the final blend mask.
9159       V2Blend = UseLoV2 ? LoV2 : HiV2;
9160       for (int i = 0; i < SplitNumElements; ++i)
9161         if (BlendMask[i] >= SplitNumElements)
9162           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9163     }
9164     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9165   };
9166   SDValue Lo = HalfBlend(LoMask);
9167   SDValue Hi = HalfBlend(HiMask);
9168   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9169 }
9170
9171 /// \brief Either split a vector in halves or decompose the shuffles and the
9172 /// blend.
9173 ///
9174 /// This is provided as a good fallback for many lowerings of non-single-input
9175 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9176 /// between splitting the shuffle into 128-bit components and stitching those
9177 /// back together vs. extracting the single-input shuffles and blending those
9178 /// results.
9179 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9180                                                 SDValue V2, ArrayRef<int> Mask,
9181                                                 SelectionDAG &DAG) {
9182   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9183                                             "lower single-input shuffles as it "
9184                                             "could then recurse on itself.");
9185   int Size = Mask.size();
9186
9187   // If this can be modeled as a broadcast of two elements followed by a blend,
9188   // prefer that lowering. This is especially important because broadcasts can
9189   // often fold with memory operands.
9190   auto DoBothBroadcast = [&] {
9191     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9192     for (int M : Mask)
9193       if (M >= Size) {
9194         if (V2BroadcastIdx == -1)
9195           V2BroadcastIdx = M - Size;
9196         else if (M - Size != V2BroadcastIdx)
9197           return false;
9198       } else if (M >= 0) {
9199         if (V1BroadcastIdx == -1)
9200           V1BroadcastIdx = M;
9201         else if (M != V1BroadcastIdx)
9202           return false;
9203       }
9204     return true;
9205   };
9206   if (DoBothBroadcast())
9207     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9208                                                       DAG);
9209
9210   // If the inputs all stem from a single 128-bit lane of each input, then we
9211   // split them rather than blending because the split will decompose to
9212   // unusually few instructions.
9213   int LaneCount = VT.getSizeInBits() / 128;
9214   int LaneSize = Size / LaneCount;
9215   SmallBitVector LaneInputs[2];
9216   LaneInputs[0].resize(LaneCount, false);
9217   LaneInputs[1].resize(LaneCount, false);
9218   for (int i = 0; i < Size; ++i)
9219     if (Mask[i] >= 0)
9220       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9221   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9222     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9223
9224   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9225   // that the decomposed single-input shuffles don't end up here.
9226   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9227 }
9228
9229 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9230 /// a permutation and blend of those lanes.
9231 ///
9232 /// This essentially blends the out-of-lane inputs to each lane into the lane
9233 /// from a permuted copy of the vector. This lowering strategy results in four
9234 /// instructions in the worst case for a single-input cross lane shuffle which
9235 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9236 /// of. Special cases for each particular shuffle pattern should be handled
9237 /// prior to trying this lowering.
9238 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9239                                                        SDValue V1, SDValue V2,
9240                                                        ArrayRef<int> Mask,
9241                                                        SelectionDAG &DAG) {
9242   // FIXME: This should probably be generalized for 512-bit vectors as well.
9243   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9244   int LaneSize = Mask.size() / 2;
9245
9246   // If there are only inputs from one 128-bit lane, splitting will in fact be
9247   // less expensive. The flags track whether the given lane contains an element
9248   // that crosses to another lane.
9249   bool LaneCrossing[2] = {false, false};
9250   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9251     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9252       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9253   if (!LaneCrossing[0] || !LaneCrossing[1])
9254     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9255
9256   if (isSingleInputShuffleMask(Mask)) {
9257     SmallVector<int, 32> FlippedBlendMask;
9258     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9259       FlippedBlendMask.push_back(
9260           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9261                                   ? Mask[i]
9262                                   : Mask[i] % LaneSize +
9263                                         (i / LaneSize) * LaneSize + Size));
9264
9265     // Flip the vector, and blend the results which should now be in-lane. The
9266     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9267     // 5 for the high source. The value 3 selects the high half of source 2 and
9268     // the value 2 selects the low half of source 2. We only use source 2 to
9269     // allow folding it into a memory operand.
9270     unsigned PERMMask = 3 | 2 << 4;
9271     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9272                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9273     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9274   }
9275
9276   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9277   // will be handled by the above logic and a blend of the results, much like
9278   // other patterns in AVX.
9279   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9280 }
9281
9282 /// \brief Handle lowering 2-lane 128-bit shuffles.
9283 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9284                                         SDValue V2, ArrayRef<int> Mask,
9285                                         const X86Subtarget *Subtarget,
9286                                         SelectionDAG &DAG) {
9287   // TODO: If minimizing size and one of the inputs is a zero vector and the
9288   // the zero vector has only one use, we could use a VPERM2X128 to save the
9289   // instruction bytes needed to explicitly generate the zero vector.
9290
9291   // Blends are faster and handle all the non-lane-crossing cases.
9292   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9293                                                 Subtarget, DAG))
9294     return Blend;
9295
9296   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9297   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9298
9299   // If either input operand is a zero vector, use VPERM2X128 because its mask
9300   // allows us to replace the zero input with an implicit zero.
9301   if (!IsV1Zero && !IsV2Zero) {
9302     // Check for patterns which can be matched with a single insert of a 128-bit
9303     // subvector.
9304     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9305     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9306       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9307                                    VT.getVectorNumElements() / 2);
9308       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9309                                 DAG.getIntPtrConstant(0, DL));
9310       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9311                                 OnlyUsesV1 ? V1 : V2,
9312                                 DAG.getIntPtrConstant(0, DL));
9313       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9314     }
9315   }
9316
9317   // Otherwise form a 128-bit permutation. After accounting for undefs,
9318   // convert the 64-bit shuffle mask selection values into 128-bit
9319   // selection bits by dividing the indexes by 2 and shifting into positions
9320   // defined by a vperm2*128 instruction's immediate control byte.
9321
9322   // The immediate permute control byte looks like this:
9323   //    [1:0] - select 128 bits from sources for low half of destination
9324   //    [2]   - ignore
9325   //    [3]   - zero low half of destination
9326   //    [5:4] - select 128 bits from sources for high half of destination
9327   //    [6]   - ignore
9328   //    [7]   - zero high half of destination
9329
9330   int MaskLO = Mask[0];
9331   if (MaskLO == SM_SentinelUndef)
9332     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9333
9334   int MaskHI = Mask[2];
9335   if (MaskHI == SM_SentinelUndef)
9336     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9337
9338   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9339
9340   // If either input is a zero vector, replace it with an undef input.
9341   // Shuffle mask values <  4 are selecting elements of V1.
9342   // Shuffle mask values >= 4 are selecting elements of V2.
9343   // Adjust each half of the permute mask by clearing the half that was
9344   // selecting the zero vector and setting the zero mask bit.
9345   if (IsV1Zero) {
9346     V1 = DAG.getUNDEF(VT);
9347     if (MaskLO < 4)
9348       PermMask = (PermMask & 0xf0) | 0x08;
9349     if (MaskHI < 4)
9350       PermMask = (PermMask & 0x0f) | 0x80;
9351   }
9352   if (IsV2Zero) {
9353     V2 = DAG.getUNDEF(VT);
9354     if (MaskLO >= 4)
9355       PermMask = (PermMask & 0xf0) | 0x08;
9356     if (MaskHI >= 4)
9357       PermMask = (PermMask & 0x0f) | 0x80;
9358   }
9359
9360   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9361                      DAG.getConstant(PermMask, DL, MVT::i8));
9362 }
9363
9364 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9365 /// shuffling each lane.
9366 ///
9367 /// This will only succeed when the result of fixing the 128-bit lanes results
9368 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9369 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9370 /// the lane crosses early and then use simpler shuffles within each lane.
9371 ///
9372 /// FIXME: It might be worthwhile at some point to support this without
9373 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9374 /// in x86 only floating point has interesting non-repeating shuffles, and even
9375 /// those are still *marginally* more expensive.
9376 static SDValue lowerVectorShuffleByMerging128BitLanes(
9377     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9378     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9379   assert(!isSingleInputShuffleMask(Mask) &&
9380          "This is only useful with multiple inputs.");
9381
9382   int Size = Mask.size();
9383   int LaneSize = 128 / VT.getScalarSizeInBits();
9384   int NumLanes = Size / LaneSize;
9385   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9386
9387   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9388   // check whether the in-128-bit lane shuffles share a repeating pattern.
9389   SmallVector<int, 4> Lanes;
9390   Lanes.resize(NumLanes, -1);
9391   SmallVector<int, 4> InLaneMask;
9392   InLaneMask.resize(LaneSize, -1);
9393   for (int i = 0; i < Size; ++i) {
9394     if (Mask[i] < 0)
9395       continue;
9396
9397     int j = i / LaneSize;
9398
9399     if (Lanes[j] < 0) {
9400       // First entry we've seen for this lane.
9401       Lanes[j] = Mask[i] / LaneSize;
9402     } else if (Lanes[j] != Mask[i] / LaneSize) {
9403       // This doesn't match the lane selected previously!
9404       return SDValue();
9405     }
9406
9407     // Check that within each lane we have a consistent shuffle mask.
9408     int k = i % LaneSize;
9409     if (InLaneMask[k] < 0) {
9410       InLaneMask[k] = Mask[i] % LaneSize;
9411     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9412       // This doesn't fit a repeating in-lane mask.
9413       return SDValue();
9414     }
9415   }
9416
9417   // First shuffle the lanes into place.
9418   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9419                                 VT.getSizeInBits() / 64);
9420   SmallVector<int, 8> LaneMask;
9421   LaneMask.resize(NumLanes * 2, -1);
9422   for (int i = 0; i < NumLanes; ++i)
9423     if (Lanes[i] >= 0) {
9424       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9425       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9426     }
9427
9428   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9429   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9430   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9431
9432   // Cast it back to the type we actually want.
9433   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9434
9435   // Now do a simple shuffle that isn't lane crossing.
9436   SmallVector<int, 8> NewMask;
9437   NewMask.resize(Size, -1);
9438   for (int i = 0; i < Size; ++i)
9439     if (Mask[i] >= 0)
9440       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9441   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9442          "Must not introduce lane crosses at this point!");
9443
9444   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9445 }
9446
9447 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9448 /// given mask.
9449 ///
9450 /// This returns true if the elements from a particular input are already in the
9451 /// slot required by the given mask and require no permutation.
9452 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9453   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9454   int Size = Mask.size();
9455   for (int i = 0; i < Size; ++i)
9456     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9457       return false;
9458
9459   return true;
9460 }
9461
9462 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9463 ///
9464 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9465 /// isn't available.
9466 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9467                                        const X86Subtarget *Subtarget,
9468                                        SelectionDAG &DAG) {
9469   SDLoc DL(Op);
9470   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9471   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9472   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9473   ArrayRef<int> Mask = SVOp->getMask();
9474   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9475
9476   SmallVector<int, 4> WidenedMask;
9477   if (canWidenShuffleElements(Mask, WidenedMask))
9478     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9479                                     DAG);
9480
9481   if (isSingleInputShuffleMask(Mask)) {
9482     // Check for being able to broadcast a single element.
9483     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9484                                                           Mask, Subtarget, DAG))
9485       return Broadcast;
9486
9487     // Use low duplicate instructions for masks that match their pattern.
9488     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9489       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9490
9491     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9492       // Non-half-crossing single input shuffles can be lowerid with an
9493       // interleaved permutation.
9494       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9495                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9496       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9497                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9498     }
9499
9500     // With AVX2 we have direct support for this permutation.
9501     if (Subtarget->hasAVX2())
9502       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9503                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9504
9505     // Otherwise, fall back.
9506     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9507                                                    DAG);
9508   }
9509
9510   // X86 has dedicated unpack instructions that can handle specific blend
9511   // operations: UNPCKH and UNPCKL.
9512   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9513     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9514   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9515     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9516   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9517     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9518   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9519     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9520
9521   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9522                                                 Subtarget, DAG))
9523     return Blend;
9524
9525   // Check if the blend happens to exactly fit that of SHUFPD.
9526   if ((Mask[0] == -1 || Mask[0] < 2) &&
9527       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9528       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9529       (Mask[3] == -1 || Mask[3] >= 6)) {
9530     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9531                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9532     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9533                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9534   }
9535   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9536       (Mask[1] == -1 || Mask[1] < 2) &&
9537       (Mask[2] == -1 || Mask[2] >= 6) &&
9538       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9539     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9540                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9541     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9542                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9543   }
9544
9545   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9546   // shuffle. However, if we have AVX2 and either inputs are already in place,
9547   // we will be able to shuffle even across lanes the other input in a single
9548   // instruction so skip this pattern.
9549   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9550                                  isShuffleMaskInputInPlace(1, Mask))))
9551     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9552             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9553       return Result;
9554
9555   // If we have AVX2 then we always want to lower with a blend because an v4 we
9556   // can fully permute the elements.
9557   if (Subtarget->hasAVX2())
9558     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9559                                                       Mask, DAG);
9560
9561   // Otherwise fall back on generic lowering.
9562   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9563 }
9564
9565 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9566 ///
9567 /// This routine is only called when we have AVX2 and thus a reasonable
9568 /// instruction set for v4i64 shuffling..
9569 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9570                                        const X86Subtarget *Subtarget,
9571                                        SelectionDAG &DAG) {
9572   SDLoc DL(Op);
9573   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9574   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9575   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9576   ArrayRef<int> Mask = SVOp->getMask();
9577   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9578   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9579
9580   SmallVector<int, 4> WidenedMask;
9581   if (canWidenShuffleElements(Mask, WidenedMask))
9582     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9583                                     DAG);
9584
9585   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9586                                                 Subtarget, DAG))
9587     return Blend;
9588
9589   // Check for being able to broadcast a single element.
9590   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9591                                                         Mask, Subtarget, DAG))
9592     return Broadcast;
9593
9594   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9595   // use lower latency instructions that will operate on both 128-bit lanes.
9596   SmallVector<int, 2> RepeatedMask;
9597   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9598     if (isSingleInputShuffleMask(Mask)) {
9599       int PSHUFDMask[] = {-1, -1, -1, -1};
9600       for (int i = 0; i < 2; ++i)
9601         if (RepeatedMask[i] >= 0) {
9602           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9603           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9604         }
9605       return DAG.getNode(
9606           ISD::BITCAST, DL, MVT::v4i64,
9607           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9608                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9609                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9610     }
9611   }
9612
9613   // AVX2 provides a direct instruction for permuting a single input across
9614   // lanes.
9615   if (isSingleInputShuffleMask(Mask))
9616     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9617                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9618
9619   // Try to use shift instructions.
9620   if (SDValue Shift =
9621           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9622     return Shift;
9623
9624   // Use dedicated unpack instructions for masks that match their pattern.
9625   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9626     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9627   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9628     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9629   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9630     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9631   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9632     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9633
9634   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9635   // shuffle. However, if we have AVX2 and either inputs are already in place,
9636   // we will be able to shuffle even across lanes the other input in a single
9637   // instruction so skip this pattern.
9638   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9639                                  isShuffleMaskInputInPlace(1, Mask))))
9640     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9641             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9642       return Result;
9643
9644   // Otherwise fall back on generic blend lowering.
9645   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9646                                                     Mask, DAG);
9647 }
9648
9649 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9650 ///
9651 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9652 /// isn't available.
9653 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9654                                        const X86Subtarget *Subtarget,
9655                                        SelectionDAG &DAG) {
9656   SDLoc DL(Op);
9657   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9658   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9659   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9660   ArrayRef<int> Mask = SVOp->getMask();
9661   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9662
9663   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9664                                                 Subtarget, DAG))
9665     return Blend;
9666
9667   // Check for being able to broadcast a single element.
9668   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9669                                                         Mask, Subtarget, DAG))
9670     return Broadcast;
9671
9672   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9673   // options to efficiently lower the shuffle.
9674   SmallVector<int, 4> RepeatedMask;
9675   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9676     assert(RepeatedMask.size() == 4 &&
9677            "Repeated masks must be half the mask width!");
9678
9679     // Use even/odd duplicate instructions for masks that match their pattern.
9680     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9681       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9682     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9683       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9684
9685     if (isSingleInputShuffleMask(Mask))
9686       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9687                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9688
9689     // Use dedicated unpack instructions for masks that match their pattern.
9690     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9691       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9692     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9693       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9694     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9695       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9696     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9697       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9698
9699     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9700     // have already handled any direct blends. We also need to squash the
9701     // repeated mask into a simulated v4f32 mask.
9702     for (int i = 0; i < 4; ++i)
9703       if (RepeatedMask[i] >= 8)
9704         RepeatedMask[i] -= 4;
9705     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9706   }
9707
9708   // If we have a single input shuffle with different shuffle patterns in the
9709   // two 128-bit lanes use the variable mask to VPERMILPS.
9710   if (isSingleInputShuffleMask(Mask)) {
9711     SDValue VPermMask[8];
9712     for (int i = 0; i < 8; ++i)
9713       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9714                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9715     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9716       return DAG.getNode(
9717           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9718           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9719
9720     if (Subtarget->hasAVX2())
9721       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9722                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9723                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9724                                                  MVT::v8i32, VPermMask)),
9725                          V1);
9726
9727     // Otherwise, fall back.
9728     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9729                                                    DAG);
9730   }
9731
9732   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9733   // shuffle.
9734   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9735           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9736     return Result;
9737
9738   // If we have AVX2 then we always want to lower with a blend because at v8 we
9739   // can fully permute the elements.
9740   if (Subtarget->hasAVX2())
9741     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9742                                                       Mask, DAG);
9743
9744   // Otherwise fall back on generic lowering.
9745   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9746 }
9747
9748 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9749 ///
9750 /// This routine is only called when we have AVX2 and thus a reasonable
9751 /// instruction set for v8i32 shuffling..
9752 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9753                                        const X86Subtarget *Subtarget,
9754                                        SelectionDAG &DAG) {
9755   SDLoc DL(Op);
9756   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9757   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9758   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9759   ArrayRef<int> Mask = SVOp->getMask();
9760   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9761   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9762
9763   // Whenever we can lower this as a zext, that instruction is strictly faster
9764   // than any alternative. It also allows us to fold memory operands into the
9765   // shuffle in many cases.
9766   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9767                                                          Mask, Subtarget, DAG))
9768     return ZExt;
9769
9770   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9771                                                 Subtarget, DAG))
9772     return Blend;
9773
9774   // Check for being able to broadcast a single element.
9775   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9776                                                         Mask, Subtarget, DAG))
9777     return Broadcast;
9778
9779   // If the shuffle mask is repeated in each 128-bit lane we can use more
9780   // efficient instructions that mirror the shuffles across the two 128-bit
9781   // lanes.
9782   SmallVector<int, 4> RepeatedMask;
9783   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9784     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9785     if (isSingleInputShuffleMask(Mask))
9786       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9787                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9788
9789     // Use dedicated unpack instructions for masks that match their pattern.
9790     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9791       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9792     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9793       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9794     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9795       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9796     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9797       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9798   }
9799
9800   // Try to use shift instructions.
9801   if (SDValue Shift =
9802           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9803     return Shift;
9804
9805   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9806           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9807     return Rotate;
9808
9809   // If the shuffle patterns aren't repeated but it is a single input, directly
9810   // generate a cross-lane VPERMD instruction.
9811   if (isSingleInputShuffleMask(Mask)) {
9812     SDValue VPermMask[8];
9813     for (int i = 0; i < 8; ++i)
9814       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9815                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9816     return DAG.getNode(
9817         X86ISD::VPERMV, DL, MVT::v8i32,
9818         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9819   }
9820
9821   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9822   // shuffle.
9823   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9824           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9825     return Result;
9826
9827   // Otherwise fall back on generic blend lowering.
9828   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9829                                                     Mask, DAG);
9830 }
9831
9832 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9833 ///
9834 /// This routine is only called when we have AVX2 and thus a reasonable
9835 /// instruction set for v16i16 shuffling..
9836 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9837                                         const X86Subtarget *Subtarget,
9838                                         SelectionDAG &DAG) {
9839   SDLoc DL(Op);
9840   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9841   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9842   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9843   ArrayRef<int> Mask = SVOp->getMask();
9844   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9845   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9846
9847   // Whenever we can lower this as a zext, that instruction is strictly faster
9848   // than any alternative. It also allows us to fold memory operands into the
9849   // shuffle in many cases.
9850   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9851                                                          Mask, Subtarget, DAG))
9852     return ZExt;
9853
9854   // Check for being able to broadcast a single element.
9855   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9856                                                         Mask, Subtarget, DAG))
9857     return Broadcast;
9858
9859   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9860                                                 Subtarget, DAG))
9861     return Blend;
9862
9863   // Use dedicated unpack instructions for masks that match their pattern.
9864   if (isShuffleEquivalent(V1, V2, Mask,
9865                           {// First 128-bit lane:
9866                            0, 16, 1, 17, 2, 18, 3, 19,
9867                            // Second 128-bit lane:
9868                            8, 24, 9, 25, 10, 26, 11, 27}))
9869     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9870   if (isShuffleEquivalent(V1, V2, Mask,
9871                           {// First 128-bit lane:
9872                            4, 20, 5, 21, 6, 22, 7, 23,
9873                            // Second 128-bit lane:
9874                            12, 28, 13, 29, 14, 30, 15, 31}))
9875     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9876
9877   // Try to use shift instructions.
9878   if (SDValue Shift =
9879           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9880     return Shift;
9881
9882   // Try to use byte rotation instructions.
9883   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9884           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9885     return Rotate;
9886
9887   if (isSingleInputShuffleMask(Mask)) {
9888     // There are no generalized cross-lane shuffle operations available on i16
9889     // element types.
9890     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9891       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9892                                                      Mask, DAG);
9893
9894     SmallVector<int, 8> RepeatedMask;
9895     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9896       // As this is a single-input shuffle, the repeated mask should be
9897       // a strictly valid v8i16 mask that we can pass through to the v8i16
9898       // lowering to handle even the v16 case.
9899       return lowerV8I16GeneralSingleInputVectorShuffle(
9900           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9901     }
9902
9903     SDValue PSHUFBMask[32];
9904     for (int i = 0; i < 16; ++i) {
9905       if (Mask[i] == -1) {
9906         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9907         continue;
9908       }
9909
9910       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9911       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9912       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9913       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9914     }
9915     return DAG.getNode(
9916         ISD::BITCAST, DL, MVT::v16i16,
9917         DAG.getNode(
9918             X86ISD::PSHUFB, DL, MVT::v32i8,
9919             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9920             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9921   }
9922
9923   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9924   // shuffle.
9925   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9926           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9927     return Result;
9928
9929   // Otherwise fall back on generic lowering.
9930   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9931 }
9932
9933 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9934 ///
9935 /// This routine is only called when we have AVX2 and thus a reasonable
9936 /// instruction set for v32i8 shuffling..
9937 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9938                                        const X86Subtarget *Subtarget,
9939                                        SelectionDAG &DAG) {
9940   SDLoc DL(Op);
9941   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9942   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9943   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9944   ArrayRef<int> Mask = SVOp->getMask();
9945   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9946   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9947
9948   // Whenever we can lower this as a zext, that instruction is strictly faster
9949   // than any alternative. It also allows us to fold memory operands into the
9950   // shuffle in many cases.
9951   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9952                                                          Mask, Subtarget, DAG))
9953     return ZExt;
9954
9955   // Check for being able to broadcast a single element.
9956   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9957                                                         Mask, Subtarget, DAG))
9958     return Broadcast;
9959
9960   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9961                                                 Subtarget, DAG))
9962     return Blend;
9963
9964   // Use dedicated unpack instructions for masks that match their pattern.
9965   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9966   // 256-bit lanes.
9967   if (isShuffleEquivalent(
9968           V1, V2, Mask,
9969           {// First 128-bit lane:
9970            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9971            // Second 128-bit lane:
9972            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9973     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9974   if (isShuffleEquivalent(
9975           V1, V2, Mask,
9976           {// First 128-bit lane:
9977            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9978            // Second 128-bit lane:
9979            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9980     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9981
9982   // Try to use shift instructions.
9983   if (SDValue Shift =
9984           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9985     return Shift;
9986
9987   // Try to use byte rotation instructions.
9988   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9989           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9990     return Rotate;
9991
9992   if (isSingleInputShuffleMask(Mask)) {
9993     // There are no generalized cross-lane shuffle operations available on i8
9994     // element types.
9995     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9996       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9997                                                      Mask, DAG);
9998
9999     SDValue PSHUFBMask[32];
10000     for (int i = 0; i < 32; ++i)
10001       PSHUFBMask[i] =
10002           Mask[i] < 0
10003               ? DAG.getUNDEF(MVT::i8)
10004               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10005                                 MVT::i8);
10006
10007     return DAG.getNode(
10008         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10009         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10010   }
10011
10012   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10013   // shuffle.
10014   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10015           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10016     return Result;
10017
10018   // Otherwise fall back on generic lowering.
10019   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10020 }
10021
10022 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10023 ///
10024 /// This routine either breaks down the specific type of a 256-bit x86 vector
10025 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10026 /// together based on the available instructions.
10027 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10028                                         MVT VT, const X86Subtarget *Subtarget,
10029                                         SelectionDAG &DAG) {
10030   SDLoc DL(Op);
10031   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10032   ArrayRef<int> Mask = SVOp->getMask();
10033
10034   // If we have a single input to the zero element, insert that into V1 if we
10035   // can do so cheaply.
10036   int NumElts = VT.getVectorNumElements();
10037   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10038     return M >= NumElts;
10039   });
10040
10041   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10042     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10043                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10044       return Insertion;
10045
10046   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10047   // check for those subtargets here and avoid much of the subtarget querying in
10048   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10049   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10050   // floating point types there eventually, just immediately cast everything to
10051   // a float and operate entirely in that domain.
10052   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10053     int ElementBits = VT.getScalarSizeInBits();
10054     if (ElementBits < 32)
10055       // No floating point type available, decompose into 128-bit vectors.
10056       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10057
10058     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10059                                 VT.getVectorNumElements());
10060     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10061     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10062     return DAG.getNode(ISD::BITCAST, DL, VT,
10063                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10064   }
10065
10066   switch (VT.SimpleTy) {
10067   case MVT::v4f64:
10068     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10069   case MVT::v4i64:
10070     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10071   case MVT::v8f32:
10072     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10073   case MVT::v8i32:
10074     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10075   case MVT::v16i16:
10076     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10077   case MVT::v32i8:
10078     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10079
10080   default:
10081     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10082   }
10083 }
10084
10085 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10086 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10087                                        const X86Subtarget *Subtarget,
10088                                        SelectionDAG &DAG) {
10089   SDLoc DL(Op);
10090   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10091   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10092   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10093   ArrayRef<int> Mask = SVOp->getMask();
10094   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10095
10096   // X86 has dedicated unpack instructions that can handle specific blend
10097   // operations: UNPCKH and UNPCKL.
10098   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10099     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10100   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10101     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10102
10103   // FIXME: Implement direct support for this type!
10104   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10105 }
10106
10107 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10108 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10109                                        const X86Subtarget *Subtarget,
10110                                        SelectionDAG &DAG) {
10111   SDLoc DL(Op);
10112   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10113   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10114   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10115   ArrayRef<int> Mask = SVOp->getMask();
10116   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10117
10118   // Use dedicated unpack instructions for masks that match their pattern.
10119   if (isShuffleEquivalent(V1, V2, Mask,
10120                           {// First 128-bit lane.
10121                            0, 16, 1, 17, 4, 20, 5, 21,
10122                            // Second 128-bit lane.
10123                            8, 24, 9, 25, 12, 28, 13, 29}))
10124     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10125   if (isShuffleEquivalent(V1, V2, Mask,
10126                           {// First 128-bit lane.
10127                            2, 18, 3, 19, 6, 22, 7, 23,
10128                            // Second 128-bit lane.
10129                            10, 26, 11, 27, 14, 30, 15, 31}))
10130     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10131
10132   // FIXME: Implement direct support for this type!
10133   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10134 }
10135
10136 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10137 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10138                                        const X86Subtarget *Subtarget,
10139                                        SelectionDAG &DAG) {
10140   SDLoc DL(Op);
10141   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10142   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10143   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10144   ArrayRef<int> Mask = SVOp->getMask();
10145   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10146
10147   // X86 has dedicated unpack instructions that can handle specific blend
10148   // operations: UNPCKH and UNPCKL.
10149   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10150     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10151   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10152     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10153
10154   // FIXME: Implement direct support for this type!
10155   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10156 }
10157
10158 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10159 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10160                                        const X86Subtarget *Subtarget,
10161                                        SelectionDAG &DAG) {
10162   SDLoc DL(Op);
10163   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10164   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10165   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10166   ArrayRef<int> Mask = SVOp->getMask();
10167   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10168
10169   // Use dedicated unpack instructions for masks that match their pattern.
10170   if (isShuffleEquivalent(V1, V2, Mask,
10171                           {// First 128-bit lane.
10172                            0, 16, 1, 17, 4, 20, 5, 21,
10173                            // Second 128-bit lane.
10174                            8, 24, 9, 25, 12, 28, 13, 29}))
10175     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10176   if (isShuffleEquivalent(V1, V2, Mask,
10177                           {// First 128-bit lane.
10178                            2, 18, 3, 19, 6, 22, 7, 23,
10179                            // Second 128-bit lane.
10180                            10, 26, 11, 27, 14, 30, 15, 31}))
10181     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10182
10183   // FIXME: Implement direct support for this type!
10184   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10185 }
10186
10187 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10188 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10189                                         const X86Subtarget *Subtarget,
10190                                         SelectionDAG &DAG) {
10191   SDLoc DL(Op);
10192   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10193   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10194   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10195   ArrayRef<int> Mask = SVOp->getMask();
10196   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10197   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10198
10199   // FIXME: Implement direct support for this type!
10200   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10201 }
10202
10203 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10204 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10205                                        const X86Subtarget *Subtarget,
10206                                        SelectionDAG &DAG) {
10207   SDLoc DL(Op);
10208   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10209   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10210   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10211   ArrayRef<int> Mask = SVOp->getMask();
10212   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10213   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10214
10215   // FIXME: Implement direct support for this type!
10216   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10217 }
10218
10219 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10220 ///
10221 /// This routine either breaks down the specific type of a 512-bit x86 vector
10222 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10223 /// together based on the available instructions.
10224 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10225                                         MVT VT, const X86Subtarget *Subtarget,
10226                                         SelectionDAG &DAG) {
10227   SDLoc DL(Op);
10228   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10229   ArrayRef<int> Mask = SVOp->getMask();
10230   assert(Subtarget->hasAVX512() &&
10231          "Cannot lower 512-bit vectors w/ basic ISA!");
10232
10233   // Check for being able to broadcast a single element.
10234   if (SDValue Broadcast =
10235           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10236     return Broadcast;
10237
10238   // Dispatch to each element type for lowering. If we don't have supprot for
10239   // specific element type shuffles at 512 bits, immediately split them and
10240   // lower them. Each lowering routine of a given type is allowed to assume that
10241   // the requisite ISA extensions for that element type are available.
10242   switch (VT.SimpleTy) {
10243   case MVT::v8f64:
10244     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10245   case MVT::v16f32:
10246     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10247   case MVT::v8i64:
10248     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10249   case MVT::v16i32:
10250     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10251   case MVT::v32i16:
10252     if (Subtarget->hasBWI())
10253       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10254     break;
10255   case MVT::v64i8:
10256     if (Subtarget->hasBWI())
10257       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10258     break;
10259
10260   default:
10261     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10262   }
10263
10264   // Otherwise fall back on splitting.
10265   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10266 }
10267
10268 /// \brief Top-level lowering for x86 vector shuffles.
10269 ///
10270 /// This handles decomposition, canonicalization, and lowering of all x86
10271 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10272 /// above in helper routines. The canonicalization attempts to widen shuffles
10273 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10274 /// s.t. only one of the two inputs needs to be tested, etc.
10275 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10276                                   SelectionDAG &DAG) {
10277   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10278   ArrayRef<int> Mask = SVOp->getMask();
10279   SDValue V1 = Op.getOperand(0);
10280   SDValue V2 = Op.getOperand(1);
10281   MVT VT = Op.getSimpleValueType();
10282   int NumElements = VT.getVectorNumElements();
10283   SDLoc dl(Op);
10284
10285   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10286
10287   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10288   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10289   if (V1IsUndef && V2IsUndef)
10290     return DAG.getUNDEF(VT);
10291
10292   // When we create a shuffle node we put the UNDEF node to second operand,
10293   // but in some cases the first operand may be transformed to UNDEF.
10294   // In this case we should just commute the node.
10295   if (V1IsUndef)
10296     return DAG.getCommutedVectorShuffle(*SVOp);
10297
10298   // Check for non-undef masks pointing at an undef vector and make the masks
10299   // undef as well. This makes it easier to match the shuffle based solely on
10300   // the mask.
10301   if (V2IsUndef)
10302     for (int M : Mask)
10303       if (M >= NumElements) {
10304         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10305         for (int &M : NewMask)
10306           if (M >= NumElements)
10307             M = -1;
10308         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10309       }
10310
10311   // We actually see shuffles that are entirely re-arrangements of a set of
10312   // zero inputs. This mostly happens while decomposing complex shuffles into
10313   // simple ones. Directly lower these as a buildvector of zeros.
10314   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10315   if (Zeroable.all())
10316     return getZeroVector(VT, Subtarget, DAG, dl);
10317
10318   // Try to collapse shuffles into using a vector type with fewer elements but
10319   // wider element types. We cap this to not form integers or floating point
10320   // elements wider than 64 bits, but it might be interesting to form i128
10321   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10322   SmallVector<int, 16> WidenedMask;
10323   if (VT.getScalarSizeInBits() < 64 &&
10324       canWidenShuffleElements(Mask, WidenedMask)) {
10325     MVT NewEltVT = VT.isFloatingPoint()
10326                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10327                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10328     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10329     // Make sure that the new vector type is legal. For example, v2f64 isn't
10330     // legal on SSE1.
10331     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10332       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10333       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10334       return DAG.getNode(ISD::BITCAST, dl, VT,
10335                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10336     }
10337   }
10338
10339   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10340   for (int M : SVOp->getMask())
10341     if (M < 0)
10342       ++NumUndefElements;
10343     else if (M < NumElements)
10344       ++NumV1Elements;
10345     else
10346       ++NumV2Elements;
10347
10348   // Commute the shuffle as needed such that more elements come from V1 than
10349   // V2. This allows us to match the shuffle pattern strictly on how many
10350   // elements come from V1 without handling the symmetric cases.
10351   if (NumV2Elements > NumV1Elements)
10352     return DAG.getCommutedVectorShuffle(*SVOp);
10353
10354   // When the number of V1 and V2 elements are the same, try to minimize the
10355   // number of uses of V2 in the low half of the vector. When that is tied,
10356   // ensure that the sum of indices for V1 is equal to or lower than the sum
10357   // indices for V2. When those are equal, try to ensure that the number of odd
10358   // indices for V1 is lower than the number of odd indices for V2.
10359   if (NumV1Elements == NumV2Elements) {
10360     int LowV1Elements = 0, LowV2Elements = 0;
10361     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10362       if (M >= NumElements)
10363         ++LowV2Elements;
10364       else if (M >= 0)
10365         ++LowV1Elements;
10366     if (LowV2Elements > LowV1Elements) {
10367       return DAG.getCommutedVectorShuffle(*SVOp);
10368     } else if (LowV2Elements == LowV1Elements) {
10369       int SumV1Indices = 0, SumV2Indices = 0;
10370       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10371         if (SVOp->getMask()[i] >= NumElements)
10372           SumV2Indices += i;
10373         else if (SVOp->getMask()[i] >= 0)
10374           SumV1Indices += i;
10375       if (SumV2Indices < SumV1Indices) {
10376         return DAG.getCommutedVectorShuffle(*SVOp);
10377       } else if (SumV2Indices == SumV1Indices) {
10378         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10379         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10380           if (SVOp->getMask()[i] >= NumElements)
10381             NumV2OddIndices += i % 2;
10382           else if (SVOp->getMask()[i] >= 0)
10383             NumV1OddIndices += i % 2;
10384         if (NumV2OddIndices < NumV1OddIndices)
10385           return DAG.getCommutedVectorShuffle(*SVOp);
10386       }
10387     }
10388   }
10389
10390   // For each vector width, delegate to a specialized lowering routine.
10391   if (VT.getSizeInBits() == 128)
10392     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10393
10394   if (VT.getSizeInBits() == 256)
10395     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10396
10397   // Force AVX-512 vectors to be scalarized for now.
10398   // FIXME: Implement AVX-512 support!
10399   if (VT.getSizeInBits() == 512)
10400     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10401
10402   llvm_unreachable("Unimplemented!");
10403 }
10404
10405 // This function assumes its argument is a BUILD_VECTOR of constants or
10406 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10407 // true.
10408 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10409                                     unsigned &MaskValue) {
10410   MaskValue = 0;
10411   unsigned NumElems = BuildVector->getNumOperands();
10412   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10413   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10414   unsigned NumElemsInLane = NumElems / NumLanes;
10415
10416   // Blend for v16i16 should be symetric for the both lanes.
10417   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10418     SDValue EltCond = BuildVector->getOperand(i);
10419     SDValue SndLaneEltCond =
10420         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10421
10422     int Lane1Cond = -1, Lane2Cond = -1;
10423     if (isa<ConstantSDNode>(EltCond))
10424       Lane1Cond = !isZero(EltCond);
10425     if (isa<ConstantSDNode>(SndLaneEltCond))
10426       Lane2Cond = !isZero(SndLaneEltCond);
10427
10428     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10429       // Lane1Cond != 0, means we want the first argument.
10430       // Lane1Cond == 0, means we want the second argument.
10431       // The encoding of this argument is 0 for the first argument, 1
10432       // for the second. Therefore, invert the condition.
10433       MaskValue |= !Lane1Cond << i;
10434     else if (Lane1Cond < 0)
10435       MaskValue |= !Lane2Cond << i;
10436     else
10437       return false;
10438   }
10439   return true;
10440 }
10441
10442 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10443 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10444                                            const X86Subtarget *Subtarget,
10445                                            SelectionDAG &DAG) {
10446   SDValue Cond = Op.getOperand(0);
10447   SDValue LHS = Op.getOperand(1);
10448   SDValue RHS = Op.getOperand(2);
10449   SDLoc dl(Op);
10450   MVT VT = Op.getSimpleValueType();
10451
10452   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10453     return SDValue();
10454   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10455
10456   // Only non-legal VSELECTs reach this lowering, convert those into generic
10457   // shuffles and re-use the shuffle lowering path for blends.
10458   SmallVector<int, 32> Mask;
10459   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10460     SDValue CondElt = CondBV->getOperand(i);
10461     Mask.push_back(
10462         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10463   }
10464   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10465 }
10466
10467 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10468   // A vselect where all conditions and data are constants can be optimized into
10469   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10470   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10471       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10472       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10473     return SDValue();
10474
10475   // Try to lower this to a blend-style vector shuffle. This can handle all
10476   // constant condition cases.
10477   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10478     return BlendOp;
10479
10480   // Variable blends are only legal from SSE4.1 onward.
10481   if (!Subtarget->hasSSE41())
10482     return SDValue();
10483
10484   // Only some types will be legal on some subtargets. If we can emit a legal
10485   // VSELECT-matching blend, return Op, and but if we need to expand, return
10486   // a null value.
10487   switch (Op.getSimpleValueType().SimpleTy) {
10488   default:
10489     // Most of the vector types have blends past SSE4.1.
10490     return Op;
10491
10492   case MVT::v32i8:
10493     // The byte blends for AVX vectors were introduced only in AVX2.
10494     if (Subtarget->hasAVX2())
10495       return Op;
10496
10497     return SDValue();
10498
10499   case MVT::v8i16:
10500   case MVT::v16i16:
10501     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10502     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10503       return Op;
10504
10505     // FIXME: We should custom lower this by fixing the condition and using i8
10506     // blends.
10507     return SDValue();
10508   }
10509 }
10510
10511 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10512   MVT VT = Op.getSimpleValueType();
10513   SDLoc dl(Op);
10514
10515   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10516     return SDValue();
10517
10518   if (VT.getSizeInBits() == 8) {
10519     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10520                                   Op.getOperand(0), Op.getOperand(1));
10521     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10522                                   DAG.getValueType(VT));
10523     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10524   }
10525
10526   if (VT.getSizeInBits() == 16) {
10527     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10528     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10529     if (Idx == 0)
10530       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10531                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10532                                      DAG.getNode(ISD::BITCAST, dl,
10533                                                  MVT::v4i32,
10534                                                  Op.getOperand(0)),
10535                                      Op.getOperand(1)));
10536     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10537                                   Op.getOperand(0), Op.getOperand(1));
10538     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10539                                   DAG.getValueType(VT));
10540     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10541   }
10542
10543   if (VT == MVT::f32) {
10544     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10545     // the result back to FR32 register. It's only worth matching if the
10546     // result has a single use which is a store or a bitcast to i32.  And in
10547     // the case of a store, it's not worth it if the index is a constant 0,
10548     // because a MOVSSmr can be used instead, which is smaller and faster.
10549     if (!Op.hasOneUse())
10550       return SDValue();
10551     SDNode *User = *Op.getNode()->use_begin();
10552     if ((User->getOpcode() != ISD::STORE ||
10553          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10554           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10555         (User->getOpcode() != ISD::BITCAST ||
10556          User->getValueType(0) != MVT::i32))
10557       return SDValue();
10558     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10559                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10560                                               Op.getOperand(0)),
10561                                               Op.getOperand(1));
10562     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10563   }
10564
10565   if (VT == MVT::i32 || VT == MVT::i64) {
10566     // ExtractPS/pextrq works with constant index.
10567     if (isa<ConstantSDNode>(Op.getOperand(1)))
10568       return Op;
10569   }
10570   return SDValue();
10571 }
10572
10573 /// Extract one bit from mask vector, like v16i1 or v8i1.
10574 /// AVX-512 feature.
10575 SDValue
10576 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10577   SDValue Vec = Op.getOperand(0);
10578   SDLoc dl(Vec);
10579   MVT VecVT = Vec.getSimpleValueType();
10580   SDValue Idx = Op.getOperand(1);
10581   MVT EltVT = Op.getSimpleValueType();
10582
10583   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10584   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10585          "Unexpected vector type in ExtractBitFromMaskVector");
10586
10587   // variable index can't be handled in mask registers,
10588   // extend vector to VR512
10589   if (!isa<ConstantSDNode>(Idx)) {
10590     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10591     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10592     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10593                               ExtVT.getVectorElementType(), Ext, Idx);
10594     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10595   }
10596
10597   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10598   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10599   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10600     rc = getRegClassFor(MVT::v16i1);
10601   unsigned MaxSift = rc->getSize()*8 - 1;
10602   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10603                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10604   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10605                     DAG.getConstant(MaxSift, dl, MVT::i8));
10606   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10607                        DAG.getIntPtrConstant(0, dl));
10608 }
10609
10610 SDValue
10611 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10612                                            SelectionDAG &DAG) const {
10613   SDLoc dl(Op);
10614   SDValue Vec = Op.getOperand(0);
10615   MVT VecVT = Vec.getSimpleValueType();
10616   SDValue Idx = Op.getOperand(1);
10617
10618   if (Op.getSimpleValueType() == MVT::i1)
10619     return ExtractBitFromMaskVector(Op, DAG);
10620
10621   if (!isa<ConstantSDNode>(Idx)) {
10622     if (VecVT.is512BitVector() ||
10623         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10624          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10625
10626       MVT MaskEltVT =
10627         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10628       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10629                                     MaskEltVT.getSizeInBits());
10630
10631       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10632       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10633                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10634                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10635       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10636       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10637                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10638     }
10639     return SDValue();
10640   }
10641
10642   // If this is a 256-bit vector result, first extract the 128-bit vector and
10643   // then extract the element from the 128-bit vector.
10644   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10645
10646     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10647     // Get the 128-bit vector.
10648     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10649     MVT EltVT = VecVT.getVectorElementType();
10650
10651     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10652
10653     //if (IdxVal >= NumElems/2)
10654     //  IdxVal -= NumElems/2;
10655     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10656     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10657                        DAG.getConstant(IdxVal, dl, MVT::i32));
10658   }
10659
10660   assert(VecVT.is128BitVector() && "Unexpected vector length");
10661
10662   if (Subtarget->hasSSE41()) {
10663     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10664     if (Res.getNode())
10665       return Res;
10666   }
10667
10668   MVT VT = Op.getSimpleValueType();
10669   // TODO: handle v16i8.
10670   if (VT.getSizeInBits() == 16) {
10671     SDValue Vec = Op.getOperand(0);
10672     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10673     if (Idx == 0)
10674       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10675                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10676                                      DAG.getNode(ISD::BITCAST, dl,
10677                                                  MVT::v4i32, Vec),
10678                                      Op.getOperand(1)));
10679     // Transform it so it match pextrw which produces a 32-bit result.
10680     MVT EltVT = MVT::i32;
10681     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10682                                   Op.getOperand(0), Op.getOperand(1));
10683     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10684                                   DAG.getValueType(VT));
10685     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10686   }
10687
10688   if (VT.getSizeInBits() == 32) {
10689     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10690     if (Idx == 0)
10691       return Op;
10692
10693     // SHUFPS the element to the lowest double word, then movss.
10694     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10695     MVT VVT = Op.getOperand(0).getSimpleValueType();
10696     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10697                                        DAG.getUNDEF(VVT), Mask);
10698     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10699                        DAG.getIntPtrConstant(0, dl));
10700   }
10701
10702   if (VT.getSizeInBits() == 64) {
10703     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10704     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10705     //        to match extract_elt for f64.
10706     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10707     if (Idx == 0)
10708       return Op;
10709
10710     // UNPCKHPD the element to the lowest double word, then movsd.
10711     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10712     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10713     int Mask[2] = { 1, -1 };
10714     MVT VVT = Op.getOperand(0).getSimpleValueType();
10715     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10716                                        DAG.getUNDEF(VVT), Mask);
10717     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10718                        DAG.getIntPtrConstant(0, dl));
10719   }
10720
10721   return SDValue();
10722 }
10723
10724 /// Insert one bit to mask vector, like v16i1 or v8i1.
10725 /// AVX-512 feature.
10726 SDValue
10727 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10728   SDLoc dl(Op);
10729   SDValue Vec = Op.getOperand(0);
10730   SDValue Elt = Op.getOperand(1);
10731   SDValue Idx = Op.getOperand(2);
10732   MVT VecVT = Vec.getSimpleValueType();
10733
10734   if (!isa<ConstantSDNode>(Idx)) {
10735     // Non constant index. Extend source and destination,
10736     // insert element and then truncate the result.
10737     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10738     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10739     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10740       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10741       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10742     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10743   }
10744
10745   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10746   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10747   if (IdxVal)
10748     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10749                            DAG.getConstant(IdxVal, dl, MVT::i8));
10750   if (Vec.getOpcode() == ISD::UNDEF)
10751     return EltInVec;
10752   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10753 }
10754
10755 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10756                                                   SelectionDAG &DAG) const {
10757   MVT VT = Op.getSimpleValueType();
10758   MVT EltVT = VT.getVectorElementType();
10759
10760   if (EltVT == MVT::i1)
10761     return InsertBitToMaskVector(Op, DAG);
10762
10763   SDLoc dl(Op);
10764   SDValue N0 = Op.getOperand(0);
10765   SDValue N1 = Op.getOperand(1);
10766   SDValue N2 = Op.getOperand(2);
10767   if (!isa<ConstantSDNode>(N2))
10768     return SDValue();
10769   auto *N2C = cast<ConstantSDNode>(N2);
10770   unsigned IdxVal = N2C->getZExtValue();
10771
10772   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10773   // into that, and then insert the subvector back into the result.
10774   if (VT.is256BitVector() || VT.is512BitVector()) {
10775     // With a 256-bit vector, we can insert into the zero element efficiently
10776     // using a blend if we have AVX or AVX2 and the right data type.
10777     if (VT.is256BitVector() && IdxVal == 0) {
10778       // TODO: It is worthwhile to cast integer to floating point and back
10779       // and incur a domain crossing penalty if that's what we'll end up
10780       // doing anyway after extracting to a 128-bit vector.
10781       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10782           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10783         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10784         N2 = DAG.getIntPtrConstant(1, dl);
10785         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10786       }
10787     }
10788
10789     // Get the desired 128-bit vector chunk.
10790     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10791
10792     // Insert the element into the desired chunk.
10793     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10794     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10795
10796     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10797                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10798
10799     // Insert the changed part back into the bigger vector
10800     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10801   }
10802   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10803
10804   if (Subtarget->hasSSE41()) {
10805     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10806       unsigned Opc;
10807       if (VT == MVT::v8i16) {
10808         Opc = X86ISD::PINSRW;
10809       } else {
10810         assert(VT == MVT::v16i8);
10811         Opc = X86ISD::PINSRB;
10812       }
10813
10814       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10815       // argument.
10816       if (N1.getValueType() != MVT::i32)
10817         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10818       if (N2.getValueType() != MVT::i32)
10819         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10820       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10821     }
10822
10823     if (EltVT == MVT::f32) {
10824       // Bits [7:6] of the constant are the source select. This will always be
10825       //   zero here. The DAG Combiner may combine an extract_elt index into
10826       //   these bits. For example (insert (extract, 3), 2) could be matched by
10827       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10828       // Bits [5:4] of the constant are the destination select. This is the
10829       //   value of the incoming immediate.
10830       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10831       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10832
10833       const Function *F = DAG.getMachineFunction().getFunction();
10834       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10835       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10836         // If this is an insertion of 32-bits into the low 32-bits of
10837         // a vector, we prefer to generate a blend with immediate rather
10838         // than an insertps. Blends are simpler operations in hardware and so
10839         // will always have equal or better performance than insertps.
10840         // But if optimizing for size and there's a load folding opportunity,
10841         // generate insertps because blendps does not have a 32-bit memory
10842         // operand form.
10843         N2 = DAG.getIntPtrConstant(1, dl);
10844         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10845         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10846       }
10847       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10848       // Create this as a scalar to vector..
10849       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10850       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10851     }
10852
10853     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10854       // PINSR* works with constant index.
10855       return Op;
10856     }
10857   }
10858
10859   if (EltVT == MVT::i8)
10860     return SDValue();
10861
10862   if (EltVT.getSizeInBits() == 16) {
10863     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10864     // as its second argument.
10865     if (N1.getValueType() != MVT::i32)
10866       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10867     if (N2.getValueType() != MVT::i32)
10868       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10869     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10870   }
10871   return SDValue();
10872 }
10873
10874 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10875   SDLoc dl(Op);
10876   MVT OpVT = Op.getSimpleValueType();
10877
10878   // If this is a 256-bit vector result, first insert into a 128-bit
10879   // vector and then insert into the 256-bit vector.
10880   if (!OpVT.is128BitVector()) {
10881     // Insert into a 128-bit vector.
10882     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10883     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10884                                  OpVT.getVectorNumElements() / SizeFactor);
10885
10886     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10887
10888     // Insert the 128-bit vector.
10889     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10890   }
10891
10892   if (OpVT == MVT::v1i64 &&
10893       Op.getOperand(0).getValueType() == MVT::i64)
10894     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10895
10896   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10897   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10898   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10899                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10900 }
10901
10902 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10903 // a simple subregister reference or explicit instructions to grab
10904 // upper bits of a vector.
10905 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10906                                       SelectionDAG &DAG) {
10907   SDLoc dl(Op);
10908   SDValue In =  Op.getOperand(0);
10909   SDValue Idx = Op.getOperand(1);
10910   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10911   MVT ResVT   = Op.getSimpleValueType();
10912   MVT InVT    = In.getSimpleValueType();
10913
10914   if (Subtarget->hasFp256()) {
10915     if (ResVT.is128BitVector() &&
10916         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10917         isa<ConstantSDNode>(Idx)) {
10918       return Extract128BitVector(In, IdxVal, DAG, dl);
10919     }
10920     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10921         isa<ConstantSDNode>(Idx)) {
10922       return Extract256BitVector(In, IdxVal, DAG, dl);
10923     }
10924   }
10925   return SDValue();
10926 }
10927
10928 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10929 // simple superregister reference or explicit instructions to insert
10930 // the upper bits of a vector.
10931 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10932                                      SelectionDAG &DAG) {
10933   if (!Subtarget->hasAVX())
10934     return SDValue();
10935
10936   SDLoc dl(Op);
10937   SDValue Vec = Op.getOperand(0);
10938   SDValue SubVec = Op.getOperand(1);
10939   SDValue Idx = Op.getOperand(2);
10940
10941   if (!isa<ConstantSDNode>(Idx))
10942     return SDValue();
10943
10944   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10945   MVT OpVT = Op.getSimpleValueType();
10946   MVT SubVecVT = SubVec.getSimpleValueType();
10947
10948   // Fold two 16-byte subvector loads into one 32-byte load:
10949   // (insert_subvector (insert_subvector undef, (load addr), 0),
10950   //                   (load addr + 16), Elts/2)
10951   // --> load32 addr
10952   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10953       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10954       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10955       !Subtarget->isUnalignedMem32Slow()) {
10956     SDValue SubVec2 = Vec.getOperand(1);
10957     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10958       if (Idx2->getZExtValue() == 0) {
10959         SDValue Ops[] = { SubVec2, SubVec };
10960         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10961         if (LD.getNode())
10962           return LD;
10963       }
10964     }
10965   }
10966
10967   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10968       SubVecVT.is128BitVector())
10969     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10970
10971   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10972     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10973
10974   if (OpVT.getVectorElementType() == MVT::i1) {
10975     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10976       return Op;
10977     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10978     SDValue Undef = DAG.getUNDEF(OpVT);
10979     unsigned NumElems = OpVT.getVectorNumElements();
10980     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10981
10982     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10983       // Zero upper bits of the Vec
10984       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10985       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10986
10987       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10988                                  SubVec, ZeroIdx);
10989       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10990       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10991     }
10992     if (IdxVal == 0) {
10993       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10994                                  SubVec, ZeroIdx);
10995       // Zero upper bits of the Vec2
10996       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10997       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10998       // Zero lower bits of the Vec
10999       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11000       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11001       // Merge them together
11002       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11003     }
11004   }
11005   return SDValue();
11006 }
11007
11008 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11009 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11010 // one of the above mentioned nodes. It has to be wrapped because otherwise
11011 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11012 // be used to form addressing mode. These wrapped nodes will be selected
11013 // into MOV32ri.
11014 SDValue
11015 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11016   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11017
11018   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11019   // global base reg.
11020   unsigned char OpFlag = 0;
11021   unsigned WrapperKind = X86ISD::Wrapper;
11022   CodeModel::Model M = DAG.getTarget().getCodeModel();
11023
11024   if (Subtarget->isPICStyleRIPRel() &&
11025       (M == CodeModel::Small || M == CodeModel::Kernel))
11026     WrapperKind = X86ISD::WrapperRIP;
11027   else if (Subtarget->isPICStyleGOT())
11028     OpFlag = X86II::MO_GOTOFF;
11029   else if (Subtarget->isPICStyleStubPIC())
11030     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11031
11032   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11033                                              CP->getAlignment(),
11034                                              CP->getOffset(), OpFlag);
11035   SDLoc DL(CP);
11036   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11037   // With PIC, the address is actually $g + Offset.
11038   if (OpFlag) {
11039     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11040                          DAG.getNode(X86ISD::GlobalBaseReg,
11041                                      SDLoc(), getPointerTy()),
11042                          Result);
11043   }
11044
11045   return Result;
11046 }
11047
11048 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11049   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11050
11051   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11052   // global base reg.
11053   unsigned char OpFlag = 0;
11054   unsigned WrapperKind = X86ISD::Wrapper;
11055   CodeModel::Model M = DAG.getTarget().getCodeModel();
11056
11057   if (Subtarget->isPICStyleRIPRel() &&
11058       (M == CodeModel::Small || M == CodeModel::Kernel))
11059     WrapperKind = X86ISD::WrapperRIP;
11060   else if (Subtarget->isPICStyleGOT())
11061     OpFlag = X86II::MO_GOTOFF;
11062   else if (Subtarget->isPICStyleStubPIC())
11063     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11064
11065   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11066                                           OpFlag);
11067   SDLoc DL(JT);
11068   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11069
11070   // With PIC, the address is actually $g + Offset.
11071   if (OpFlag)
11072     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11073                          DAG.getNode(X86ISD::GlobalBaseReg,
11074                                      SDLoc(), getPointerTy()),
11075                          Result);
11076
11077   return Result;
11078 }
11079
11080 SDValue
11081 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11082   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11083
11084   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11085   // global base reg.
11086   unsigned char OpFlag = 0;
11087   unsigned WrapperKind = X86ISD::Wrapper;
11088   CodeModel::Model M = DAG.getTarget().getCodeModel();
11089
11090   if (Subtarget->isPICStyleRIPRel() &&
11091       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11092     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11093       OpFlag = X86II::MO_GOTPCREL;
11094     WrapperKind = X86ISD::WrapperRIP;
11095   } else if (Subtarget->isPICStyleGOT()) {
11096     OpFlag = X86II::MO_GOT;
11097   } else if (Subtarget->isPICStyleStubPIC()) {
11098     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11099   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11100     OpFlag = X86II::MO_DARWIN_NONLAZY;
11101   }
11102
11103   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11104
11105   SDLoc DL(Op);
11106   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11107
11108   // With PIC, the address is actually $g + Offset.
11109   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11110       !Subtarget->is64Bit()) {
11111     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11112                          DAG.getNode(X86ISD::GlobalBaseReg,
11113                                      SDLoc(), getPointerTy()),
11114                          Result);
11115   }
11116
11117   // For symbols that require a load from a stub to get the address, emit the
11118   // load.
11119   if (isGlobalStubReference(OpFlag))
11120     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11121                          MachinePointerInfo::getGOT(), false, false, false, 0);
11122
11123   return Result;
11124 }
11125
11126 SDValue
11127 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11128   // Create the TargetBlockAddressAddress node.
11129   unsigned char OpFlags =
11130     Subtarget->ClassifyBlockAddressReference();
11131   CodeModel::Model M = DAG.getTarget().getCodeModel();
11132   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11133   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11134   SDLoc dl(Op);
11135   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11136                                              OpFlags);
11137
11138   if (Subtarget->isPICStyleRIPRel() &&
11139       (M == CodeModel::Small || M == CodeModel::Kernel))
11140     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11141   else
11142     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11143
11144   // With PIC, the address is actually $g + Offset.
11145   if (isGlobalRelativeToPICBase(OpFlags)) {
11146     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11147                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11148                          Result);
11149   }
11150
11151   return Result;
11152 }
11153
11154 SDValue
11155 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11156                                       int64_t Offset, SelectionDAG &DAG) const {
11157   // Create the TargetGlobalAddress node, folding in the constant
11158   // offset if it is legal.
11159   unsigned char OpFlags =
11160       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11161   CodeModel::Model M = DAG.getTarget().getCodeModel();
11162   SDValue Result;
11163   if (OpFlags == X86II::MO_NO_FLAG &&
11164       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11165     // A direct static reference to a global.
11166     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11167     Offset = 0;
11168   } else {
11169     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11170   }
11171
11172   if (Subtarget->isPICStyleRIPRel() &&
11173       (M == CodeModel::Small || M == CodeModel::Kernel))
11174     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11175   else
11176     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11177
11178   // With PIC, the address is actually $g + Offset.
11179   if (isGlobalRelativeToPICBase(OpFlags)) {
11180     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11181                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11182                          Result);
11183   }
11184
11185   // For globals that require a load from a stub to get the address, emit the
11186   // load.
11187   if (isGlobalStubReference(OpFlags))
11188     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11189                          MachinePointerInfo::getGOT(), false, false, false, 0);
11190
11191   // If there was a non-zero offset that we didn't fold, create an explicit
11192   // addition for it.
11193   if (Offset != 0)
11194     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11195                          DAG.getConstant(Offset, dl, getPointerTy()));
11196
11197   return Result;
11198 }
11199
11200 SDValue
11201 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11202   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11203   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11204   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11205 }
11206
11207 static SDValue
11208 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11209            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11210            unsigned char OperandFlags, bool LocalDynamic = false) {
11211   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11212   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11213   SDLoc dl(GA);
11214   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11215                                            GA->getValueType(0),
11216                                            GA->getOffset(),
11217                                            OperandFlags);
11218
11219   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11220                                            : X86ISD::TLSADDR;
11221
11222   if (InFlag) {
11223     SDValue Ops[] = { Chain,  TGA, *InFlag };
11224     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11225   } else {
11226     SDValue Ops[]  = { Chain, TGA };
11227     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11228   }
11229
11230   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11231   MFI->setAdjustsStack(true);
11232   MFI->setHasCalls(true);
11233
11234   SDValue Flag = Chain.getValue(1);
11235   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11236 }
11237
11238 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11239 static SDValue
11240 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11241                                 const EVT PtrVT) {
11242   SDValue InFlag;
11243   SDLoc dl(GA);  // ? function entry point might be better
11244   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11245                                    DAG.getNode(X86ISD::GlobalBaseReg,
11246                                                SDLoc(), PtrVT), InFlag);
11247   InFlag = Chain.getValue(1);
11248
11249   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11250 }
11251
11252 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11253 static SDValue
11254 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11255                                 const EVT PtrVT) {
11256   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11257                     X86::RAX, X86II::MO_TLSGD);
11258 }
11259
11260 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11261                                            SelectionDAG &DAG,
11262                                            const EVT PtrVT,
11263                                            bool is64Bit) {
11264   SDLoc dl(GA);
11265
11266   // Get the start address of the TLS block for this module.
11267   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11268       .getInfo<X86MachineFunctionInfo>();
11269   MFI->incNumLocalDynamicTLSAccesses();
11270
11271   SDValue Base;
11272   if (is64Bit) {
11273     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11274                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11275   } else {
11276     SDValue InFlag;
11277     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11278         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11279     InFlag = Chain.getValue(1);
11280     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11281                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11282   }
11283
11284   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11285   // of Base.
11286
11287   // Build x@dtpoff.
11288   unsigned char OperandFlags = X86II::MO_DTPOFF;
11289   unsigned WrapperKind = X86ISD::Wrapper;
11290   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11291                                            GA->getValueType(0),
11292                                            GA->getOffset(), OperandFlags);
11293   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11294
11295   // Add x@dtpoff with the base.
11296   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11297 }
11298
11299 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11300 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11301                                    const EVT PtrVT, TLSModel::Model model,
11302                                    bool is64Bit, bool isPIC) {
11303   SDLoc dl(GA);
11304
11305   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11306   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11307                                                          is64Bit ? 257 : 256));
11308
11309   SDValue ThreadPointer =
11310       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11311                   MachinePointerInfo(Ptr), false, false, false, 0);
11312
11313   unsigned char OperandFlags = 0;
11314   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11315   // initialexec.
11316   unsigned WrapperKind = X86ISD::Wrapper;
11317   if (model == TLSModel::LocalExec) {
11318     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11319   } else if (model == TLSModel::InitialExec) {
11320     if (is64Bit) {
11321       OperandFlags = X86II::MO_GOTTPOFF;
11322       WrapperKind = X86ISD::WrapperRIP;
11323     } else {
11324       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11325     }
11326   } else {
11327     llvm_unreachable("Unexpected model");
11328   }
11329
11330   // emit "addl x@ntpoff,%eax" (local exec)
11331   // or "addl x@indntpoff,%eax" (initial exec)
11332   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11333   SDValue TGA =
11334       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11335                                  GA->getOffset(), OperandFlags);
11336   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11337
11338   if (model == TLSModel::InitialExec) {
11339     if (isPIC && !is64Bit) {
11340       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11341                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11342                            Offset);
11343     }
11344
11345     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11346                          MachinePointerInfo::getGOT(), false, false, false, 0);
11347   }
11348
11349   // The address of the thread local variable is the add of the thread
11350   // pointer with the offset of the variable.
11351   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11352 }
11353
11354 SDValue
11355 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11356
11357   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11358   const GlobalValue *GV = GA->getGlobal();
11359
11360   if (Subtarget->isTargetELF()) {
11361     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11362     switch (model) {
11363       case TLSModel::GeneralDynamic:
11364         if (Subtarget->is64Bit())
11365           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11366         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11367       case TLSModel::LocalDynamic:
11368         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11369                                            Subtarget->is64Bit());
11370       case TLSModel::InitialExec:
11371       case TLSModel::LocalExec:
11372         return LowerToTLSExecModel(
11373             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11374             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11375     }
11376     llvm_unreachable("Unknown TLS model.");
11377   }
11378
11379   if (Subtarget->isTargetDarwin()) {
11380     // Darwin only has one model of TLS.  Lower to that.
11381     unsigned char OpFlag = 0;
11382     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11383                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11384
11385     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11386     // global base reg.
11387     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11388                  !Subtarget->is64Bit();
11389     if (PIC32)
11390       OpFlag = X86II::MO_TLVP_PIC_BASE;
11391     else
11392       OpFlag = X86II::MO_TLVP;
11393     SDLoc DL(Op);
11394     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11395                                                 GA->getValueType(0),
11396                                                 GA->getOffset(), OpFlag);
11397     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11398
11399     // With PIC32, the address is actually $g + Offset.
11400     if (PIC32)
11401       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11402                            DAG.getNode(X86ISD::GlobalBaseReg,
11403                                        SDLoc(), getPointerTy()),
11404                            Offset);
11405
11406     // Lowering the machine isd will make sure everything is in the right
11407     // location.
11408     SDValue Chain = DAG.getEntryNode();
11409     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11410     SDValue Args[] = { Chain, Offset };
11411     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11412
11413     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11414     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11415     MFI->setAdjustsStack(true);
11416
11417     // And our return value (tls address) is in the standard call return value
11418     // location.
11419     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11420     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11421                               Chain.getValue(1));
11422   }
11423
11424   if (Subtarget->isTargetKnownWindowsMSVC() ||
11425       Subtarget->isTargetWindowsGNU()) {
11426     // Just use the implicit TLS architecture
11427     // Need to generate someting similar to:
11428     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11429     //                                  ; from TEB
11430     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11431     //   mov     rcx, qword [rdx+rcx*8]
11432     //   mov     eax, .tls$:tlsvar
11433     //   [rax+rcx] contains the address
11434     // Windows 64bit: gs:0x58
11435     // Windows 32bit: fs:__tls_array
11436
11437     SDLoc dl(GA);
11438     SDValue Chain = DAG.getEntryNode();
11439
11440     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11441     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11442     // use its literal value of 0x2C.
11443     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11444                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11445                                                              256)
11446                                         : Type::getInt32PtrTy(*DAG.getContext(),
11447                                                               257));
11448
11449     SDValue TlsArray =
11450         Subtarget->is64Bit()
11451             ? DAG.getIntPtrConstant(0x58, dl)
11452             : (Subtarget->isTargetWindowsGNU()
11453                    ? DAG.getIntPtrConstant(0x2C, dl)
11454                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11455
11456     SDValue ThreadPointer =
11457         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11458                     MachinePointerInfo(Ptr), false, false, false, 0);
11459
11460     SDValue res;
11461     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11462       res = ThreadPointer;
11463     } else {
11464       // Load the _tls_index variable
11465       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11466       if (Subtarget->is64Bit())
11467         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11468                              MachinePointerInfo(), MVT::i32, false, false,
11469                              false, 0);
11470       else
11471         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11472                           false, false, false, 0);
11473
11474       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11475                                       getPointerTy());
11476       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11477
11478       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11479     }
11480
11481     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11482                       false, false, false, 0);
11483
11484     // Get the offset of start of .tls section
11485     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11486                                              GA->getValueType(0),
11487                                              GA->getOffset(), X86II::MO_SECREL);
11488     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11489
11490     // The address of the thread local variable is the add of the thread
11491     // pointer with the offset of the variable.
11492     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11493   }
11494
11495   llvm_unreachable("TLS not implemented for this target.");
11496 }
11497
11498 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11499 /// and take a 2 x i32 value to shift plus a shift amount.
11500 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11501   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11502   MVT VT = Op.getSimpleValueType();
11503   unsigned VTBits = VT.getSizeInBits();
11504   SDLoc dl(Op);
11505   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11506   SDValue ShOpLo = Op.getOperand(0);
11507   SDValue ShOpHi = Op.getOperand(1);
11508   SDValue ShAmt  = Op.getOperand(2);
11509   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11510   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11511   // during isel.
11512   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11513                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11514   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11515                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11516                        : DAG.getConstant(0, dl, VT);
11517
11518   SDValue Tmp2, Tmp3;
11519   if (Op.getOpcode() == ISD::SHL_PARTS) {
11520     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11521     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11522   } else {
11523     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11524     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11525   }
11526
11527   // If the shift amount is larger or equal than the width of a part we can't
11528   // rely on the results of shld/shrd. Insert a test and select the appropriate
11529   // values for large shift amounts.
11530   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11531                                 DAG.getConstant(VTBits, dl, MVT::i8));
11532   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11533                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11534
11535   SDValue Hi, Lo;
11536   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11537   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11538   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11539
11540   if (Op.getOpcode() == ISD::SHL_PARTS) {
11541     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11542     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11543   } else {
11544     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11545     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11546   }
11547
11548   SDValue Ops[2] = { Lo, Hi };
11549   return DAG.getMergeValues(Ops, dl);
11550 }
11551
11552 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11553                                            SelectionDAG &DAG) const {
11554   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11555   SDLoc dl(Op);
11556
11557   if (SrcVT.isVector()) {
11558     if (SrcVT.getVectorElementType() == MVT::i1) {
11559       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11560       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11561                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11562                                      Op.getOperand(0)));
11563     }
11564     return SDValue();
11565   }
11566
11567   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11568          "Unknown SINT_TO_FP to lower!");
11569
11570   // These are really Legal; return the operand so the caller accepts it as
11571   // Legal.
11572   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11573     return Op;
11574   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11575       Subtarget->is64Bit()) {
11576     return Op;
11577   }
11578
11579   unsigned Size = SrcVT.getSizeInBits()/8;
11580   MachineFunction &MF = DAG.getMachineFunction();
11581   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11582   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11583   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11584                                StackSlot,
11585                                MachinePointerInfo::getFixedStack(SSFI),
11586                                false, false, 0);
11587   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11588 }
11589
11590 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11591                                      SDValue StackSlot,
11592                                      SelectionDAG &DAG) const {
11593   // Build the FILD
11594   SDLoc DL(Op);
11595   SDVTList Tys;
11596   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11597   if (useSSE)
11598     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11599   else
11600     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11601
11602   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11603
11604   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11605   MachineMemOperand *MMO;
11606   if (FI) {
11607     int SSFI = FI->getIndex();
11608     MMO =
11609       DAG.getMachineFunction()
11610       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11611                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11612   } else {
11613     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11614     StackSlot = StackSlot.getOperand(1);
11615   }
11616   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11617   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11618                                            X86ISD::FILD, DL,
11619                                            Tys, Ops, SrcVT, MMO);
11620
11621   if (useSSE) {
11622     Chain = Result.getValue(1);
11623     SDValue InFlag = Result.getValue(2);
11624
11625     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11626     // shouldn't be necessary except that RFP cannot be live across
11627     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11628     MachineFunction &MF = DAG.getMachineFunction();
11629     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11630     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11631     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11632     Tys = DAG.getVTList(MVT::Other);
11633     SDValue Ops[] = {
11634       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11635     };
11636     MachineMemOperand *MMO =
11637       DAG.getMachineFunction()
11638       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11639                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11640
11641     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11642                                     Ops, Op.getValueType(), MMO);
11643     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11644                          MachinePointerInfo::getFixedStack(SSFI),
11645                          false, false, false, 0);
11646   }
11647
11648   return Result;
11649 }
11650
11651 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11652 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11653                                                SelectionDAG &DAG) const {
11654   // This algorithm is not obvious. Here it is what we're trying to output:
11655   /*
11656      movq       %rax,  %xmm0
11657      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11658      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11659      #ifdef __SSE3__
11660        haddpd   %xmm0, %xmm0
11661      #else
11662        pshufd   $0x4e, %xmm0, %xmm1
11663        addpd    %xmm1, %xmm0
11664      #endif
11665   */
11666
11667   SDLoc dl(Op);
11668   LLVMContext *Context = DAG.getContext();
11669
11670   // Build some magic constants.
11671   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11672   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11673   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11674
11675   SmallVector<Constant*,2> CV1;
11676   CV1.push_back(
11677     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11678                                       APInt(64, 0x4330000000000000ULL))));
11679   CV1.push_back(
11680     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11681                                       APInt(64, 0x4530000000000000ULL))));
11682   Constant *C1 = ConstantVector::get(CV1);
11683   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11684
11685   // Load the 64-bit value into an XMM register.
11686   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11687                             Op.getOperand(0));
11688   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11689                               MachinePointerInfo::getConstantPool(),
11690                               false, false, false, 16);
11691   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11692                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11693                               CLod0);
11694
11695   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11696                               MachinePointerInfo::getConstantPool(),
11697                               false, false, false, 16);
11698   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11699   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11700   SDValue Result;
11701
11702   if (Subtarget->hasSSE3()) {
11703     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11704     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11705   } else {
11706     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11707     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11708                                            S2F, 0x4E, DAG);
11709     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11710                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11711                          Sub);
11712   }
11713
11714   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11715                      DAG.getIntPtrConstant(0, dl));
11716 }
11717
11718 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11719 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11720                                                SelectionDAG &DAG) const {
11721   SDLoc dl(Op);
11722   // FP constant to bias correct the final result.
11723   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11724                                    MVT::f64);
11725
11726   // Load the 32-bit value into an XMM register.
11727   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11728                              Op.getOperand(0));
11729
11730   // Zero out the upper parts of the register.
11731   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11732
11733   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11734                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11735                      DAG.getIntPtrConstant(0, dl));
11736
11737   // Or the load with the bias.
11738   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11739                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11740                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11741                                                    MVT::v2f64, Load)),
11742                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11743                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11744                                                    MVT::v2f64, Bias)));
11745   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11746                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11747                    DAG.getIntPtrConstant(0, dl));
11748
11749   // Subtract the bias.
11750   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11751
11752   // Handle final rounding.
11753   EVT DestVT = Op.getValueType();
11754
11755   if (DestVT.bitsLT(MVT::f64))
11756     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11757                        DAG.getIntPtrConstant(0, dl));
11758   if (DestVT.bitsGT(MVT::f64))
11759     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11760
11761   // Handle final rounding.
11762   return Sub;
11763 }
11764
11765 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11766                                      const X86Subtarget &Subtarget) {
11767   // The algorithm is the following:
11768   // #ifdef __SSE4_1__
11769   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11770   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11771   //                                 (uint4) 0x53000000, 0xaa);
11772   // #else
11773   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11774   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11775   // #endif
11776   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11777   //     return (float4) lo + fhi;
11778
11779   SDLoc DL(Op);
11780   SDValue V = Op->getOperand(0);
11781   EVT VecIntVT = V.getValueType();
11782   bool Is128 = VecIntVT == MVT::v4i32;
11783   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11784   // If we convert to something else than the supported type, e.g., to v4f64,
11785   // abort early.
11786   if (VecFloatVT != Op->getValueType(0))
11787     return SDValue();
11788
11789   unsigned NumElts = VecIntVT.getVectorNumElements();
11790   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11791          "Unsupported custom type");
11792   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11793
11794   // In the #idef/#else code, we have in common:
11795   // - The vector of constants:
11796   // -- 0x4b000000
11797   // -- 0x53000000
11798   // - A shift:
11799   // -- v >> 16
11800
11801   // Create the splat vector for 0x4b000000.
11802   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11803   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11804                            CstLow, CstLow, CstLow, CstLow};
11805   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11806                                   makeArrayRef(&CstLowArray[0], NumElts));
11807   // Create the splat vector for 0x53000000.
11808   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11809   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11810                             CstHigh, CstHigh, CstHigh, CstHigh};
11811   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11812                                    makeArrayRef(&CstHighArray[0], NumElts));
11813
11814   // Create the right shift.
11815   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11816   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11817                              CstShift, CstShift, CstShift, CstShift};
11818   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11819                                     makeArrayRef(&CstShiftArray[0], NumElts));
11820   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11821
11822   SDValue Low, High;
11823   if (Subtarget.hasSSE41()) {
11824     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11825     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11826     SDValue VecCstLowBitcast =
11827         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11828     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11829     // Low will be bitcasted right away, so do not bother bitcasting back to its
11830     // original type.
11831     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11832                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11833     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11834     //                                 (uint4) 0x53000000, 0xaa);
11835     SDValue VecCstHighBitcast =
11836         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11837     SDValue VecShiftBitcast =
11838         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11839     // High will be bitcasted right away, so do not bother bitcasting back to
11840     // its original type.
11841     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11842                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11843   } else {
11844     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11845     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11846                                      CstMask, CstMask, CstMask);
11847     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11848     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11849     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11850
11851     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11852     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11853   }
11854
11855   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11856   SDValue CstFAdd = DAG.getConstantFP(
11857       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11858   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11859                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11860   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11861                                    makeArrayRef(&CstFAddArray[0], NumElts));
11862
11863   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11864   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11865   SDValue FHigh =
11866       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11867   //     return (float4) lo + fhi;
11868   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11869   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11870 }
11871
11872 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11873                                                SelectionDAG &DAG) const {
11874   SDValue N0 = Op.getOperand(0);
11875   MVT SVT = N0.getSimpleValueType();
11876   SDLoc dl(Op);
11877
11878   switch (SVT.SimpleTy) {
11879   default:
11880     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11881   case MVT::v4i8:
11882   case MVT::v4i16:
11883   case MVT::v8i8:
11884   case MVT::v8i16: {
11885     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11886     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11887                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11888   }
11889   case MVT::v4i32:
11890   case MVT::v8i32:
11891     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11892   case MVT::v16i8:
11893   case MVT::v16i16:
11894     if (Subtarget->hasAVX512())
11895       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11896                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11897   }
11898   llvm_unreachable(nullptr);
11899 }
11900
11901 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11902                                            SelectionDAG &DAG) const {
11903   SDValue N0 = Op.getOperand(0);
11904   SDLoc dl(Op);
11905
11906   if (Op.getValueType().isVector())
11907     return lowerUINT_TO_FP_vec(Op, DAG);
11908
11909   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11910   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11911   // the optimization here.
11912   if (DAG.SignBitIsZero(N0))
11913     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11914
11915   MVT SrcVT = N0.getSimpleValueType();
11916   MVT DstVT = Op.getSimpleValueType();
11917   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11918     return LowerUINT_TO_FP_i64(Op, DAG);
11919   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11920     return LowerUINT_TO_FP_i32(Op, DAG);
11921   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11922     return SDValue();
11923
11924   // Make a 64-bit buffer, and use it to build an FILD.
11925   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11926   if (SrcVT == MVT::i32) {
11927     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11928     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11929                                      getPointerTy(), StackSlot, WordOff);
11930     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11931                                   StackSlot, MachinePointerInfo(),
11932                                   false, false, 0);
11933     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11934                                   OffsetSlot, MachinePointerInfo(),
11935                                   false, false, 0);
11936     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11937     return Fild;
11938   }
11939
11940   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11941   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11942                                StackSlot, MachinePointerInfo(),
11943                                false, false, 0);
11944   // For i64 source, we need to add the appropriate power of 2 if the input
11945   // was negative.  This is the same as the optimization in
11946   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11947   // we must be careful to do the computation in x87 extended precision, not
11948   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11949   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11950   MachineMemOperand *MMO =
11951     DAG.getMachineFunction()
11952     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11953                           MachineMemOperand::MOLoad, 8, 8);
11954
11955   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11956   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11957   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11958                                          MVT::i64, MMO);
11959
11960   APInt FF(32, 0x5F800000ULL);
11961
11962   // Check whether the sign bit is set.
11963   SDValue SignSet = DAG.getSetCC(dl,
11964                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11965                                  Op.getOperand(0),
11966                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11967
11968   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11969   SDValue FudgePtr = DAG.getConstantPool(
11970                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11971                                          getPointerTy());
11972
11973   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11974   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11975   SDValue Four = DAG.getIntPtrConstant(4, dl);
11976   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11977                                Zero, Four);
11978   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11979
11980   // Load the value out, extending it from f32 to f80.
11981   // FIXME: Avoid the extend by constructing the right constant pool?
11982   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11983                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11984                                  MVT::f32, false, false, false, 4);
11985   // Extend everything to 80 bits to force it to be done on x87.
11986   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11987   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11988                      DAG.getIntPtrConstant(0, dl));
11989 }
11990
11991 std::pair<SDValue,SDValue>
11992 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11993                                     bool IsSigned, bool IsReplace) const {
11994   SDLoc DL(Op);
11995
11996   EVT DstTy = Op.getValueType();
11997
11998   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11999     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12000     DstTy = MVT::i64;
12001   }
12002
12003   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12004          DstTy.getSimpleVT() >= MVT::i16 &&
12005          "Unknown FP_TO_INT to lower!");
12006
12007   // These are really Legal.
12008   if (DstTy == MVT::i32 &&
12009       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12010     return std::make_pair(SDValue(), SDValue());
12011   if (Subtarget->is64Bit() &&
12012       DstTy == MVT::i64 &&
12013       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12014     return std::make_pair(SDValue(), SDValue());
12015
12016   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12017   // stack slot, or into the FTOL runtime function.
12018   MachineFunction &MF = DAG.getMachineFunction();
12019   unsigned MemSize = DstTy.getSizeInBits()/8;
12020   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12021   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12022
12023   unsigned Opc;
12024   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12025     Opc = X86ISD::WIN_FTOL;
12026   else
12027     switch (DstTy.getSimpleVT().SimpleTy) {
12028     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12029     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12030     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12031     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12032     }
12033
12034   SDValue Chain = DAG.getEntryNode();
12035   SDValue Value = Op.getOperand(0);
12036   EVT TheVT = Op.getOperand(0).getValueType();
12037   // FIXME This causes a redundant load/store if the SSE-class value is already
12038   // in memory, such as if it is on the callstack.
12039   if (isScalarFPTypeInSSEReg(TheVT)) {
12040     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12041     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12042                          MachinePointerInfo::getFixedStack(SSFI),
12043                          false, false, 0);
12044     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12045     SDValue Ops[] = {
12046       Chain, StackSlot, DAG.getValueType(TheVT)
12047     };
12048
12049     MachineMemOperand *MMO =
12050       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12051                               MachineMemOperand::MOLoad, MemSize, MemSize);
12052     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12053     Chain = Value.getValue(1);
12054     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12055     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12056   }
12057
12058   MachineMemOperand *MMO =
12059     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12060                             MachineMemOperand::MOStore, MemSize, MemSize);
12061
12062   if (Opc != X86ISD::WIN_FTOL) {
12063     // Build the FP_TO_INT*_IN_MEM
12064     SDValue Ops[] = { Chain, Value, StackSlot };
12065     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12066                                            Ops, DstTy, MMO);
12067     return std::make_pair(FIST, StackSlot);
12068   } else {
12069     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12070       DAG.getVTList(MVT::Other, MVT::Glue),
12071       Chain, Value);
12072     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12073       MVT::i32, ftol.getValue(1));
12074     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12075       MVT::i32, eax.getValue(2));
12076     SDValue Ops[] = { eax, edx };
12077     SDValue pair = IsReplace
12078       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12079       : DAG.getMergeValues(Ops, DL);
12080     return std::make_pair(pair, SDValue());
12081   }
12082 }
12083
12084 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12085                               const X86Subtarget *Subtarget) {
12086   MVT VT = Op->getSimpleValueType(0);
12087   SDValue In = Op->getOperand(0);
12088   MVT InVT = In.getSimpleValueType();
12089   SDLoc dl(Op);
12090
12091   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12092     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12093
12094   // Optimize vectors in AVX mode:
12095   //
12096   //   v8i16 -> v8i32
12097   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12098   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12099   //   Concat upper and lower parts.
12100   //
12101   //   v4i32 -> v4i64
12102   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12103   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12104   //   Concat upper and lower parts.
12105   //
12106
12107   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12108       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12109       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12110     return SDValue();
12111
12112   if (Subtarget->hasInt256())
12113     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12114
12115   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12116   SDValue Undef = DAG.getUNDEF(InVT);
12117   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12118   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12119   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12120
12121   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12122                              VT.getVectorNumElements()/2);
12123
12124   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12125   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12126
12127   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12128 }
12129
12130 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12131                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12132   MVT VT = Op->getSimpleValueType(0);
12133   SDValue In = Op->getOperand(0);
12134   MVT InVT = In.getSimpleValueType();
12135   SDLoc DL(Op);
12136   unsigned int NumElts = VT.getVectorNumElements();
12137   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12138     return SDValue();
12139
12140   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12141     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12142
12143   assert(InVT.getVectorElementType() == MVT::i1);
12144   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12145   SDValue One =
12146    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12147   SDValue Zero =
12148    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12149
12150   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12151   if (VT.is512BitVector())
12152     return V;
12153   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12154 }
12155
12156 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12157                                SelectionDAG &DAG) {
12158   if (Subtarget->hasFp256()) {
12159     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12160     if (Res.getNode())
12161       return Res;
12162   }
12163
12164   return SDValue();
12165 }
12166
12167 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12168                                 SelectionDAG &DAG) {
12169   SDLoc DL(Op);
12170   MVT VT = Op.getSimpleValueType();
12171   SDValue In = Op.getOperand(0);
12172   MVT SVT = In.getSimpleValueType();
12173
12174   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12175     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12176
12177   if (Subtarget->hasFp256()) {
12178     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12179     if (Res.getNode())
12180       return Res;
12181   }
12182
12183   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12184          VT.getVectorNumElements() != SVT.getVectorNumElements());
12185   return SDValue();
12186 }
12187
12188 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12189   SDLoc DL(Op);
12190   MVT VT = Op.getSimpleValueType();
12191   SDValue In = Op.getOperand(0);
12192   MVT InVT = In.getSimpleValueType();
12193
12194   if (VT == MVT::i1) {
12195     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12196            "Invalid scalar TRUNCATE operation");
12197     if (InVT.getSizeInBits() >= 32)
12198       return SDValue();
12199     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12200     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12201   }
12202   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12203          "Invalid TRUNCATE operation");
12204
12205   // move vector to mask - truncate solution for SKX
12206   if (VT.getVectorElementType() == MVT::i1) {
12207     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12208         Subtarget->hasBWI())
12209       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12210     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12211         && InVT.getScalarSizeInBits() <= 16 &&
12212         Subtarget->hasBWI() && Subtarget->hasVLX())
12213       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12214     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12215         Subtarget->hasDQI())
12216       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12217     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12218         && InVT.getScalarSizeInBits() >= 32 &&
12219         Subtarget->hasDQI() && Subtarget->hasVLX())
12220       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12221   }
12222   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12223     if (VT.getVectorElementType().getSizeInBits() >=8)
12224       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12225
12226     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12227     unsigned NumElts = InVT.getVectorNumElements();
12228     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12229     if (InVT.getSizeInBits() < 512) {
12230       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12231       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12232       InVT = ExtVT;
12233     }
12234
12235     SDValue OneV =
12236      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12237     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12238     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12239   }
12240
12241   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12242     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12243     if (Subtarget->hasInt256()) {
12244       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12245       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12246       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12247                                 ShufMask);
12248       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12249                          DAG.getIntPtrConstant(0, DL));
12250     }
12251
12252     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12253                                DAG.getIntPtrConstant(0, DL));
12254     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12255                                DAG.getIntPtrConstant(2, DL));
12256     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12257     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12258     static const int ShufMask[] = {0, 2, 4, 6};
12259     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12260   }
12261
12262   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12263     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12264     if (Subtarget->hasInt256()) {
12265       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12266
12267       SmallVector<SDValue,32> pshufbMask;
12268       for (unsigned i = 0; i < 2; ++i) {
12269         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12270         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12271         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12272         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12273         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12274         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12275         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12276         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12277         for (unsigned j = 0; j < 8; ++j)
12278           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12279       }
12280       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12281       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12282       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12283
12284       static const int ShufMask[] = {0,  2,  -1,  -1};
12285       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12286                                 &ShufMask[0]);
12287       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12288                        DAG.getIntPtrConstant(0, DL));
12289       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12290     }
12291
12292     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12293                                DAG.getIntPtrConstant(0, DL));
12294
12295     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12296                                DAG.getIntPtrConstant(4, DL));
12297
12298     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12299     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12300
12301     // The PSHUFB mask:
12302     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12303                                    -1, -1, -1, -1, -1, -1, -1, -1};
12304
12305     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12306     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12307     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12308
12309     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12310     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12311
12312     // The MOVLHPS Mask:
12313     static const int ShufMask2[] = {0, 1, 4, 5};
12314     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12315     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12316   }
12317
12318   // Handle truncation of V256 to V128 using shuffles.
12319   if (!VT.is128BitVector() || !InVT.is256BitVector())
12320     return SDValue();
12321
12322   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12323
12324   unsigned NumElems = VT.getVectorNumElements();
12325   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12326
12327   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12328   // Prepare truncation shuffle mask
12329   for (unsigned i = 0; i != NumElems; ++i)
12330     MaskVec[i] = i * 2;
12331   SDValue V = DAG.getVectorShuffle(NVT, DL,
12332                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12333                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12334   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12335                      DAG.getIntPtrConstant(0, DL));
12336 }
12337
12338 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12339                                            SelectionDAG &DAG) const {
12340   assert(!Op.getSimpleValueType().isVector());
12341
12342   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12343     /*IsSigned=*/ true, /*IsReplace=*/ false);
12344   SDValue FIST = Vals.first, StackSlot = Vals.second;
12345   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12346   if (!FIST.getNode()) return Op;
12347
12348   if (StackSlot.getNode())
12349     // Load the result.
12350     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12351                        FIST, StackSlot, MachinePointerInfo(),
12352                        false, false, false, 0);
12353
12354   // The node is the result.
12355   return FIST;
12356 }
12357
12358 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12359                                            SelectionDAG &DAG) const {
12360   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12361     /*IsSigned=*/ false, /*IsReplace=*/ false);
12362   SDValue FIST = Vals.first, StackSlot = Vals.second;
12363   assert(FIST.getNode() && "Unexpected failure");
12364
12365   if (StackSlot.getNode())
12366     // Load the result.
12367     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12368                        FIST, StackSlot, MachinePointerInfo(),
12369                        false, false, false, 0);
12370
12371   // The node is the result.
12372   return FIST;
12373 }
12374
12375 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12376   SDLoc DL(Op);
12377   MVT VT = Op.getSimpleValueType();
12378   SDValue In = Op.getOperand(0);
12379   MVT SVT = In.getSimpleValueType();
12380
12381   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12382
12383   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12384                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12385                                  In, DAG.getUNDEF(SVT)));
12386 }
12387
12388 /// The only differences between FABS and FNEG are the mask and the logic op.
12389 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12390 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12391   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12392          "Wrong opcode for lowering FABS or FNEG.");
12393
12394   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12395
12396   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12397   // into an FNABS. We'll lower the FABS after that if it is still in use.
12398   if (IsFABS)
12399     for (SDNode *User : Op->uses())
12400       if (User->getOpcode() == ISD::FNEG)
12401         return Op;
12402
12403   SDValue Op0 = Op.getOperand(0);
12404   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12405
12406   SDLoc dl(Op);
12407   MVT VT = Op.getSimpleValueType();
12408   // Assume scalar op for initialization; update for vector if needed.
12409   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12410   // generate a 16-byte vector constant and logic op even for the scalar case.
12411   // Using a 16-byte mask allows folding the load of the mask with
12412   // the logic op, so it can save (~4 bytes) on code size.
12413   MVT EltVT = VT;
12414   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12415   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12416   // decide if we should generate a 16-byte constant mask when we only need 4 or
12417   // 8 bytes for the scalar case.
12418   if (VT.isVector()) {
12419     EltVT = VT.getVectorElementType();
12420     NumElts = VT.getVectorNumElements();
12421   }
12422
12423   unsigned EltBits = EltVT.getSizeInBits();
12424   LLVMContext *Context = DAG.getContext();
12425   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12426   APInt MaskElt =
12427     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12428   Constant *C = ConstantInt::get(*Context, MaskElt);
12429   C = ConstantVector::getSplat(NumElts, C);
12430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12431   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12432   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12433   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12434                              MachinePointerInfo::getConstantPool(),
12435                              false, false, false, Alignment);
12436
12437   if (VT.isVector()) {
12438     // For a vector, cast operands to a vector type, perform the logic op,
12439     // and cast the result back to the original value type.
12440     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12441     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12442     SDValue Operand = IsFNABS ?
12443       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12444       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12445     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12446     return DAG.getNode(ISD::BITCAST, dl, VT,
12447                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12448   }
12449
12450   // If not vector, then scalar.
12451   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12452   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12453   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12454 }
12455
12456 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12458   LLVMContext *Context = DAG.getContext();
12459   SDValue Op0 = Op.getOperand(0);
12460   SDValue Op1 = Op.getOperand(1);
12461   SDLoc dl(Op);
12462   MVT VT = Op.getSimpleValueType();
12463   MVT SrcVT = Op1.getSimpleValueType();
12464
12465   // If second operand is smaller, extend it first.
12466   if (SrcVT.bitsLT(VT)) {
12467     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12468     SrcVT = VT;
12469   }
12470   // And if it is bigger, shrink it first.
12471   if (SrcVT.bitsGT(VT)) {
12472     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12473     SrcVT = VT;
12474   }
12475
12476   // At this point the operands and the result should have the same
12477   // type, and that won't be f80 since that is not custom lowered.
12478
12479   const fltSemantics &Sem =
12480       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12481   const unsigned SizeInBits = VT.getSizeInBits();
12482
12483   SmallVector<Constant *, 4> CV(
12484       VT == MVT::f64 ? 2 : 4,
12485       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12486
12487   // First, clear all bits but the sign bit from the second operand (sign).
12488   CV[0] = ConstantFP::get(*Context,
12489                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12490   Constant *C = ConstantVector::get(CV);
12491   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12492   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12493                               MachinePointerInfo::getConstantPool(),
12494                               false, false, false, 16);
12495   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12496
12497   // Next, clear the sign bit from the first operand (magnitude).
12498   // If it's a constant, we can clear it here.
12499   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12500     APFloat APF = Op0CN->getValueAPF();
12501     // If the magnitude is a positive zero, the sign bit alone is enough.
12502     if (APF.isPosZero())
12503       return SignBit;
12504     APF.clearSign();
12505     CV[0] = ConstantFP::get(*Context, APF);
12506   } else {
12507     CV[0] = ConstantFP::get(
12508         *Context,
12509         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12510   }
12511   C = ConstantVector::get(CV);
12512   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12513   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12514                             MachinePointerInfo::getConstantPool(),
12515                             false, false, false, 16);
12516   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12517   if (!isa<ConstantFPSDNode>(Op0))
12518     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12519
12520   // OR the magnitude value with the sign bit.
12521   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12522 }
12523
12524 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12525   SDValue N0 = Op.getOperand(0);
12526   SDLoc dl(Op);
12527   MVT VT = Op.getSimpleValueType();
12528
12529   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12530   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12531                                   DAG.getConstant(1, dl, VT));
12532   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12533 }
12534
12535 // Check whether an OR'd tree is PTEST-able.
12536 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12537                                       SelectionDAG &DAG) {
12538   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12539
12540   if (!Subtarget->hasSSE41())
12541     return SDValue();
12542
12543   if (!Op->hasOneUse())
12544     return SDValue();
12545
12546   SDNode *N = Op.getNode();
12547   SDLoc DL(N);
12548
12549   SmallVector<SDValue, 8> Opnds;
12550   DenseMap<SDValue, unsigned> VecInMap;
12551   SmallVector<SDValue, 8> VecIns;
12552   EVT VT = MVT::Other;
12553
12554   // Recognize a special case where a vector is casted into wide integer to
12555   // test all 0s.
12556   Opnds.push_back(N->getOperand(0));
12557   Opnds.push_back(N->getOperand(1));
12558
12559   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12560     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12561     // BFS traverse all OR'd operands.
12562     if (I->getOpcode() == ISD::OR) {
12563       Opnds.push_back(I->getOperand(0));
12564       Opnds.push_back(I->getOperand(1));
12565       // Re-evaluate the number of nodes to be traversed.
12566       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12567       continue;
12568     }
12569
12570     // Quit if a non-EXTRACT_VECTOR_ELT
12571     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12572       return SDValue();
12573
12574     // Quit if without a constant index.
12575     SDValue Idx = I->getOperand(1);
12576     if (!isa<ConstantSDNode>(Idx))
12577       return SDValue();
12578
12579     SDValue ExtractedFromVec = I->getOperand(0);
12580     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12581     if (M == VecInMap.end()) {
12582       VT = ExtractedFromVec.getValueType();
12583       // Quit if not 128/256-bit vector.
12584       if (!VT.is128BitVector() && !VT.is256BitVector())
12585         return SDValue();
12586       // Quit if not the same type.
12587       if (VecInMap.begin() != VecInMap.end() &&
12588           VT != VecInMap.begin()->first.getValueType())
12589         return SDValue();
12590       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12591       VecIns.push_back(ExtractedFromVec);
12592     }
12593     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12594   }
12595
12596   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12597          "Not extracted from 128-/256-bit vector.");
12598
12599   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12600
12601   for (DenseMap<SDValue, unsigned>::const_iterator
12602         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12603     // Quit if not all elements are used.
12604     if (I->second != FullMask)
12605       return SDValue();
12606   }
12607
12608   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12609
12610   // Cast all vectors into TestVT for PTEST.
12611   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12612     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12613
12614   // If more than one full vectors are evaluated, OR them first before PTEST.
12615   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12616     // Each iteration will OR 2 nodes and append the result until there is only
12617     // 1 node left, i.e. the final OR'd value of all vectors.
12618     SDValue LHS = VecIns[Slot];
12619     SDValue RHS = VecIns[Slot + 1];
12620     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12621   }
12622
12623   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12624                      VecIns.back(), VecIns.back());
12625 }
12626
12627 /// \brief return true if \c Op has a use that doesn't just read flags.
12628 static bool hasNonFlagsUse(SDValue Op) {
12629   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12630        ++UI) {
12631     SDNode *User = *UI;
12632     unsigned UOpNo = UI.getOperandNo();
12633     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12634       // Look pass truncate.
12635       UOpNo = User->use_begin().getOperandNo();
12636       User = *User->use_begin();
12637     }
12638
12639     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12640         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12641       return true;
12642   }
12643   return false;
12644 }
12645
12646 /// Emit nodes that will be selected as "test Op0,Op0", or something
12647 /// equivalent.
12648 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12649                                     SelectionDAG &DAG) const {
12650   if (Op.getValueType() == MVT::i1) {
12651     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12652     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12653                        DAG.getConstant(0, dl, MVT::i8));
12654   }
12655   // CF and OF aren't always set the way we want. Determine which
12656   // of these we need.
12657   bool NeedCF = false;
12658   bool NeedOF = false;
12659   switch (X86CC) {
12660   default: break;
12661   case X86::COND_A: case X86::COND_AE:
12662   case X86::COND_B: case X86::COND_BE:
12663     NeedCF = true;
12664     break;
12665   case X86::COND_G: case X86::COND_GE:
12666   case X86::COND_L: case X86::COND_LE:
12667   case X86::COND_O: case X86::COND_NO: {
12668     // Check if we really need to set the
12669     // Overflow flag. If NoSignedWrap is present
12670     // that is not actually needed.
12671     switch (Op->getOpcode()) {
12672     case ISD::ADD:
12673     case ISD::SUB:
12674     case ISD::MUL:
12675     case ISD::SHL: {
12676       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12677       if (BinNode->Flags.hasNoSignedWrap())
12678         break;
12679     }
12680     default:
12681       NeedOF = true;
12682       break;
12683     }
12684     break;
12685   }
12686   }
12687   // See if we can use the EFLAGS value from the operand instead of
12688   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12689   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12690   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12691     // Emit a CMP with 0, which is the TEST pattern.
12692     //if (Op.getValueType() == MVT::i1)
12693     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12694     //                     DAG.getConstant(0, MVT::i1));
12695     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12696                        DAG.getConstant(0, dl, Op.getValueType()));
12697   }
12698   unsigned Opcode = 0;
12699   unsigned NumOperands = 0;
12700
12701   // Truncate operations may prevent the merge of the SETCC instruction
12702   // and the arithmetic instruction before it. Attempt to truncate the operands
12703   // of the arithmetic instruction and use a reduced bit-width instruction.
12704   bool NeedTruncation = false;
12705   SDValue ArithOp = Op;
12706   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12707     SDValue Arith = Op->getOperand(0);
12708     // Both the trunc and the arithmetic op need to have one user each.
12709     if (Arith->hasOneUse())
12710       switch (Arith.getOpcode()) {
12711         default: break;
12712         case ISD::ADD:
12713         case ISD::SUB:
12714         case ISD::AND:
12715         case ISD::OR:
12716         case ISD::XOR: {
12717           NeedTruncation = true;
12718           ArithOp = Arith;
12719         }
12720       }
12721   }
12722
12723   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12724   // which may be the result of a CAST.  We use the variable 'Op', which is the
12725   // non-casted variable when we check for possible users.
12726   switch (ArithOp.getOpcode()) {
12727   case ISD::ADD:
12728     // Due to an isel shortcoming, be conservative if this add is likely to be
12729     // selected as part of a load-modify-store instruction. When the root node
12730     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12731     // uses of other nodes in the match, such as the ADD in this case. This
12732     // leads to the ADD being left around and reselected, with the result being
12733     // two adds in the output.  Alas, even if none our users are stores, that
12734     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12735     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12736     // climbing the DAG back to the root, and it doesn't seem to be worth the
12737     // effort.
12738     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12739          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12740       if (UI->getOpcode() != ISD::CopyToReg &&
12741           UI->getOpcode() != ISD::SETCC &&
12742           UI->getOpcode() != ISD::STORE)
12743         goto default_case;
12744
12745     if (ConstantSDNode *C =
12746         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12747       // An add of one will be selected as an INC.
12748       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12749         Opcode = X86ISD::INC;
12750         NumOperands = 1;
12751         break;
12752       }
12753
12754       // An add of negative one (subtract of one) will be selected as a DEC.
12755       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12756         Opcode = X86ISD::DEC;
12757         NumOperands = 1;
12758         break;
12759       }
12760     }
12761
12762     // Otherwise use a regular EFLAGS-setting add.
12763     Opcode = X86ISD::ADD;
12764     NumOperands = 2;
12765     break;
12766   case ISD::SHL:
12767   case ISD::SRL:
12768     // If we have a constant logical shift that's only used in a comparison
12769     // against zero turn it into an equivalent AND. This allows turning it into
12770     // a TEST instruction later.
12771     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12772         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12773       EVT VT = Op.getValueType();
12774       unsigned BitWidth = VT.getSizeInBits();
12775       unsigned ShAmt = Op->getConstantOperandVal(1);
12776       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12777         break;
12778       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12779                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12780                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12781       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12782         break;
12783       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12784                                 DAG.getConstant(Mask, dl, VT));
12785       DAG.ReplaceAllUsesWith(Op, New);
12786       Op = New;
12787     }
12788     break;
12789
12790   case ISD::AND:
12791     // If the primary and result isn't used, don't bother using X86ISD::AND,
12792     // because a TEST instruction will be better.
12793     if (!hasNonFlagsUse(Op))
12794       break;
12795     // FALL THROUGH
12796   case ISD::SUB:
12797   case ISD::OR:
12798   case ISD::XOR:
12799     // Due to the ISEL shortcoming noted above, be conservative if this op is
12800     // likely to be selected as part of a load-modify-store instruction.
12801     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12802            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12803       if (UI->getOpcode() == ISD::STORE)
12804         goto default_case;
12805
12806     // Otherwise use a regular EFLAGS-setting instruction.
12807     switch (ArithOp.getOpcode()) {
12808     default: llvm_unreachable("unexpected operator!");
12809     case ISD::SUB: Opcode = X86ISD::SUB; break;
12810     case ISD::XOR: Opcode = X86ISD::XOR; break;
12811     case ISD::AND: Opcode = X86ISD::AND; break;
12812     case ISD::OR: {
12813       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12814         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12815         if (EFLAGS.getNode())
12816           return EFLAGS;
12817       }
12818       Opcode = X86ISD::OR;
12819       break;
12820     }
12821     }
12822
12823     NumOperands = 2;
12824     break;
12825   case X86ISD::ADD:
12826   case X86ISD::SUB:
12827   case X86ISD::INC:
12828   case X86ISD::DEC:
12829   case X86ISD::OR:
12830   case X86ISD::XOR:
12831   case X86ISD::AND:
12832     return SDValue(Op.getNode(), 1);
12833   default:
12834   default_case:
12835     break;
12836   }
12837
12838   // If we found that truncation is beneficial, perform the truncation and
12839   // update 'Op'.
12840   if (NeedTruncation) {
12841     EVT VT = Op.getValueType();
12842     SDValue WideVal = Op->getOperand(0);
12843     EVT WideVT = WideVal.getValueType();
12844     unsigned ConvertedOp = 0;
12845     // Use a target machine opcode to prevent further DAGCombine
12846     // optimizations that may separate the arithmetic operations
12847     // from the setcc node.
12848     switch (WideVal.getOpcode()) {
12849       default: break;
12850       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12851       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12852       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12853       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12854       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12855     }
12856
12857     if (ConvertedOp) {
12858       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12859       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12860         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12861         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12862         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12863       }
12864     }
12865   }
12866
12867   if (Opcode == 0)
12868     // Emit a CMP with 0, which is the TEST pattern.
12869     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12870                        DAG.getConstant(0, dl, Op.getValueType()));
12871
12872   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12873   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12874
12875   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12876   DAG.ReplaceAllUsesWith(Op, New);
12877   return SDValue(New.getNode(), 1);
12878 }
12879
12880 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12881 /// equivalent.
12882 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12883                                    SDLoc dl, SelectionDAG &DAG) const {
12884   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12885     if (C->getAPIntValue() == 0)
12886       return EmitTest(Op0, X86CC, dl, DAG);
12887
12888      if (Op0.getValueType() == MVT::i1)
12889        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12890   }
12891
12892   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12893        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12894     // Do the comparison at i32 if it's smaller, besides the Atom case.
12895     // This avoids subregister aliasing issues. Keep the smaller reference
12896     // if we're optimizing for size, however, as that'll allow better folding
12897     // of memory operations.
12898     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12899         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12900             Attribute::MinSize) &&
12901         !Subtarget->isAtom()) {
12902       unsigned ExtendOp =
12903           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12904       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12905       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12906     }
12907     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12908     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12909     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12910                               Op0, Op1);
12911     return SDValue(Sub.getNode(), 1);
12912   }
12913   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12914 }
12915
12916 /// Convert a comparison if required by the subtarget.
12917 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12918                                                  SelectionDAG &DAG) const {
12919   // If the subtarget does not support the FUCOMI instruction, floating-point
12920   // comparisons have to be converted.
12921   if (Subtarget->hasCMov() ||
12922       Cmp.getOpcode() != X86ISD::CMP ||
12923       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12924       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12925     return Cmp;
12926
12927   // The instruction selector will select an FUCOM instruction instead of
12928   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12929   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12930   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12931   SDLoc dl(Cmp);
12932   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12933   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12934   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12935                             DAG.getConstant(8, dl, MVT::i8));
12936   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12937   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12938 }
12939
12940 /// The minimum architected relative accuracy is 2^-12. We need one
12941 /// Newton-Raphson step to have a good float result (24 bits of precision).
12942 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12943                                             DAGCombinerInfo &DCI,
12944                                             unsigned &RefinementSteps,
12945                                             bool &UseOneConstNR) const {
12946   // FIXME: We should use instruction latency models to calculate the cost of
12947   // each potential sequence, but this is very hard to do reliably because
12948   // at least Intel's Core* chips have variable timing based on the number of
12949   // significant digits in the divisor and/or sqrt operand.
12950   if (!Subtarget->useSqrtEst())
12951     return SDValue();
12952
12953   EVT VT = Op.getValueType();
12954
12955   // SSE1 has rsqrtss and rsqrtps.
12956   // TODO: Add support for AVX512 (v16f32).
12957   // It is likely not profitable to do this for f64 because a double-precision
12958   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12959   // instructions: convert to single, rsqrtss, convert back to double, refine
12960   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12961   // along with FMA, this could be a throughput win.
12962   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12963       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12964     RefinementSteps = 1;
12965     UseOneConstNR = false;
12966     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12967   }
12968   return SDValue();
12969 }
12970
12971 /// The minimum architected relative accuracy is 2^-12. We need one
12972 /// Newton-Raphson step to have a good float result (24 bits of precision).
12973 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12974                                             DAGCombinerInfo &DCI,
12975                                             unsigned &RefinementSteps) const {
12976   // FIXME: We should use instruction latency models to calculate the cost of
12977   // each potential sequence, but this is very hard to do reliably because
12978   // at least Intel's Core* chips have variable timing based on the number of
12979   // significant digits in the divisor.
12980   if (!Subtarget->useReciprocalEst())
12981     return SDValue();
12982
12983   EVT VT = Op.getValueType();
12984
12985   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12986   // TODO: Add support for AVX512 (v16f32).
12987   // It is likely not profitable to do this for f64 because a double-precision
12988   // reciprocal estimate with refinement on x86 prior to FMA requires
12989   // 15 instructions: convert to single, rcpss, convert back to double, refine
12990   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12991   // along with FMA, this could be a throughput win.
12992   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12993       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12994     RefinementSteps = ReciprocalEstimateRefinementSteps;
12995     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12996   }
12997   return SDValue();
12998 }
12999
13000 /// If we have at least two divisions that use the same divisor, convert to
13001 /// multplication by a reciprocal. This may need to be adjusted for a given
13002 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13003 /// This is because we still need one division to calculate the reciprocal and
13004 /// then we need two multiplies by that reciprocal as replacements for the
13005 /// original divisions.
13006 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13007   return NumUsers > 1;
13008 }
13009
13010 static bool isAllOnes(SDValue V) {
13011   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13012   return C && C->isAllOnesValue();
13013 }
13014
13015 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13016 /// if it's possible.
13017 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13018                                      SDLoc dl, SelectionDAG &DAG) const {
13019   SDValue Op0 = And.getOperand(0);
13020   SDValue Op1 = And.getOperand(1);
13021   if (Op0.getOpcode() == ISD::TRUNCATE)
13022     Op0 = Op0.getOperand(0);
13023   if (Op1.getOpcode() == ISD::TRUNCATE)
13024     Op1 = Op1.getOperand(0);
13025
13026   SDValue LHS, RHS;
13027   if (Op1.getOpcode() == ISD::SHL)
13028     std::swap(Op0, Op1);
13029   if (Op0.getOpcode() == ISD::SHL) {
13030     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13031       if (And00C->getZExtValue() == 1) {
13032         // If we looked past a truncate, check that it's only truncating away
13033         // known zeros.
13034         unsigned BitWidth = Op0.getValueSizeInBits();
13035         unsigned AndBitWidth = And.getValueSizeInBits();
13036         if (BitWidth > AndBitWidth) {
13037           APInt Zeros, Ones;
13038           DAG.computeKnownBits(Op0, Zeros, Ones);
13039           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13040             return SDValue();
13041         }
13042         LHS = Op1;
13043         RHS = Op0.getOperand(1);
13044       }
13045   } else if (Op1.getOpcode() == ISD::Constant) {
13046     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13047     uint64_t AndRHSVal = AndRHS->getZExtValue();
13048     SDValue AndLHS = Op0;
13049
13050     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13051       LHS = AndLHS.getOperand(0);
13052       RHS = AndLHS.getOperand(1);
13053     }
13054
13055     // Use BT if the immediate can't be encoded in a TEST instruction.
13056     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13057       LHS = AndLHS;
13058       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13059     }
13060   }
13061
13062   if (LHS.getNode()) {
13063     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13064     // instruction.  Since the shift amount is in-range-or-undefined, we know
13065     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13066     // the encoding for the i16 version is larger than the i32 version.
13067     // Also promote i16 to i32 for performance / code size reason.
13068     if (LHS.getValueType() == MVT::i8 ||
13069         LHS.getValueType() == MVT::i16)
13070       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13071
13072     // If the operand types disagree, extend the shift amount to match.  Since
13073     // BT ignores high bits (like shifts) we can use anyextend.
13074     if (LHS.getValueType() != RHS.getValueType())
13075       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13076
13077     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13078     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13079     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13080                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13081   }
13082
13083   return SDValue();
13084 }
13085
13086 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13087 /// mask CMPs.
13088 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13089                               SDValue &Op1) {
13090   unsigned SSECC;
13091   bool Swap = false;
13092
13093   // SSE Condition code mapping:
13094   //  0 - EQ
13095   //  1 - LT
13096   //  2 - LE
13097   //  3 - UNORD
13098   //  4 - NEQ
13099   //  5 - NLT
13100   //  6 - NLE
13101   //  7 - ORD
13102   switch (SetCCOpcode) {
13103   default: llvm_unreachable("Unexpected SETCC condition");
13104   case ISD::SETOEQ:
13105   case ISD::SETEQ:  SSECC = 0; break;
13106   case ISD::SETOGT:
13107   case ISD::SETGT:  Swap = true; // Fallthrough
13108   case ISD::SETLT:
13109   case ISD::SETOLT: SSECC = 1; break;
13110   case ISD::SETOGE:
13111   case ISD::SETGE:  Swap = true; // Fallthrough
13112   case ISD::SETLE:
13113   case ISD::SETOLE: SSECC = 2; break;
13114   case ISD::SETUO:  SSECC = 3; break;
13115   case ISD::SETUNE:
13116   case ISD::SETNE:  SSECC = 4; break;
13117   case ISD::SETULE: Swap = true; // Fallthrough
13118   case ISD::SETUGE: SSECC = 5; break;
13119   case ISD::SETULT: Swap = true; // Fallthrough
13120   case ISD::SETUGT: SSECC = 6; break;
13121   case ISD::SETO:   SSECC = 7; break;
13122   case ISD::SETUEQ:
13123   case ISD::SETONE: SSECC = 8; break;
13124   }
13125   if (Swap)
13126     std::swap(Op0, Op1);
13127
13128   return SSECC;
13129 }
13130
13131 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13132 // ones, and then concatenate the result back.
13133 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13134   MVT VT = Op.getSimpleValueType();
13135
13136   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13137          "Unsupported value type for operation");
13138
13139   unsigned NumElems = VT.getVectorNumElements();
13140   SDLoc dl(Op);
13141   SDValue CC = Op.getOperand(2);
13142
13143   // Extract the LHS vectors
13144   SDValue LHS = Op.getOperand(0);
13145   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13146   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13147
13148   // Extract the RHS vectors
13149   SDValue RHS = Op.getOperand(1);
13150   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13151   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13152
13153   // Issue the operation on the smaller types and concatenate the result back
13154   MVT EltVT = VT.getVectorElementType();
13155   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13156   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13157                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13158                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13159 }
13160
13161 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13162   SDValue Op0 = Op.getOperand(0);
13163   SDValue Op1 = Op.getOperand(1);
13164   SDValue CC = Op.getOperand(2);
13165   MVT VT = Op.getSimpleValueType();
13166   SDLoc dl(Op);
13167
13168   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13169          "Unexpected type for boolean compare operation");
13170   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13171   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13172                                DAG.getConstant(-1, dl, VT));
13173   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13174                                DAG.getConstant(-1, dl, VT));
13175   switch (SetCCOpcode) {
13176   default: llvm_unreachable("Unexpected SETCC condition");
13177   case ISD::SETNE:
13178     // (x != y) -> ~(x ^ y)
13179     return DAG.getNode(ISD::XOR, dl, VT,
13180                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13181                        DAG.getConstant(-1, dl, VT));
13182   case ISD::SETEQ:
13183     // (x == y) -> (x ^ y)
13184     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13185   case ISD::SETUGT:
13186   case ISD::SETGT:
13187     // (x > y) -> (x & ~y)
13188     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13189   case ISD::SETULT:
13190   case ISD::SETLT:
13191     // (x < y) -> (~x & y)
13192     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13193   case ISD::SETULE:
13194   case ISD::SETLE:
13195     // (x <= y) -> (~x | y)
13196     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13197   case ISD::SETUGE:
13198   case ISD::SETGE:
13199     // (x >=y) -> (x | ~y)
13200     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13201   }
13202 }
13203
13204 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13205                                      const X86Subtarget *Subtarget) {
13206   SDValue Op0 = Op.getOperand(0);
13207   SDValue Op1 = Op.getOperand(1);
13208   SDValue CC = Op.getOperand(2);
13209   MVT VT = Op.getSimpleValueType();
13210   SDLoc dl(Op);
13211
13212   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13213          Op.getValueType().getScalarType() == MVT::i1 &&
13214          "Cannot set masked compare for this operation");
13215
13216   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13217   unsigned  Opc = 0;
13218   bool Unsigned = false;
13219   bool Swap = false;
13220   unsigned SSECC;
13221   switch (SetCCOpcode) {
13222   default: llvm_unreachable("Unexpected SETCC condition");
13223   case ISD::SETNE:  SSECC = 4; break;
13224   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13225   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13226   case ISD::SETLT:  Swap = true; //fall-through
13227   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13228   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13229   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13230   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13231   case ISD::SETULE: Unsigned = true; //fall-through
13232   case ISD::SETLE:  SSECC = 2; break;
13233   }
13234
13235   if (Swap)
13236     std::swap(Op0, Op1);
13237   if (Opc)
13238     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13239   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13240   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13241                      DAG.getConstant(SSECC, dl, MVT::i8));
13242 }
13243
13244 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13245 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13246 /// return an empty value.
13247 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13248 {
13249   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13250   if (!BV)
13251     return SDValue();
13252
13253   MVT VT = Op1.getSimpleValueType();
13254   MVT EVT = VT.getVectorElementType();
13255   unsigned n = VT.getVectorNumElements();
13256   SmallVector<SDValue, 8> ULTOp1;
13257
13258   for (unsigned i = 0; i < n; ++i) {
13259     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13260     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13261       return SDValue();
13262
13263     // Avoid underflow.
13264     APInt Val = Elt->getAPIntValue();
13265     if (Val == 0)
13266       return SDValue();
13267
13268     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13269   }
13270
13271   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13272 }
13273
13274 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13275                            SelectionDAG &DAG) {
13276   SDValue Op0 = Op.getOperand(0);
13277   SDValue Op1 = Op.getOperand(1);
13278   SDValue CC = Op.getOperand(2);
13279   MVT VT = Op.getSimpleValueType();
13280   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13281   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13282   SDLoc dl(Op);
13283
13284   if (isFP) {
13285 #ifndef NDEBUG
13286     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13287     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13288 #endif
13289
13290     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13291     unsigned Opc = X86ISD::CMPP;
13292     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13293       assert(VT.getVectorNumElements() <= 16);
13294       Opc = X86ISD::CMPM;
13295     }
13296     // In the two special cases we can't handle, emit two comparisons.
13297     if (SSECC == 8) {
13298       unsigned CC0, CC1;
13299       unsigned CombineOpc;
13300       if (SetCCOpcode == ISD::SETUEQ) {
13301         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13302       } else {
13303         assert(SetCCOpcode == ISD::SETONE);
13304         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13305       }
13306
13307       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13308                                  DAG.getConstant(CC0, dl, MVT::i8));
13309       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13310                                  DAG.getConstant(CC1, dl, MVT::i8));
13311       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13312     }
13313     // Handle all other FP comparisons here.
13314     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13315                        DAG.getConstant(SSECC, dl, MVT::i8));
13316   }
13317
13318   // Break 256-bit integer vector compare into smaller ones.
13319   if (VT.is256BitVector() && !Subtarget->hasInt256())
13320     return Lower256IntVSETCC(Op, DAG);
13321
13322   EVT OpVT = Op1.getValueType();
13323   if (OpVT.getVectorElementType() == MVT::i1)
13324     return LowerBoolVSETCC_AVX512(Op, DAG);
13325
13326   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13327   if (Subtarget->hasAVX512()) {
13328     if (Op1.getValueType().is512BitVector() ||
13329         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13330         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13331       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13332
13333     // In AVX-512 architecture setcc returns mask with i1 elements,
13334     // But there is no compare instruction for i8 and i16 elements in KNL.
13335     // We are not talking about 512-bit operands in this case, these
13336     // types are illegal.
13337     if (MaskResult &&
13338         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13339          OpVT.getVectorElementType().getSizeInBits() >= 8))
13340       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13341                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13342   }
13343
13344   // We are handling one of the integer comparisons here.  Since SSE only has
13345   // GT and EQ comparisons for integer, swapping operands and multiple
13346   // operations may be required for some comparisons.
13347   unsigned Opc;
13348   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13349   bool Subus = false;
13350
13351   switch (SetCCOpcode) {
13352   default: llvm_unreachable("Unexpected SETCC condition");
13353   case ISD::SETNE:  Invert = true;
13354   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13355   case ISD::SETLT:  Swap = true;
13356   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13357   case ISD::SETGE:  Swap = true;
13358   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13359                     Invert = true; break;
13360   case ISD::SETULT: Swap = true;
13361   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13362                     FlipSigns = true; break;
13363   case ISD::SETUGE: Swap = true;
13364   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13365                     FlipSigns = true; Invert = true; break;
13366   }
13367
13368   // Special case: Use min/max operations for SETULE/SETUGE
13369   MVT VET = VT.getVectorElementType();
13370   bool hasMinMax =
13371        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13372     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13373
13374   if (hasMinMax) {
13375     switch (SetCCOpcode) {
13376     default: break;
13377     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13378     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13379     }
13380
13381     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13382   }
13383
13384   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13385   if (!MinMax && hasSubus) {
13386     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13387     // Op0 u<= Op1:
13388     //   t = psubus Op0, Op1
13389     //   pcmpeq t, <0..0>
13390     switch (SetCCOpcode) {
13391     default: break;
13392     case ISD::SETULT: {
13393       // If the comparison is against a constant we can turn this into a
13394       // setule.  With psubus, setule does not require a swap.  This is
13395       // beneficial because the constant in the register is no longer
13396       // destructed as the destination so it can be hoisted out of a loop.
13397       // Only do this pre-AVX since vpcmp* is no longer destructive.
13398       if (Subtarget->hasAVX())
13399         break;
13400       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13401       if (ULEOp1.getNode()) {
13402         Op1 = ULEOp1;
13403         Subus = true; Invert = false; Swap = false;
13404       }
13405       break;
13406     }
13407     // Psubus is better than flip-sign because it requires no inversion.
13408     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13409     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13410     }
13411
13412     if (Subus) {
13413       Opc = X86ISD::SUBUS;
13414       FlipSigns = false;
13415     }
13416   }
13417
13418   if (Swap)
13419     std::swap(Op0, Op1);
13420
13421   // Check that the operation in question is available (most are plain SSE2,
13422   // but PCMPGTQ and PCMPEQQ have different requirements).
13423   if (VT == MVT::v2i64) {
13424     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13425       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13426
13427       // First cast everything to the right type.
13428       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13429       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13430
13431       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13432       // bits of the inputs before performing those operations. The lower
13433       // compare is always unsigned.
13434       SDValue SB;
13435       if (FlipSigns) {
13436         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13437       } else {
13438         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13439         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13440         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13441                          Sign, Zero, Sign, Zero);
13442       }
13443       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13444       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13445
13446       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13447       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13448       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13449
13450       // Create masks for only the low parts/high parts of the 64 bit integers.
13451       static const int MaskHi[] = { 1, 1, 3, 3 };
13452       static const int MaskLo[] = { 0, 0, 2, 2 };
13453       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13454       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13455       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13456
13457       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13458       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13459
13460       if (Invert)
13461         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13462
13463       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13464     }
13465
13466     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13467       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13468       // pcmpeqd + pshufd + pand.
13469       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13470
13471       // First cast everything to the right type.
13472       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13473       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13474
13475       // Do the compare.
13476       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13477
13478       // Make sure the lower and upper halves are both all-ones.
13479       static const int Mask[] = { 1, 0, 3, 2 };
13480       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13481       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13482
13483       if (Invert)
13484         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13485
13486       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13487     }
13488   }
13489
13490   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13491   // bits of the inputs before performing those operations.
13492   if (FlipSigns) {
13493     EVT EltVT = VT.getVectorElementType();
13494     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13495                                  VT);
13496     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13497     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13498   }
13499
13500   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13501
13502   // If the logical-not of the result is required, perform that now.
13503   if (Invert)
13504     Result = DAG.getNOT(dl, Result, VT);
13505
13506   if (MinMax)
13507     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13508
13509   if (Subus)
13510     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13511                          getZeroVector(VT, Subtarget, DAG, dl));
13512
13513   return Result;
13514 }
13515
13516 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13517
13518   MVT VT = Op.getSimpleValueType();
13519
13520   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13521
13522   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13523          && "SetCC type must be 8-bit or 1-bit integer");
13524   SDValue Op0 = Op.getOperand(0);
13525   SDValue Op1 = Op.getOperand(1);
13526   SDLoc dl(Op);
13527   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13528
13529   // Optimize to BT if possible.
13530   // Lower (X & (1 << N)) == 0 to BT(X, N).
13531   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13532   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13533   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13534       Op1.getOpcode() == ISD::Constant &&
13535       cast<ConstantSDNode>(Op1)->isNullValue() &&
13536       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13537     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13538     if (NewSetCC.getNode()) {
13539       if (VT == MVT::i1)
13540         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13541       return NewSetCC;
13542     }
13543   }
13544
13545   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13546   // these.
13547   if (Op1.getOpcode() == ISD::Constant &&
13548       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13549        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13550       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13551
13552     // If the input is a setcc, then reuse the input setcc or use a new one with
13553     // the inverted condition.
13554     if (Op0.getOpcode() == X86ISD::SETCC) {
13555       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13556       bool Invert = (CC == ISD::SETNE) ^
13557         cast<ConstantSDNode>(Op1)->isNullValue();
13558       if (!Invert)
13559         return Op0;
13560
13561       CCode = X86::GetOppositeBranchCondition(CCode);
13562       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13563                                   DAG.getConstant(CCode, dl, MVT::i8),
13564                                   Op0.getOperand(1));
13565       if (VT == MVT::i1)
13566         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13567       return SetCC;
13568     }
13569   }
13570   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13571       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13572       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13573
13574     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13575     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13576   }
13577
13578   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13579   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13580   if (X86CC == X86::COND_INVALID)
13581     return SDValue();
13582
13583   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13584   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13585   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13586                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13587   if (VT == MVT::i1)
13588     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13589   return SetCC;
13590 }
13591
13592 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13593 static bool isX86LogicalCmp(SDValue Op) {
13594   unsigned Opc = Op.getNode()->getOpcode();
13595   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13596       Opc == X86ISD::SAHF)
13597     return true;
13598   if (Op.getResNo() == 1 &&
13599       (Opc == X86ISD::ADD ||
13600        Opc == X86ISD::SUB ||
13601        Opc == X86ISD::ADC ||
13602        Opc == X86ISD::SBB ||
13603        Opc == X86ISD::SMUL ||
13604        Opc == X86ISD::UMUL ||
13605        Opc == X86ISD::INC ||
13606        Opc == X86ISD::DEC ||
13607        Opc == X86ISD::OR ||
13608        Opc == X86ISD::XOR ||
13609        Opc == X86ISD::AND))
13610     return true;
13611
13612   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13613     return true;
13614
13615   return false;
13616 }
13617
13618 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13619   if (V.getOpcode() != ISD::TRUNCATE)
13620     return false;
13621
13622   SDValue VOp0 = V.getOperand(0);
13623   unsigned InBits = VOp0.getValueSizeInBits();
13624   unsigned Bits = V.getValueSizeInBits();
13625   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13626 }
13627
13628 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13629   bool addTest = true;
13630   SDValue Cond  = Op.getOperand(0);
13631   SDValue Op1 = Op.getOperand(1);
13632   SDValue Op2 = Op.getOperand(2);
13633   SDLoc DL(Op);
13634   EVT VT = Op1.getValueType();
13635   SDValue CC;
13636
13637   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13638   // are available or VBLENDV if AVX is available.
13639   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13640   if (Cond.getOpcode() == ISD::SETCC &&
13641       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13642        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13643       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13644     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13645     int SSECC = translateX86FSETCC(
13646         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13647
13648     if (SSECC != 8) {
13649       if (Subtarget->hasAVX512()) {
13650         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13651                                   DAG.getConstant(SSECC, DL, MVT::i8));
13652         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13653       }
13654
13655       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13656                                 DAG.getConstant(SSECC, DL, MVT::i8));
13657
13658       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13659       // of 3 logic instructions for size savings and potentially speed.
13660       // Unfortunately, there is no scalar form of VBLENDV.
13661
13662       // If either operand is a constant, don't try this. We can expect to
13663       // optimize away at least one of the logic instructions later in that
13664       // case, so that sequence would be faster than a variable blend.
13665
13666       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13667       // uses XMM0 as the selection register. That may need just as many
13668       // instructions as the AND/ANDN/OR sequence due to register moves, so
13669       // don't bother.
13670
13671       if (Subtarget->hasAVX() &&
13672           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13673
13674         // Convert to vectors, do a VSELECT, and convert back to scalar.
13675         // All of the conversions should be optimized away.
13676
13677         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13678         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13679         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13680         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13681
13682         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13683         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13684
13685         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13686
13687         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13688                            VSel, DAG.getIntPtrConstant(0, DL));
13689       }
13690       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13691       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13692       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13693     }
13694   }
13695
13696     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13697       SDValue Op1Scalar;
13698       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13699         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13700       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13701         Op1Scalar = Op1.getOperand(0);
13702       SDValue Op2Scalar;
13703       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13704         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13705       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13706         Op2Scalar = Op2.getOperand(0);
13707       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13708         SDValue newSelect = DAG.getNode(ISD::SELECT, DL, 
13709                                         Op1Scalar.getValueType(),
13710                                         Cond, Op1Scalar, Op2Scalar);
13711         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13712           return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13713         SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13714         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13715                            DAG.getIntPtrConstant(0, DL));
13716     }
13717   }
13718
13719   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13720     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13721     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13722                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13723     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13724                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13725     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13726                                     Cond, Op1, Op2);
13727     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13728   }
13729
13730   if (Cond.getOpcode() == ISD::SETCC) {
13731     SDValue NewCond = LowerSETCC(Cond, DAG);
13732     if (NewCond.getNode())
13733       Cond = NewCond;
13734   }
13735
13736   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13737   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13738   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13739   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13740   if (Cond.getOpcode() == X86ISD::SETCC &&
13741       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13742       isZero(Cond.getOperand(1).getOperand(1))) {
13743     SDValue Cmp = Cond.getOperand(1);
13744
13745     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13746
13747     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13748         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13749       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13750
13751       SDValue CmpOp0 = Cmp.getOperand(0);
13752       // Apply further optimizations for special cases
13753       // (select (x != 0), -1, 0) -> neg & sbb
13754       // (select (x == 0), 0, -1) -> neg & sbb
13755       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13756         if (YC->isNullValue() &&
13757             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13758           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13759           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13760                                     DAG.getConstant(0, DL,
13761                                                     CmpOp0.getValueType()),
13762                                     CmpOp0);
13763           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13764                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13765                                     SDValue(Neg.getNode(), 1));
13766           return Res;
13767         }
13768
13769       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13770                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13771       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13772
13773       SDValue Res =   // Res = 0 or -1.
13774         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13775                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13776
13777       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13778         Res = DAG.getNOT(DL, Res, Res.getValueType());
13779
13780       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13781       if (!N2C || !N2C->isNullValue())
13782         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13783       return Res;
13784     }
13785   }
13786
13787   // Look past (and (setcc_carry (cmp ...)), 1).
13788   if (Cond.getOpcode() == ISD::AND &&
13789       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13790     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13791     if (C && C->getAPIntValue() == 1)
13792       Cond = Cond.getOperand(0);
13793   }
13794
13795   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13796   // setting operand in place of the X86ISD::SETCC.
13797   unsigned CondOpcode = Cond.getOpcode();
13798   if (CondOpcode == X86ISD::SETCC ||
13799       CondOpcode == X86ISD::SETCC_CARRY) {
13800     CC = Cond.getOperand(0);
13801
13802     SDValue Cmp = Cond.getOperand(1);
13803     unsigned Opc = Cmp.getOpcode();
13804     MVT VT = Op.getSimpleValueType();
13805
13806     bool IllegalFPCMov = false;
13807     if (VT.isFloatingPoint() && !VT.isVector() &&
13808         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13809       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13810
13811     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13812         Opc == X86ISD::BT) { // FIXME
13813       Cond = Cmp;
13814       addTest = false;
13815     }
13816   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13817              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13818              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13819               Cond.getOperand(0).getValueType() != MVT::i8)) {
13820     SDValue LHS = Cond.getOperand(0);
13821     SDValue RHS = Cond.getOperand(1);
13822     unsigned X86Opcode;
13823     unsigned X86Cond;
13824     SDVTList VTs;
13825     switch (CondOpcode) {
13826     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13827     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13828     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13829     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13830     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13831     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13832     default: llvm_unreachable("unexpected overflowing operator");
13833     }
13834     if (CondOpcode == ISD::UMULO)
13835       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13836                           MVT::i32);
13837     else
13838       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13839
13840     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13841
13842     if (CondOpcode == ISD::UMULO)
13843       Cond = X86Op.getValue(2);
13844     else
13845       Cond = X86Op.getValue(1);
13846
13847     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13848     addTest = false;
13849   }
13850
13851   if (addTest) {
13852     // Look pass the truncate if the high bits are known zero.
13853     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13854         Cond = Cond.getOperand(0);
13855
13856     // We know the result of AND is compared against zero. Try to match
13857     // it to BT.
13858     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13859       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13860       if (NewSetCC.getNode()) {
13861         CC = NewSetCC.getOperand(0);
13862         Cond = NewSetCC.getOperand(1);
13863         addTest = false;
13864       }
13865     }
13866   }
13867
13868   if (addTest) {
13869     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13870     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13871   }
13872
13873   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13874   // a <  b ?  0 : -1 -> RES = setcc_carry
13875   // a >= b ? -1 :  0 -> RES = setcc_carry
13876   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13877   if (Cond.getOpcode() == X86ISD::SUB) {
13878     Cond = ConvertCmpIfNecessary(Cond, DAG);
13879     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13880
13881     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13882         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13883       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13884                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13885                                 Cond);
13886       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13887         return DAG.getNOT(DL, Res, Res.getValueType());
13888       return Res;
13889     }
13890   }
13891
13892   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13893   // widen the cmov and push the truncate through. This avoids introducing a new
13894   // branch during isel and doesn't add any extensions.
13895   if (Op.getValueType() == MVT::i8 &&
13896       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13897     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13898     if (T1.getValueType() == T2.getValueType() &&
13899         // Blacklist CopyFromReg to avoid partial register stalls.
13900         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13901       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13902       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13903       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13904     }
13905   }
13906
13907   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13908   // condition is true.
13909   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13910   SDValue Ops[] = { Op2, Op1, CC, Cond };
13911   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13912 }
13913
13914 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
13915                                        const X86Subtarget *Subtarget,
13916                                        SelectionDAG &DAG) {
13917   MVT VT = Op->getSimpleValueType(0);
13918   SDValue In = Op->getOperand(0);
13919   MVT InVT = In.getSimpleValueType();
13920   MVT VTElt = VT.getVectorElementType();
13921   MVT InVTElt = InVT.getVectorElementType();
13922   SDLoc dl(Op);
13923
13924   // SKX processor
13925   if ((InVTElt == MVT::i1) &&
13926       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13927         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13928
13929        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13930         VTElt.getSizeInBits() <= 16)) ||
13931
13932        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13933         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13934
13935        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13936         VTElt.getSizeInBits() >= 32))))
13937     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13938
13939   unsigned int NumElts = VT.getVectorNumElements();
13940
13941   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13942     return SDValue();
13943
13944   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13945     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13946       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13947     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13948   }
13949
13950   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13951   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13952   SDValue NegOne =
13953    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13954                    ExtVT);
13955   SDValue Zero =
13956    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13957
13958   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13959   if (VT.is512BitVector())
13960     return V;
13961   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13962 }
13963
13964 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
13965                                              const X86Subtarget *Subtarget,
13966                                              SelectionDAG &DAG) {
13967   SDValue In = Op->getOperand(0);
13968   MVT VT = Op->getSimpleValueType(0);
13969   MVT InVT = In.getSimpleValueType();
13970   assert(VT.getSizeInBits() == InVT.getSizeInBits());
13971
13972   MVT InSVT = InVT.getScalarType();
13973   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
13974
13975   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13976     return SDValue();
13977   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
13978     return SDValue();
13979
13980   SDLoc dl(Op);
13981
13982   // SSE41 targets can use the pmovsx* instructions directly.
13983   if (Subtarget->hasSSE41())
13984     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13985
13986   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
13987   SDValue Curr = In;
13988   MVT CurrVT = InVT;
13989
13990   // As SRAI is only available on i16/i32 types, we expand only up to i32
13991   // and handle i64 separately.
13992   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
13993     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
13994     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
13995     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
13996     Curr = DAG.getNode(ISD::BITCAST, dl, CurrVT, Curr);
13997   }
13998
13999   SDValue SignExt = Curr;
14000   if (CurrVT != InVT) {
14001     unsigned SignExtShift =
14002         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14003     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14004                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14005   }
14006
14007   if (CurrVT == VT)
14008     return SignExt;
14009
14010   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14011     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14012                                DAG.getConstant(31, dl, MVT::i8));
14013     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14014     return DAG.getNode(ISD::BITCAST, dl, VT, Ext);
14015   }
14016
14017   return SDValue();
14018 }
14019
14020 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14021                                 SelectionDAG &DAG) {
14022   MVT VT = Op->getSimpleValueType(0);
14023   SDValue In = Op->getOperand(0);
14024   MVT InVT = In.getSimpleValueType();
14025   SDLoc dl(Op);
14026
14027   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14028     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14029
14030   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14031       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14032       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14033     return SDValue();
14034
14035   if (Subtarget->hasInt256())
14036     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14037
14038   // Optimize vectors in AVX mode
14039   // Sign extend  v8i16 to v8i32 and
14040   //              v4i32 to v4i64
14041   //
14042   // Divide input vector into two parts
14043   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14044   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14045   // concat the vectors to original VT
14046
14047   unsigned NumElems = InVT.getVectorNumElements();
14048   SDValue Undef = DAG.getUNDEF(InVT);
14049
14050   SmallVector<int,8> ShufMask1(NumElems, -1);
14051   for (unsigned i = 0; i != NumElems/2; ++i)
14052     ShufMask1[i] = i;
14053
14054   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14055
14056   SmallVector<int,8> ShufMask2(NumElems, -1);
14057   for (unsigned i = 0; i != NumElems/2; ++i)
14058     ShufMask2[i] = i + NumElems/2;
14059
14060   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14061
14062   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14063                                 VT.getVectorNumElements()/2);
14064
14065   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14066   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14067
14068   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14069 }
14070
14071 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14072 // may emit an illegal shuffle but the expansion is still better than scalar
14073 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14074 // we'll emit a shuffle and a arithmetic shift.
14075 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14076 // TODO: It is possible to support ZExt by zeroing the undef values during
14077 // the shuffle phase or after the shuffle.
14078 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14079                                  SelectionDAG &DAG) {
14080   MVT RegVT = Op.getSimpleValueType();
14081   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14082   assert(RegVT.isInteger() &&
14083          "We only custom lower integer vector sext loads.");
14084
14085   // Nothing useful we can do without SSE2 shuffles.
14086   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14087
14088   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14089   SDLoc dl(Ld);
14090   EVT MemVT = Ld->getMemoryVT();
14091   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14092   unsigned RegSz = RegVT.getSizeInBits();
14093
14094   ISD::LoadExtType Ext = Ld->getExtensionType();
14095
14096   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14097          && "Only anyext and sext are currently implemented.");
14098   assert(MemVT != RegVT && "Cannot extend to the same type");
14099   assert(MemVT.isVector() && "Must load a vector from memory");
14100
14101   unsigned NumElems = RegVT.getVectorNumElements();
14102   unsigned MemSz = MemVT.getSizeInBits();
14103   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14104
14105   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14106     // The only way in which we have a legal 256-bit vector result but not the
14107     // integer 256-bit operations needed to directly lower a sextload is if we
14108     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14109     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14110     // correctly legalized. We do this late to allow the canonical form of
14111     // sextload to persist throughout the rest of the DAG combiner -- it wants
14112     // to fold together any extensions it can, and so will fuse a sign_extend
14113     // of an sextload into a sextload targeting a wider value.
14114     SDValue Load;
14115     if (MemSz == 128) {
14116       // Just switch this to a normal load.
14117       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14118                                        "it must be a legal 128-bit vector "
14119                                        "type!");
14120       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14121                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14122                   Ld->isInvariant(), Ld->getAlignment());
14123     } else {
14124       assert(MemSz < 128 &&
14125              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14126       // Do an sext load to a 128-bit vector type. We want to use the same
14127       // number of elements, but elements half as wide. This will end up being
14128       // recursively lowered by this routine, but will succeed as we definitely
14129       // have all the necessary features if we're using AVX1.
14130       EVT HalfEltVT =
14131           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14132       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14133       Load =
14134           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14135                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14136                          Ld->isNonTemporal(), Ld->isInvariant(),
14137                          Ld->getAlignment());
14138     }
14139
14140     // Replace chain users with the new chain.
14141     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14142     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14143
14144     // Finally, do a normal sign-extend to the desired register.
14145     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14146   }
14147
14148   // All sizes must be a power of two.
14149   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14150          "Non-power-of-two elements are not custom lowered!");
14151
14152   // Attempt to load the original value using scalar loads.
14153   // Find the largest scalar type that divides the total loaded size.
14154   MVT SclrLoadTy = MVT::i8;
14155   for (MVT Tp : MVT::integer_valuetypes()) {
14156     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14157       SclrLoadTy = Tp;
14158     }
14159   }
14160
14161   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14162   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14163       (64 <= MemSz))
14164     SclrLoadTy = MVT::f64;
14165
14166   // Calculate the number of scalar loads that we need to perform
14167   // in order to load our vector from memory.
14168   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14169
14170   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14171          "Can only lower sext loads with a single scalar load!");
14172
14173   unsigned loadRegZize = RegSz;
14174   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14175     loadRegZize = 128;
14176
14177   // Represent our vector as a sequence of elements which are the
14178   // largest scalar that we can load.
14179   EVT LoadUnitVecVT = EVT::getVectorVT(
14180       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14181
14182   // Represent the data using the same element type that is stored in
14183   // memory. In practice, we ''widen'' MemVT.
14184   EVT WideVecVT =
14185       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14186                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14187
14188   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14189          "Invalid vector type");
14190
14191   // We can't shuffle using an illegal type.
14192   assert(TLI.isTypeLegal(WideVecVT) &&
14193          "We only lower types that form legal widened vector types");
14194
14195   SmallVector<SDValue, 8> Chains;
14196   SDValue Ptr = Ld->getBasePtr();
14197   SDValue Increment =
14198       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14199   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14200
14201   for (unsigned i = 0; i < NumLoads; ++i) {
14202     // Perform a single load.
14203     SDValue ScalarLoad =
14204         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14205                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14206                     Ld->getAlignment());
14207     Chains.push_back(ScalarLoad.getValue(1));
14208     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14209     // another round of DAGCombining.
14210     if (i == 0)
14211       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14212     else
14213       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14214                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14215
14216     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14217   }
14218
14219   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14220
14221   // Bitcast the loaded value to a vector of the original element type, in
14222   // the size of the target vector type.
14223   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14224   unsigned SizeRatio = RegSz / MemSz;
14225
14226   if (Ext == ISD::SEXTLOAD) {
14227     // If we have SSE4.1, we can directly emit a VSEXT node.
14228     if (Subtarget->hasSSE41()) {
14229       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14230       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14231       return Sext;
14232     }
14233
14234     // Otherwise we'll shuffle the small elements in the high bits of the
14235     // larger type and perform an arithmetic shift. If the shift is not legal
14236     // it's better to scalarize.
14237     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14238            "We can't implement a sext load without an arithmetic right shift!");
14239
14240     // Redistribute the loaded elements into the different locations.
14241     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14242     for (unsigned i = 0; i != NumElems; ++i)
14243       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14244
14245     SDValue Shuff = DAG.getVectorShuffle(
14246         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14247
14248     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14249
14250     // Build the arithmetic shift.
14251     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14252                    MemVT.getVectorElementType().getSizeInBits();
14253     Shuff =
14254         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14255                     DAG.getConstant(Amt, dl, RegVT));
14256
14257     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14258     return Shuff;
14259   }
14260
14261   // Redistribute the loaded elements into the different locations.
14262   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14263   for (unsigned i = 0; i != NumElems; ++i)
14264     ShuffleVec[i * SizeRatio] = i;
14265
14266   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14267                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14268
14269   // Bitcast to the requested type.
14270   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14271   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14272   return Shuff;
14273 }
14274
14275 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14276 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14277 // from the AND / OR.
14278 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14279   Opc = Op.getOpcode();
14280   if (Opc != ISD::OR && Opc != ISD::AND)
14281     return false;
14282   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14283           Op.getOperand(0).hasOneUse() &&
14284           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14285           Op.getOperand(1).hasOneUse());
14286 }
14287
14288 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14289 // 1 and that the SETCC node has a single use.
14290 static bool isXor1OfSetCC(SDValue Op) {
14291   if (Op.getOpcode() != ISD::XOR)
14292     return false;
14293   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14294   if (N1C && N1C->getAPIntValue() == 1) {
14295     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14296       Op.getOperand(0).hasOneUse();
14297   }
14298   return false;
14299 }
14300
14301 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14302   bool addTest = true;
14303   SDValue Chain = Op.getOperand(0);
14304   SDValue Cond  = Op.getOperand(1);
14305   SDValue Dest  = Op.getOperand(2);
14306   SDLoc dl(Op);
14307   SDValue CC;
14308   bool Inverted = false;
14309
14310   if (Cond.getOpcode() == ISD::SETCC) {
14311     // Check for setcc([su]{add,sub,mul}o == 0).
14312     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14313         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14314         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14315         Cond.getOperand(0).getResNo() == 1 &&
14316         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14317          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14318          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14319          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14320          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14321          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14322       Inverted = true;
14323       Cond = Cond.getOperand(0);
14324     } else {
14325       SDValue NewCond = LowerSETCC(Cond, DAG);
14326       if (NewCond.getNode())
14327         Cond = NewCond;
14328     }
14329   }
14330 #if 0
14331   // FIXME: LowerXALUO doesn't handle these!!
14332   else if (Cond.getOpcode() == X86ISD::ADD  ||
14333            Cond.getOpcode() == X86ISD::SUB  ||
14334            Cond.getOpcode() == X86ISD::SMUL ||
14335            Cond.getOpcode() == X86ISD::UMUL)
14336     Cond = LowerXALUO(Cond, DAG);
14337 #endif
14338
14339   // Look pass (and (setcc_carry (cmp ...)), 1).
14340   if (Cond.getOpcode() == ISD::AND &&
14341       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14342     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14343     if (C && C->getAPIntValue() == 1)
14344       Cond = Cond.getOperand(0);
14345   }
14346
14347   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14348   // setting operand in place of the X86ISD::SETCC.
14349   unsigned CondOpcode = Cond.getOpcode();
14350   if (CondOpcode == X86ISD::SETCC ||
14351       CondOpcode == X86ISD::SETCC_CARRY) {
14352     CC = Cond.getOperand(0);
14353
14354     SDValue Cmp = Cond.getOperand(1);
14355     unsigned Opc = Cmp.getOpcode();
14356     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14357     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14358       Cond = Cmp;
14359       addTest = false;
14360     } else {
14361       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14362       default: break;
14363       case X86::COND_O:
14364       case X86::COND_B:
14365         // These can only come from an arithmetic instruction with overflow,
14366         // e.g. SADDO, UADDO.
14367         Cond = Cond.getNode()->getOperand(1);
14368         addTest = false;
14369         break;
14370       }
14371     }
14372   }
14373   CondOpcode = Cond.getOpcode();
14374   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14375       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14376       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14377        Cond.getOperand(0).getValueType() != MVT::i8)) {
14378     SDValue LHS = Cond.getOperand(0);
14379     SDValue RHS = Cond.getOperand(1);
14380     unsigned X86Opcode;
14381     unsigned X86Cond;
14382     SDVTList VTs;
14383     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14384     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14385     // X86ISD::INC).
14386     switch (CondOpcode) {
14387     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14388     case ISD::SADDO:
14389       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14390         if (C->isOne()) {
14391           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14392           break;
14393         }
14394       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14395     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14396     case ISD::SSUBO:
14397       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14398         if (C->isOne()) {
14399           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14400           break;
14401         }
14402       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14403     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14404     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14405     default: llvm_unreachable("unexpected overflowing operator");
14406     }
14407     if (Inverted)
14408       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14409     if (CondOpcode == ISD::UMULO)
14410       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14411                           MVT::i32);
14412     else
14413       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14414
14415     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14416
14417     if (CondOpcode == ISD::UMULO)
14418       Cond = X86Op.getValue(2);
14419     else
14420       Cond = X86Op.getValue(1);
14421
14422     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14423     addTest = false;
14424   } else {
14425     unsigned CondOpc;
14426     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14427       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14428       if (CondOpc == ISD::OR) {
14429         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14430         // two branches instead of an explicit OR instruction with a
14431         // separate test.
14432         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14433             isX86LogicalCmp(Cmp)) {
14434           CC = Cond.getOperand(0).getOperand(0);
14435           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14436                               Chain, Dest, CC, Cmp);
14437           CC = Cond.getOperand(1).getOperand(0);
14438           Cond = Cmp;
14439           addTest = false;
14440         }
14441       } else { // ISD::AND
14442         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14443         // two branches instead of an explicit AND instruction with a
14444         // separate test. However, we only do this if this block doesn't
14445         // have a fall-through edge, because this requires an explicit
14446         // jmp when the condition is false.
14447         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14448             isX86LogicalCmp(Cmp) &&
14449             Op.getNode()->hasOneUse()) {
14450           X86::CondCode CCode =
14451             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14452           CCode = X86::GetOppositeBranchCondition(CCode);
14453           CC = DAG.getConstant(CCode, dl, MVT::i8);
14454           SDNode *User = *Op.getNode()->use_begin();
14455           // Look for an unconditional branch following this conditional branch.
14456           // We need this because we need to reverse the successors in order
14457           // to implement FCMP_OEQ.
14458           if (User->getOpcode() == ISD::BR) {
14459             SDValue FalseBB = User->getOperand(1);
14460             SDNode *NewBR =
14461               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14462             assert(NewBR == User);
14463             (void)NewBR;
14464             Dest = FalseBB;
14465
14466             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14467                                 Chain, Dest, CC, Cmp);
14468             X86::CondCode CCode =
14469               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14470             CCode = X86::GetOppositeBranchCondition(CCode);
14471             CC = DAG.getConstant(CCode, dl, MVT::i8);
14472             Cond = Cmp;
14473             addTest = false;
14474           }
14475         }
14476       }
14477     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14478       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14479       // It should be transformed during dag combiner except when the condition
14480       // is set by a arithmetics with overflow node.
14481       X86::CondCode CCode =
14482         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14483       CCode = X86::GetOppositeBranchCondition(CCode);
14484       CC = DAG.getConstant(CCode, dl, MVT::i8);
14485       Cond = Cond.getOperand(0).getOperand(1);
14486       addTest = false;
14487     } else if (Cond.getOpcode() == ISD::SETCC &&
14488                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14489       // For FCMP_OEQ, we can emit
14490       // two branches instead of an explicit AND instruction with a
14491       // separate test. However, we only do this if this block doesn't
14492       // have a fall-through edge, because this requires an explicit
14493       // jmp when the condition is false.
14494       if (Op.getNode()->hasOneUse()) {
14495         SDNode *User = *Op.getNode()->use_begin();
14496         // Look for an unconditional branch following this conditional branch.
14497         // We need this because we need to reverse the successors in order
14498         // to implement FCMP_OEQ.
14499         if (User->getOpcode() == ISD::BR) {
14500           SDValue FalseBB = User->getOperand(1);
14501           SDNode *NewBR =
14502             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14503           assert(NewBR == User);
14504           (void)NewBR;
14505           Dest = FalseBB;
14506
14507           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14508                                     Cond.getOperand(0), Cond.getOperand(1));
14509           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14510           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14511           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14512                               Chain, Dest, CC, Cmp);
14513           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14514           Cond = Cmp;
14515           addTest = false;
14516         }
14517       }
14518     } else if (Cond.getOpcode() == ISD::SETCC &&
14519                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14520       // For FCMP_UNE, we can emit
14521       // two branches instead of an explicit AND instruction with a
14522       // separate test. However, we only do this if this block doesn't
14523       // have a fall-through edge, because this requires an explicit
14524       // jmp when the condition is false.
14525       if (Op.getNode()->hasOneUse()) {
14526         SDNode *User = *Op.getNode()->use_begin();
14527         // Look for an unconditional branch following this conditional branch.
14528         // We need this because we need to reverse the successors in order
14529         // to implement FCMP_UNE.
14530         if (User->getOpcode() == ISD::BR) {
14531           SDValue FalseBB = User->getOperand(1);
14532           SDNode *NewBR =
14533             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14534           assert(NewBR == User);
14535           (void)NewBR;
14536
14537           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14538                                     Cond.getOperand(0), Cond.getOperand(1));
14539           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14540           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14541           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14542                               Chain, Dest, CC, Cmp);
14543           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14544           Cond = Cmp;
14545           addTest = false;
14546           Dest = FalseBB;
14547         }
14548       }
14549     }
14550   }
14551
14552   if (addTest) {
14553     // Look pass the truncate if the high bits are known zero.
14554     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14555         Cond = Cond.getOperand(0);
14556
14557     // We know the result of AND is compared against zero. Try to match
14558     // it to BT.
14559     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14560       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14561       if (NewSetCC.getNode()) {
14562         CC = NewSetCC.getOperand(0);
14563         Cond = NewSetCC.getOperand(1);
14564         addTest = false;
14565       }
14566     }
14567   }
14568
14569   if (addTest) {
14570     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14571     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14572     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14573   }
14574   Cond = ConvertCmpIfNecessary(Cond, DAG);
14575   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14576                      Chain, Dest, CC, Cond);
14577 }
14578
14579 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14580 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14581 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14582 // that the guard pages used by the OS virtual memory manager are allocated in
14583 // correct sequence.
14584 SDValue
14585 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14586                                            SelectionDAG &DAG) const {
14587   MachineFunction &MF = DAG.getMachineFunction();
14588   bool SplitStack = MF.shouldSplitStack();
14589   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14590                SplitStack;
14591   SDLoc dl(Op);
14592
14593   if (!Lower) {
14594     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14595     SDNode* Node = Op.getNode();
14596
14597     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14598     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14599         " not tell us which reg is the stack pointer!");
14600     EVT VT = Node->getValueType(0);
14601     SDValue Tmp1 = SDValue(Node, 0);
14602     SDValue Tmp2 = SDValue(Node, 1);
14603     SDValue Tmp3 = Node->getOperand(2);
14604     SDValue Chain = Tmp1.getOperand(0);
14605
14606     // Chain the dynamic stack allocation so that it doesn't modify the stack
14607     // pointer when other instructions are using the stack.
14608     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14609         SDLoc(Node));
14610
14611     SDValue Size = Tmp2.getOperand(1);
14612     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14613     Chain = SP.getValue(1);
14614     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14615     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14616     unsigned StackAlign = TFI.getStackAlignment();
14617     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14618     if (Align > StackAlign)
14619       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14620           DAG.getConstant(-(uint64_t)Align, dl, VT));
14621     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14622
14623     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14624         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14625         SDLoc(Node));
14626
14627     SDValue Ops[2] = { Tmp1, Tmp2 };
14628     return DAG.getMergeValues(Ops, dl);
14629   }
14630
14631   // Get the inputs.
14632   SDValue Chain = Op.getOperand(0);
14633   SDValue Size  = Op.getOperand(1);
14634   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14635   EVT VT = Op.getNode()->getValueType(0);
14636
14637   bool Is64Bit = Subtarget->is64Bit();
14638   EVT SPTy = getPointerTy();
14639
14640   if (SplitStack) {
14641     MachineRegisterInfo &MRI = MF.getRegInfo();
14642
14643     if (Is64Bit) {
14644       // The 64 bit implementation of segmented stacks needs to clobber both r10
14645       // r11. This makes it impossible to use it along with nested parameters.
14646       const Function *F = MF.getFunction();
14647
14648       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14649            I != E; ++I)
14650         if (I->hasNestAttr())
14651           report_fatal_error("Cannot use segmented stacks with functions that "
14652                              "have nested arguments.");
14653     }
14654
14655     const TargetRegisterClass *AddrRegClass =
14656       getRegClassFor(getPointerTy());
14657     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14658     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14659     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14660                                 DAG.getRegister(Vreg, SPTy));
14661     SDValue Ops1[2] = { Value, Chain };
14662     return DAG.getMergeValues(Ops1, dl);
14663   } else {
14664     SDValue Flag;
14665     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14666
14667     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14668     Flag = Chain.getValue(1);
14669     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14670
14671     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14672
14673     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14674     unsigned SPReg = RegInfo->getStackRegister();
14675     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14676     Chain = SP.getValue(1);
14677
14678     if (Align) {
14679       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14680                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14681       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14682     }
14683
14684     SDValue Ops1[2] = { SP, Chain };
14685     return DAG.getMergeValues(Ops1, dl);
14686   }
14687 }
14688
14689 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14690   MachineFunction &MF = DAG.getMachineFunction();
14691   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14692
14693   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14694   SDLoc DL(Op);
14695
14696   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14697     // vastart just stores the address of the VarArgsFrameIndex slot into the
14698     // memory location argument.
14699     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14700                                    getPointerTy());
14701     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14702                         MachinePointerInfo(SV), false, false, 0);
14703   }
14704
14705   // __va_list_tag:
14706   //   gp_offset         (0 - 6 * 8)
14707   //   fp_offset         (48 - 48 + 8 * 16)
14708   //   overflow_arg_area (point to parameters coming in memory).
14709   //   reg_save_area
14710   SmallVector<SDValue, 8> MemOps;
14711   SDValue FIN = Op.getOperand(1);
14712   // Store gp_offset
14713   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14714                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14715                                                DL, MVT::i32),
14716                                FIN, MachinePointerInfo(SV), false, false, 0);
14717   MemOps.push_back(Store);
14718
14719   // Store fp_offset
14720   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14721                     FIN, DAG.getIntPtrConstant(4, DL));
14722   Store = DAG.getStore(Op.getOperand(0), DL,
14723                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14724                                        MVT::i32),
14725                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14726   MemOps.push_back(Store);
14727
14728   // Store ptr to overflow_arg_area
14729   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14730                     FIN, DAG.getIntPtrConstant(4, DL));
14731   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14732                                     getPointerTy());
14733   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14734                        MachinePointerInfo(SV, 8),
14735                        false, false, 0);
14736   MemOps.push_back(Store);
14737
14738   // Store ptr to reg_save_area.
14739   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14740                     FIN, DAG.getIntPtrConstant(8, DL));
14741   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14742                                     getPointerTy());
14743   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14744                        MachinePointerInfo(SV, 16), false, false, 0);
14745   MemOps.push_back(Store);
14746   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14747 }
14748
14749 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14750   assert(Subtarget->is64Bit() &&
14751          "LowerVAARG only handles 64-bit va_arg!");
14752   assert((Subtarget->isTargetLinux() ||
14753           Subtarget->isTargetDarwin()) &&
14754           "Unhandled target in LowerVAARG");
14755   assert(Op.getNode()->getNumOperands() == 4);
14756   SDValue Chain = Op.getOperand(0);
14757   SDValue SrcPtr = Op.getOperand(1);
14758   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14759   unsigned Align = Op.getConstantOperandVal(3);
14760   SDLoc dl(Op);
14761
14762   EVT ArgVT = Op.getNode()->getValueType(0);
14763   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14764   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14765   uint8_t ArgMode;
14766
14767   // Decide which area this value should be read from.
14768   // TODO: Implement the AMD64 ABI in its entirety. This simple
14769   // selection mechanism works only for the basic types.
14770   if (ArgVT == MVT::f80) {
14771     llvm_unreachable("va_arg for f80 not yet implemented");
14772   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14773     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14774   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14775     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14776   } else {
14777     llvm_unreachable("Unhandled argument type in LowerVAARG");
14778   }
14779
14780   if (ArgMode == 2) {
14781     // Sanity Check: Make sure using fp_offset makes sense.
14782     assert(!Subtarget->useSoftFloat() &&
14783            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14784                Attribute::NoImplicitFloat)) &&
14785            Subtarget->hasSSE1());
14786   }
14787
14788   // Insert VAARG_64 node into the DAG
14789   // VAARG_64 returns two values: Variable Argument Address, Chain
14790   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14791                        DAG.getConstant(ArgMode, dl, MVT::i8),
14792                        DAG.getConstant(Align, dl, MVT::i32)};
14793   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14794   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14795                                           VTs, InstOps, MVT::i64,
14796                                           MachinePointerInfo(SV),
14797                                           /*Align=*/0,
14798                                           /*Volatile=*/false,
14799                                           /*ReadMem=*/true,
14800                                           /*WriteMem=*/true);
14801   Chain = VAARG.getValue(1);
14802
14803   // Load the next argument and return it
14804   return DAG.getLoad(ArgVT, dl,
14805                      Chain,
14806                      VAARG,
14807                      MachinePointerInfo(),
14808                      false, false, false, 0);
14809 }
14810
14811 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14812                            SelectionDAG &DAG) {
14813   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14814   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14815   SDValue Chain = Op.getOperand(0);
14816   SDValue DstPtr = Op.getOperand(1);
14817   SDValue SrcPtr = Op.getOperand(2);
14818   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14819   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14820   SDLoc DL(Op);
14821
14822   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14823                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14824                        false, false,
14825                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14826 }
14827
14828 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14829 // amount is a constant. Takes immediate version of shift as input.
14830 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14831                                           SDValue SrcOp, uint64_t ShiftAmt,
14832                                           SelectionDAG &DAG) {
14833   MVT ElementType = VT.getVectorElementType();
14834
14835   // Fold this packed shift into its first operand if ShiftAmt is 0.
14836   if (ShiftAmt == 0)
14837     return SrcOp;
14838
14839   // Check for ShiftAmt >= element width
14840   if (ShiftAmt >= ElementType.getSizeInBits()) {
14841     if (Opc == X86ISD::VSRAI)
14842       ShiftAmt = ElementType.getSizeInBits() - 1;
14843     else
14844       return DAG.getConstant(0, dl, VT);
14845   }
14846
14847   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14848          && "Unknown target vector shift-by-constant node");
14849
14850   // Fold this packed vector shift into a build vector if SrcOp is a
14851   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14852   if (VT == SrcOp.getSimpleValueType() &&
14853       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14854     SmallVector<SDValue, 8> Elts;
14855     unsigned NumElts = SrcOp->getNumOperands();
14856     ConstantSDNode *ND;
14857
14858     switch(Opc) {
14859     default: llvm_unreachable(nullptr);
14860     case X86ISD::VSHLI:
14861       for (unsigned i=0; i!=NumElts; ++i) {
14862         SDValue CurrentOp = SrcOp->getOperand(i);
14863         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14864           Elts.push_back(CurrentOp);
14865           continue;
14866         }
14867         ND = cast<ConstantSDNode>(CurrentOp);
14868         const APInt &C = ND->getAPIntValue();
14869         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14870       }
14871       break;
14872     case X86ISD::VSRLI:
14873       for (unsigned i=0; i!=NumElts; ++i) {
14874         SDValue CurrentOp = SrcOp->getOperand(i);
14875         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14876           Elts.push_back(CurrentOp);
14877           continue;
14878         }
14879         ND = cast<ConstantSDNode>(CurrentOp);
14880         const APInt &C = ND->getAPIntValue();
14881         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14882       }
14883       break;
14884     case X86ISD::VSRAI:
14885       for (unsigned i=0; i!=NumElts; ++i) {
14886         SDValue CurrentOp = SrcOp->getOperand(i);
14887         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14888           Elts.push_back(CurrentOp);
14889           continue;
14890         }
14891         ND = cast<ConstantSDNode>(CurrentOp);
14892         const APInt &C = ND->getAPIntValue();
14893         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14894       }
14895       break;
14896     }
14897
14898     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14899   }
14900
14901   return DAG.getNode(Opc, dl, VT, SrcOp,
14902                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14903 }
14904
14905 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14906 // may or may not be a constant. Takes immediate version of shift as input.
14907 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14908                                    SDValue SrcOp, SDValue ShAmt,
14909                                    SelectionDAG &DAG) {
14910   MVT SVT = ShAmt.getSimpleValueType();
14911   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14912
14913   // Catch shift-by-constant.
14914   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14915     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14916                                       CShAmt->getZExtValue(), DAG);
14917
14918   // Change opcode to non-immediate version
14919   switch (Opc) {
14920     default: llvm_unreachable("Unknown target vector shift node");
14921     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14922     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14923     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14924   }
14925
14926   const X86Subtarget &Subtarget =
14927       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14928   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14929       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14930     // Let the shuffle legalizer expand this shift amount node.
14931     SDValue Op0 = ShAmt.getOperand(0);
14932     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14933     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14934   } else {
14935     // Need to build a vector containing shift amount.
14936     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14937     SmallVector<SDValue, 4> ShOps;
14938     ShOps.push_back(ShAmt);
14939     if (SVT == MVT::i32) {
14940       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14941       ShOps.push_back(DAG.getUNDEF(SVT));
14942     }
14943     ShOps.push_back(DAG.getUNDEF(SVT));
14944
14945     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14946     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14947   }
14948
14949   // The return type has to be a 128-bit type with the same element
14950   // type as the input type.
14951   MVT EltVT = VT.getVectorElementType();
14952   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14953
14954   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14955   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14956 }
14957
14958 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14959 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14960 /// necessary casting for \p Mask when lowering masking intrinsics.
14961 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14962                                     SDValue PreservedSrc,
14963                                     const X86Subtarget *Subtarget,
14964                                     SelectionDAG &DAG) {
14965     EVT VT = Op.getValueType();
14966     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14967                                   MVT::i1, VT.getVectorNumElements());
14968     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14969                                      Mask.getValueType().getSizeInBits());
14970     SDLoc dl(Op);
14971
14972     assert(MaskVT.isSimple() && "invalid mask type");
14973
14974     if (isAllOnes(Mask))
14975       return Op;
14976
14977     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14978     // are extracted by EXTRACT_SUBVECTOR.
14979     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14980                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14981                               DAG.getIntPtrConstant(0, dl));
14982
14983     switch (Op.getOpcode()) {
14984       default: break;
14985       case X86ISD::PCMPEQM:
14986       case X86ISD::PCMPGTM:
14987       case X86ISD::CMPM:
14988       case X86ISD::CMPMU:
14989         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14990     }
14991     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14992       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14993     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14994 }
14995
14996 /// \brief Creates an SDNode for a predicated scalar operation.
14997 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14998 /// The mask is comming as MVT::i8 and it should be truncated
14999 /// to MVT::i1 while lowering masking intrinsics.
15000 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15001 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15002 /// a scalar instruction.
15003 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15004                                     SDValue PreservedSrc,
15005                                     const X86Subtarget *Subtarget,
15006                                     SelectionDAG &DAG) {
15007     if (isAllOnes(Mask))
15008       return Op;
15009
15010     EVT VT = Op.getValueType();
15011     SDLoc dl(Op);
15012     // The mask should be of type MVT::i1
15013     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15014
15015     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15016       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15017     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15018 }
15019
15020 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15021                                        SelectionDAG &DAG) {
15022   SDLoc dl(Op);
15023   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15024   EVT VT = Op.getValueType();
15025   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15026   if (IntrData) {
15027     switch(IntrData->Type) {
15028     case INTR_TYPE_1OP:
15029       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15030     case INTR_TYPE_2OP:
15031       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15032         Op.getOperand(2));
15033     case INTR_TYPE_3OP:
15034       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15035         Op.getOperand(2), Op.getOperand(3));
15036     case INTR_TYPE_1OP_MASK_RM: {
15037       SDValue Src = Op.getOperand(1);
15038       SDValue Src0 = Op.getOperand(2);
15039       SDValue Mask = Op.getOperand(3);
15040       SDValue RoundingMode = Op.getOperand(4);
15041       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15042                                               RoundingMode),
15043                                   Mask, Src0, Subtarget, DAG);
15044     }
15045     case INTR_TYPE_SCALAR_MASK_RM: {
15046       SDValue Src1 = Op.getOperand(1);
15047       SDValue Src2 = Op.getOperand(2);
15048       SDValue Src0 = Op.getOperand(3);
15049       SDValue Mask = Op.getOperand(4);
15050       // There are 2 kinds of intrinsics in this group:
15051       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15052       // (2) With rounding mode and sae - 7 operands.
15053       if (Op.getNumOperands() == 6) {
15054         SDValue Sae  = Op.getOperand(5);
15055         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15056         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15057                                                 Sae),
15058                                     Mask, Src0, Subtarget, DAG);
15059       }
15060       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15061       SDValue RoundingMode  = Op.getOperand(5);
15062       SDValue Sae  = Op.getOperand(6);
15063       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15064                                               RoundingMode, Sae),
15065                                   Mask, Src0, Subtarget, DAG);
15066     }
15067     case INTR_TYPE_2OP_MASK: {
15068       SDValue Src1 = Op.getOperand(1);
15069       SDValue Src2 = Op.getOperand(2);
15070       SDValue PassThru = Op.getOperand(3);
15071       SDValue Mask = Op.getOperand(4);
15072       // We specify 2 possible opcodes for intrinsics with rounding modes.
15073       // First, we check if the intrinsic may have non-default rounding mode,
15074       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15075       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15076       if (IntrWithRoundingModeOpcode != 0) {
15077         SDValue Rnd = Op.getOperand(5);
15078         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15079         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15080           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15081                                       dl, Op.getValueType(),
15082                                       Src1, Src2, Rnd),
15083                                       Mask, PassThru, Subtarget, DAG);
15084         }
15085       }
15086       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15087                                               Src1,Src2),
15088                                   Mask, PassThru, Subtarget, DAG);
15089     }
15090     case FMA_OP_MASK: {
15091       SDValue Src1 = Op.getOperand(1);
15092       SDValue Src2 = Op.getOperand(2);
15093       SDValue Src3 = Op.getOperand(3);
15094       SDValue Mask = Op.getOperand(4);
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       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15099       if (IntrWithRoundingModeOpcode != 0) {
15100         SDValue Rnd = Op.getOperand(5);
15101         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15102             X86::STATIC_ROUNDING::CUR_DIRECTION)
15103           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15104                                                   dl, Op.getValueType(),
15105                                                   Src1, Src2, Src3, Rnd),
15106                                       Mask, Src1, Subtarget, DAG);
15107       }
15108       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15109                                               dl, Op.getValueType(),
15110                                               Src1, Src2, Src3),
15111                                   Mask, Src1, Subtarget, DAG);
15112     }
15113     case CMP_MASK:
15114     case CMP_MASK_CC: {
15115       // Comparison intrinsics with masks.
15116       // Example of transformation:
15117       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15118       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15119       // (i8 (bitcast
15120       //   (v8i1 (insert_subvector undef,
15121       //           (v2i1 (and (PCMPEQM %a, %b),
15122       //                      (extract_subvector
15123       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15124       EVT VT = Op.getOperand(1).getValueType();
15125       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15126                                     VT.getVectorNumElements());
15127       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15128       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15129                                        Mask.getValueType().getSizeInBits());
15130       SDValue Cmp;
15131       if (IntrData->Type == CMP_MASK_CC) {
15132         SDValue CC = Op.getOperand(3);
15133         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15134         // We specify 2 possible opcodes for intrinsics with rounding modes.
15135         // First, we check if the intrinsic may have non-default rounding mode,
15136         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15137         if (IntrData->Opc1 != 0) {
15138           SDValue Rnd = Op.getOperand(5);
15139           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15140               X86::STATIC_ROUNDING::CUR_DIRECTION)
15141             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15142                               Op.getOperand(2), CC, Rnd);
15143         }
15144         //default rounding mode
15145         if(!Cmp.getNode())
15146             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15147                               Op.getOperand(2), CC);
15148
15149       } else {
15150         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15151         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15152                           Op.getOperand(2));
15153       }
15154       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15155                                              DAG.getTargetConstant(0, dl,
15156                                                                    MaskVT),
15157                                              Subtarget, DAG);
15158       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15159                                 DAG.getUNDEF(BitcastVT), CmpMask,
15160                                 DAG.getIntPtrConstant(0, dl));
15161       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15162     }
15163     case COMI: { // Comparison intrinsics
15164       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15165       SDValue LHS = Op.getOperand(1);
15166       SDValue RHS = Op.getOperand(2);
15167       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15168       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15169       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15170       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15171                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15172       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15173     }
15174     case VSHIFT:
15175       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15176                                  Op.getOperand(1), Op.getOperand(2), DAG);
15177     case VSHIFT_MASK:
15178       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15179                                                       Op.getSimpleValueType(),
15180                                                       Op.getOperand(1),
15181                                                       Op.getOperand(2), DAG),
15182                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15183                                   DAG);
15184     case COMPRESS_EXPAND_IN_REG: {
15185       SDValue Mask = Op.getOperand(3);
15186       SDValue DataToCompress = Op.getOperand(1);
15187       SDValue PassThru = Op.getOperand(2);
15188       if (isAllOnes(Mask)) // return data as is
15189         return Op.getOperand(1);
15190       EVT VT = Op.getValueType();
15191       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15192                                     VT.getVectorNumElements());
15193       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15194                                        Mask.getValueType().getSizeInBits());
15195       SDLoc dl(Op);
15196       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15197                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15198                                   DAG.getIntPtrConstant(0, dl));
15199
15200       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15201                          PassThru);
15202     }
15203     case BLEND: {
15204       SDValue Mask = Op.getOperand(3);
15205       EVT VT = Op.getValueType();
15206       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15207                                     VT.getVectorNumElements());
15208       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15209                                        Mask.getValueType().getSizeInBits());
15210       SDLoc dl(Op);
15211       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15212                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15213                                   DAG.getIntPtrConstant(0, dl));
15214       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15215                          Op.getOperand(2));
15216     }
15217     default:
15218       break;
15219     }
15220   }
15221
15222   switch (IntNo) {
15223   default: return SDValue();    // Don't custom lower most intrinsics.
15224
15225   case Intrinsic::x86_avx2_permd:
15226   case Intrinsic::x86_avx2_permps:
15227     // Operands intentionally swapped. Mask is last operand to intrinsic,
15228     // but second operand for node/instruction.
15229     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15230                        Op.getOperand(2), Op.getOperand(1));
15231
15232   case Intrinsic::x86_avx512_mask_valign_q_512:
15233   case Intrinsic::x86_avx512_mask_valign_d_512:
15234     // Vector source operands are swapped.
15235     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15236                                             Op.getValueType(), Op.getOperand(2),
15237                                             Op.getOperand(1),
15238                                             Op.getOperand(3)),
15239                                 Op.getOperand(5), Op.getOperand(4),
15240                                 Subtarget, DAG);
15241
15242   // ptest and testp intrinsics. The intrinsic these come from are designed to
15243   // return an integer value, not just an instruction so lower it to the ptest
15244   // or testp pattern and a setcc for the result.
15245   case Intrinsic::x86_sse41_ptestz:
15246   case Intrinsic::x86_sse41_ptestc:
15247   case Intrinsic::x86_sse41_ptestnzc:
15248   case Intrinsic::x86_avx_ptestz_256:
15249   case Intrinsic::x86_avx_ptestc_256:
15250   case Intrinsic::x86_avx_ptestnzc_256:
15251   case Intrinsic::x86_avx_vtestz_ps:
15252   case Intrinsic::x86_avx_vtestc_ps:
15253   case Intrinsic::x86_avx_vtestnzc_ps:
15254   case Intrinsic::x86_avx_vtestz_pd:
15255   case Intrinsic::x86_avx_vtestc_pd:
15256   case Intrinsic::x86_avx_vtestnzc_pd:
15257   case Intrinsic::x86_avx_vtestz_ps_256:
15258   case Intrinsic::x86_avx_vtestc_ps_256:
15259   case Intrinsic::x86_avx_vtestnzc_ps_256:
15260   case Intrinsic::x86_avx_vtestz_pd_256:
15261   case Intrinsic::x86_avx_vtestc_pd_256:
15262   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15263     bool IsTestPacked = false;
15264     unsigned X86CC;
15265     switch (IntNo) {
15266     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15267     case Intrinsic::x86_avx_vtestz_ps:
15268     case Intrinsic::x86_avx_vtestz_pd:
15269     case Intrinsic::x86_avx_vtestz_ps_256:
15270     case Intrinsic::x86_avx_vtestz_pd_256:
15271       IsTestPacked = true; // Fallthrough
15272     case Intrinsic::x86_sse41_ptestz:
15273     case Intrinsic::x86_avx_ptestz_256:
15274       // ZF = 1
15275       X86CC = X86::COND_E;
15276       break;
15277     case Intrinsic::x86_avx_vtestc_ps:
15278     case Intrinsic::x86_avx_vtestc_pd:
15279     case Intrinsic::x86_avx_vtestc_ps_256:
15280     case Intrinsic::x86_avx_vtestc_pd_256:
15281       IsTestPacked = true; // Fallthrough
15282     case Intrinsic::x86_sse41_ptestc:
15283     case Intrinsic::x86_avx_ptestc_256:
15284       // CF = 1
15285       X86CC = X86::COND_B;
15286       break;
15287     case Intrinsic::x86_avx_vtestnzc_ps:
15288     case Intrinsic::x86_avx_vtestnzc_pd:
15289     case Intrinsic::x86_avx_vtestnzc_ps_256:
15290     case Intrinsic::x86_avx_vtestnzc_pd_256:
15291       IsTestPacked = true; // Fallthrough
15292     case Intrinsic::x86_sse41_ptestnzc:
15293     case Intrinsic::x86_avx_ptestnzc_256:
15294       // ZF and CF = 0
15295       X86CC = X86::COND_A;
15296       break;
15297     }
15298
15299     SDValue LHS = Op.getOperand(1);
15300     SDValue RHS = Op.getOperand(2);
15301     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15302     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15303     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15304     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15305     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15306   }
15307   case Intrinsic::x86_avx512_kortestz_w:
15308   case Intrinsic::x86_avx512_kortestc_w: {
15309     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15310     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15311     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15312     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15313     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15314     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15315     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15316   }
15317
15318   case Intrinsic::x86_sse42_pcmpistria128:
15319   case Intrinsic::x86_sse42_pcmpestria128:
15320   case Intrinsic::x86_sse42_pcmpistric128:
15321   case Intrinsic::x86_sse42_pcmpestric128:
15322   case Intrinsic::x86_sse42_pcmpistrio128:
15323   case Intrinsic::x86_sse42_pcmpestrio128:
15324   case Intrinsic::x86_sse42_pcmpistris128:
15325   case Intrinsic::x86_sse42_pcmpestris128:
15326   case Intrinsic::x86_sse42_pcmpistriz128:
15327   case Intrinsic::x86_sse42_pcmpestriz128: {
15328     unsigned Opcode;
15329     unsigned X86CC;
15330     switch (IntNo) {
15331     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15332     case Intrinsic::x86_sse42_pcmpistria128:
15333       Opcode = X86ISD::PCMPISTRI;
15334       X86CC = X86::COND_A;
15335       break;
15336     case Intrinsic::x86_sse42_pcmpestria128:
15337       Opcode = X86ISD::PCMPESTRI;
15338       X86CC = X86::COND_A;
15339       break;
15340     case Intrinsic::x86_sse42_pcmpistric128:
15341       Opcode = X86ISD::PCMPISTRI;
15342       X86CC = X86::COND_B;
15343       break;
15344     case Intrinsic::x86_sse42_pcmpestric128:
15345       Opcode = X86ISD::PCMPESTRI;
15346       X86CC = X86::COND_B;
15347       break;
15348     case Intrinsic::x86_sse42_pcmpistrio128:
15349       Opcode = X86ISD::PCMPISTRI;
15350       X86CC = X86::COND_O;
15351       break;
15352     case Intrinsic::x86_sse42_pcmpestrio128:
15353       Opcode = X86ISD::PCMPESTRI;
15354       X86CC = X86::COND_O;
15355       break;
15356     case Intrinsic::x86_sse42_pcmpistris128:
15357       Opcode = X86ISD::PCMPISTRI;
15358       X86CC = X86::COND_S;
15359       break;
15360     case Intrinsic::x86_sse42_pcmpestris128:
15361       Opcode = X86ISD::PCMPESTRI;
15362       X86CC = X86::COND_S;
15363       break;
15364     case Intrinsic::x86_sse42_pcmpistriz128:
15365       Opcode = X86ISD::PCMPISTRI;
15366       X86CC = X86::COND_E;
15367       break;
15368     case Intrinsic::x86_sse42_pcmpestriz128:
15369       Opcode = X86ISD::PCMPESTRI;
15370       X86CC = X86::COND_E;
15371       break;
15372     }
15373     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15374     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15375     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15376     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15377                                 DAG.getConstant(X86CC, dl, MVT::i8),
15378                                 SDValue(PCMP.getNode(), 1));
15379     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15380   }
15381
15382   case Intrinsic::x86_sse42_pcmpistri128:
15383   case Intrinsic::x86_sse42_pcmpestri128: {
15384     unsigned Opcode;
15385     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15386       Opcode = X86ISD::PCMPISTRI;
15387     else
15388       Opcode = X86ISD::PCMPESTRI;
15389
15390     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15391     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15392     return DAG.getNode(Opcode, dl, VTs, NewOps);
15393   }
15394
15395   case Intrinsic::x86_seh_lsda: {
15396     // Compute the symbol for the LSDA. We know it'll get emitted later.
15397     MachineFunction &MF = DAG.getMachineFunction();
15398     SDValue Op1 = Op.getOperand(1);
15399     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15400     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15401         GlobalValue::getRealLinkageName(Fn->getName()));
15402     StringRef Name = LSDASym->getName();
15403     assert(Name.data()[Name.size()] == '\0' && "not null terminated");
15404
15405     // Generate a simple absolute symbol reference. This intrinsic is only
15406     // supported on 32-bit Windows, which isn't PIC.
15407     SDValue Result =
15408         DAG.getTargetExternalSymbol(Name.data(), VT, X86II::MO_NOPREFIX);
15409     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15410   }
15411   }
15412 }
15413
15414 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15415                               SDValue Src, SDValue Mask, SDValue Base,
15416                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15417                               const X86Subtarget * Subtarget) {
15418   SDLoc dl(Op);
15419   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15420   assert(C && "Invalid scale type");
15421   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15422   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15423                              Index.getSimpleValueType().getVectorNumElements());
15424   SDValue MaskInReg;
15425   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15426   if (MaskC)
15427     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15428   else
15429     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15430   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15431   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15432   SDValue Segment = DAG.getRegister(0, MVT::i32);
15433   if (Src.getOpcode() == ISD::UNDEF)
15434     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15435   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15436   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15437   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15438   return DAG.getMergeValues(RetOps, dl);
15439 }
15440
15441 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15442                                SDValue Src, SDValue Mask, SDValue Base,
15443                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15444   SDLoc dl(Op);
15445   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15446   assert(C && "Invalid scale type");
15447   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15448   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15449   SDValue Segment = DAG.getRegister(0, MVT::i32);
15450   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15451                              Index.getSimpleValueType().getVectorNumElements());
15452   SDValue MaskInReg;
15453   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15454   if (MaskC)
15455     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15456   else
15457     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15458   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15459   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15460   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15461   return SDValue(Res, 1);
15462 }
15463
15464 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15465                                SDValue Mask, SDValue Base, SDValue Index,
15466                                SDValue ScaleOp, SDValue Chain) {
15467   SDLoc dl(Op);
15468   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15469   assert(C && "Invalid scale type");
15470   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15471   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15472   SDValue Segment = DAG.getRegister(0, MVT::i32);
15473   EVT MaskVT =
15474     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15475   SDValue MaskInReg;
15476   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15477   if (MaskC)
15478     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15479   else
15480     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15481   //SDVTList VTs = DAG.getVTList(MVT::Other);
15482   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15483   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15484   return SDValue(Res, 0);
15485 }
15486
15487 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15488 // read performance monitor counters (x86_rdpmc).
15489 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15490                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15491                               SmallVectorImpl<SDValue> &Results) {
15492   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15493   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15494   SDValue LO, HI;
15495
15496   // The ECX register is used to select the index of the performance counter
15497   // to read.
15498   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15499                                    N->getOperand(2));
15500   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15501
15502   // Reads the content of a 64-bit performance counter and returns it in the
15503   // registers EDX:EAX.
15504   if (Subtarget->is64Bit()) {
15505     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15506     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15507                             LO.getValue(2));
15508   } else {
15509     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15510     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15511                             LO.getValue(2));
15512   }
15513   Chain = HI.getValue(1);
15514
15515   if (Subtarget->is64Bit()) {
15516     // The EAX register is loaded with the low-order 32 bits. The EDX register
15517     // is loaded with the supported high-order bits of the counter.
15518     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15519                               DAG.getConstant(32, DL, MVT::i8));
15520     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15521     Results.push_back(Chain);
15522     return;
15523   }
15524
15525   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15526   SDValue Ops[] = { LO, HI };
15527   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15528   Results.push_back(Pair);
15529   Results.push_back(Chain);
15530 }
15531
15532 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15533 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15534 // also used to custom lower READCYCLECOUNTER nodes.
15535 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15536                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15537                               SmallVectorImpl<SDValue> &Results) {
15538   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15539   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15540   SDValue LO, HI;
15541
15542   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15543   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15544   // and the EAX register is loaded with the low-order 32 bits.
15545   if (Subtarget->is64Bit()) {
15546     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15547     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15548                             LO.getValue(2));
15549   } else {
15550     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15551     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15552                             LO.getValue(2));
15553   }
15554   SDValue Chain = HI.getValue(1);
15555
15556   if (Opcode == X86ISD::RDTSCP_DAG) {
15557     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15558
15559     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15560     // the ECX register. Add 'ecx' explicitly to the chain.
15561     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15562                                      HI.getValue(2));
15563     // Explicitly store the content of ECX at the location passed in input
15564     // to the 'rdtscp' intrinsic.
15565     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15566                          MachinePointerInfo(), false, false, 0);
15567   }
15568
15569   if (Subtarget->is64Bit()) {
15570     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15571     // the EAX register is loaded with the low-order 32 bits.
15572     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15573                               DAG.getConstant(32, DL, MVT::i8));
15574     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15575     Results.push_back(Chain);
15576     return;
15577   }
15578
15579   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15580   SDValue Ops[] = { LO, HI };
15581   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15582   Results.push_back(Pair);
15583   Results.push_back(Chain);
15584 }
15585
15586 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15587                                      SelectionDAG &DAG) {
15588   SmallVector<SDValue, 2> Results;
15589   SDLoc DL(Op);
15590   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15591                           Results);
15592   return DAG.getMergeValues(Results, DL);
15593 }
15594
15595
15596 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15597                                       SelectionDAG &DAG) {
15598   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15599
15600   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15601   if (!IntrData)
15602     return SDValue();
15603
15604   SDLoc dl(Op);
15605   switch(IntrData->Type) {
15606   default:
15607     llvm_unreachable("Unknown Intrinsic Type");
15608     break;
15609   case RDSEED:
15610   case RDRAND: {
15611     // Emit the node with the right value type.
15612     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15613     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15614
15615     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15616     // Otherwise return the value from Rand, which is always 0, casted to i32.
15617     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15618                       DAG.getConstant(1, dl, Op->getValueType(1)),
15619                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15620                       SDValue(Result.getNode(), 1) };
15621     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15622                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15623                                   Ops);
15624
15625     // Return { result, isValid, chain }.
15626     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15627                        SDValue(Result.getNode(), 2));
15628   }
15629   case GATHER: {
15630   //gather(v1, mask, index, base, scale);
15631     SDValue Chain = Op.getOperand(0);
15632     SDValue Src   = Op.getOperand(2);
15633     SDValue Base  = Op.getOperand(3);
15634     SDValue Index = Op.getOperand(4);
15635     SDValue Mask  = Op.getOperand(5);
15636     SDValue Scale = Op.getOperand(6);
15637     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15638                          Chain, Subtarget);
15639   }
15640   case SCATTER: {
15641   //scatter(base, mask, index, v1, scale);
15642     SDValue Chain = Op.getOperand(0);
15643     SDValue Base  = Op.getOperand(2);
15644     SDValue Mask  = Op.getOperand(3);
15645     SDValue Index = Op.getOperand(4);
15646     SDValue Src   = Op.getOperand(5);
15647     SDValue Scale = Op.getOperand(6);
15648     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15649                           Scale, Chain);
15650   }
15651   case PREFETCH: {
15652     SDValue Hint = Op.getOperand(6);
15653     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15654     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15655     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15656     SDValue Chain = Op.getOperand(0);
15657     SDValue Mask  = Op.getOperand(2);
15658     SDValue Index = Op.getOperand(3);
15659     SDValue Base  = Op.getOperand(4);
15660     SDValue Scale = Op.getOperand(5);
15661     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15662   }
15663   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15664   case RDTSC: {
15665     SmallVector<SDValue, 2> Results;
15666     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15667                             Results);
15668     return DAG.getMergeValues(Results, dl);
15669   }
15670   // Read Performance Monitoring Counters.
15671   case RDPMC: {
15672     SmallVector<SDValue, 2> Results;
15673     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15674     return DAG.getMergeValues(Results, dl);
15675   }
15676   // XTEST intrinsics.
15677   case XTEST: {
15678     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15679     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15680     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15681                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15682                                 InTrans);
15683     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15684     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15685                        Ret, SDValue(InTrans.getNode(), 1));
15686   }
15687   // ADC/ADCX/SBB
15688   case ADX: {
15689     SmallVector<SDValue, 2> Results;
15690     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15691     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15692     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15693                                 DAG.getConstant(-1, dl, MVT::i8));
15694     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15695                               Op.getOperand(4), GenCF.getValue(1));
15696     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15697                                  Op.getOperand(5), MachinePointerInfo(),
15698                                  false, false, 0);
15699     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15700                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15701                                 Res.getValue(1));
15702     Results.push_back(SetCC);
15703     Results.push_back(Store);
15704     return DAG.getMergeValues(Results, dl);
15705   }
15706   case COMPRESS_TO_MEM: {
15707     SDLoc dl(Op);
15708     SDValue Mask = Op.getOperand(4);
15709     SDValue DataToCompress = Op.getOperand(3);
15710     SDValue Addr = Op.getOperand(2);
15711     SDValue Chain = Op.getOperand(0);
15712
15713     if (isAllOnes(Mask)) // return just a store
15714       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15715                           MachinePointerInfo(), false, false, 0);
15716
15717     EVT VT = DataToCompress.getValueType();
15718     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15719                                   VT.getVectorNumElements());
15720     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15721                                      Mask.getValueType().getSizeInBits());
15722     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15723                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15724                                 DAG.getIntPtrConstant(0, dl));
15725
15726     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15727                                       DataToCompress, DAG.getUNDEF(VT));
15728     return DAG.getStore(Chain, dl, Compressed, Addr,
15729                         MachinePointerInfo(), false, false, 0);
15730   }
15731   case EXPAND_FROM_MEM: {
15732     SDLoc dl(Op);
15733     SDValue Mask = Op.getOperand(4);
15734     SDValue PathThru = Op.getOperand(3);
15735     SDValue Addr = Op.getOperand(2);
15736     SDValue Chain = Op.getOperand(0);
15737     EVT VT = Op.getValueType();
15738
15739     if (isAllOnes(Mask)) // return just a load
15740       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15741                          false, 0);
15742     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15743                                   VT.getVectorNumElements());
15744     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15745                                      Mask.getValueType().getSizeInBits());
15746     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15747                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15748                                 DAG.getIntPtrConstant(0, dl));
15749
15750     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15751                                    false, false, false, 0);
15752
15753     SDValue Results[] = {
15754         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15755         Chain};
15756     return DAG.getMergeValues(Results, dl);
15757   }
15758   }
15759 }
15760
15761 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15762                                            SelectionDAG &DAG) const {
15763   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15764   MFI->setReturnAddressIsTaken(true);
15765
15766   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15767     return SDValue();
15768
15769   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15770   SDLoc dl(Op);
15771   EVT PtrVT = getPointerTy();
15772
15773   if (Depth > 0) {
15774     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15775     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15776     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15777     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15778                        DAG.getNode(ISD::ADD, dl, PtrVT,
15779                                    FrameAddr, Offset),
15780                        MachinePointerInfo(), false, false, false, 0);
15781   }
15782
15783   // Just load the return address.
15784   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15785   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15786                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15787 }
15788
15789 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15790   MachineFunction &MF = DAG.getMachineFunction();
15791   MachineFrameInfo *MFI = MF.getFrameInfo();
15792   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15793   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15794   EVT VT = Op.getValueType();
15795
15796   MFI->setFrameAddressIsTaken(true);
15797
15798   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15799     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15800     // is not possible to crawl up the stack without looking at the unwind codes
15801     // simultaneously.
15802     int FrameAddrIndex = FuncInfo->getFAIndex();
15803     if (!FrameAddrIndex) {
15804       // Set up a frame object for the return address.
15805       unsigned SlotSize = RegInfo->getSlotSize();
15806       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15807           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15808       FuncInfo->setFAIndex(FrameAddrIndex);
15809     }
15810     return DAG.getFrameIndex(FrameAddrIndex, VT);
15811   }
15812
15813   unsigned FrameReg =
15814       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15815   SDLoc dl(Op);  // FIXME probably not meaningful
15816   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15817   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15818           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15819          "Invalid Frame Register!");
15820   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15821   while (Depth--)
15822     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15823                             MachinePointerInfo(),
15824                             false, false, false, 0);
15825   return FrameAddr;
15826 }
15827
15828 // FIXME? Maybe this could be a TableGen attribute on some registers and
15829 // this table could be generated automatically from RegInfo.
15830 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15831                                               EVT VT) const {
15832   unsigned Reg = StringSwitch<unsigned>(RegName)
15833                        .Case("esp", X86::ESP)
15834                        .Case("rsp", X86::RSP)
15835                        .Default(0);
15836   if (Reg)
15837     return Reg;
15838   report_fatal_error("Invalid register name global variable");
15839 }
15840
15841 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15842                                                      SelectionDAG &DAG) const {
15843   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15844   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15845 }
15846
15847 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15848   SDValue Chain     = Op.getOperand(0);
15849   SDValue Offset    = Op.getOperand(1);
15850   SDValue Handler   = Op.getOperand(2);
15851   SDLoc dl      (Op);
15852
15853   EVT PtrVT = getPointerTy();
15854   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15855   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15856   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15857           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15858          "Invalid Frame Register!");
15859   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15860   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15861
15862   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15863                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15864                                                        dl));
15865   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15866   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15867                        false, false, 0);
15868   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15869
15870   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15871                      DAG.getRegister(StoreAddrReg, PtrVT));
15872 }
15873
15874 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15875                                                SelectionDAG &DAG) const {
15876   SDLoc DL(Op);
15877   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15878                      DAG.getVTList(MVT::i32, MVT::Other),
15879                      Op.getOperand(0), Op.getOperand(1));
15880 }
15881
15882 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15883                                                 SelectionDAG &DAG) const {
15884   SDLoc DL(Op);
15885   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15886                      Op.getOperand(0), Op.getOperand(1));
15887 }
15888
15889 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15890   return Op.getOperand(0);
15891 }
15892
15893 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15894                                                 SelectionDAG &DAG) const {
15895   SDValue Root = Op.getOperand(0);
15896   SDValue Trmp = Op.getOperand(1); // trampoline
15897   SDValue FPtr = Op.getOperand(2); // nested function
15898   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15899   SDLoc dl (Op);
15900
15901   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15902   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15903
15904   if (Subtarget->is64Bit()) {
15905     SDValue OutChains[6];
15906
15907     // Large code-model.
15908     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15909     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15910
15911     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15912     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15913
15914     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15915
15916     // Load the pointer to the nested function into R11.
15917     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15918     SDValue Addr = Trmp;
15919     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15920                                 Addr, MachinePointerInfo(TrmpAddr),
15921                                 false, false, 0);
15922
15923     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15924                        DAG.getConstant(2, dl, MVT::i64));
15925     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15926                                 MachinePointerInfo(TrmpAddr, 2),
15927                                 false, false, 2);
15928
15929     // Load the 'nest' parameter value into R10.
15930     // R10 is specified in X86CallingConv.td
15931     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15932     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15933                        DAG.getConstant(10, dl, MVT::i64));
15934     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15935                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15936                                 false, false, 0);
15937
15938     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15939                        DAG.getConstant(12, dl, MVT::i64));
15940     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15941                                 MachinePointerInfo(TrmpAddr, 12),
15942                                 false, false, 2);
15943
15944     // Jump to the nested function.
15945     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15946     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15947                        DAG.getConstant(20, dl, MVT::i64));
15948     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15949                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15950                                 false, false, 0);
15951
15952     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15953     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15954                        DAG.getConstant(22, dl, MVT::i64));
15955     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15956                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15957                                 false, false, 0);
15958
15959     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15960   } else {
15961     const Function *Func =
15962       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15963     CallingConv::ID CC = Func->getCallingConv();
15964     unsigned NestReg;
15965
15966     switch (CC) {
15967     default:
15968       llvm_unreachable("Unsupported calling convention");
15969     case CallingConv::C:
15970     case CallingConv::X86_StdCall: {
15971       // Pass 'nest' parameter in ECX.
15972       // Must be kept in sync with X86CallingConv.td
15973       NestReg = X86::ECX;
15974
15975       // Check that ECX wasn't needed by an 'inreg' parameter.
15976       FunctionType *FTy = Func->getFunctionType();
15977       const AttributeSet &Attrs = Func->getAttributes();
15978
15979       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15980         unsigned InRegCount = 0;
15981         unsigned Idx = 1;
15982
15983         for (FunctionType::param_iterator I = FTy->param_begin(),
15984              E = FTy->param_end(); I != E; ++I, ++Idx)
15985           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15986             // FIXME: should only count parameters that are lowered to integers.
15987             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15988
15989         if (InRegCount > 2) {
15990           report_fatal_error("Nest register in use - reduce number of inreg"
15991                              " parameters!");
15992         }
15993       }
15994       break;
15995     }
15996     case CallingConv::X86_FastCall:
15997     case CallingConv::X86_ThisCall:
15998     case CallingConv::Fast:
15999       // Pass 'nest' parameter in EAX.
16000       // Must be kept in sync with X86CallingConv.td
16001       NestReg = X86::EAX;
16002       break;
16003     }
16004
16005     SDValue OutChains[4];
16006     SDValue Addr, Disp;
16007
16008     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16009                        DAG.getConstant(10, dl, MVT::i32));
16010     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16011
16012     // This is storing the opcode for MOV32ri.
16013     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16014     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16015     OutChains[0] = DAG.getStore(Root, dl,
16016                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16017                                 Trmp, MachinePointerInfo(TrmpAddr),
16018                                 false, false, 0);
16019
16020     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16021                        DAG.getConstant(1, dl, MVT::i32));
16022     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16023                                 MachinePointerInfo(TrmpAddr, 1),
16024                                 false, false, 1);
16025
16026     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16027     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16028                        DAG.getConstant(5, dl, MVT::i32));
16029     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16030                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16031                                 false, false, 1);
16032
16033     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16034                        DAG.getConstant(6, dl, MVT::i32));
16035     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16036                                 MachinePointerInfo(TrmpAddr, 6),
16037                                 false, false, 1);
16038
16039     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16040   }
16041 }
16042
16043 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16044                                             SelectionDAG &DAG) const {
16045   /*
16046    The rounding mode is in bits 11:10 of FPSR, and has the following
16047    settings:
16048      00 Round to nearest
16049      01 Round to -inf
16050      10 Round to +inf
16051      11 Round to 0
16052
16053   FLT_ROUNDS, on the other hand, expects the following:
16054     -1 Undefined
16055      0 Round to 0
16056      1 Round to nearest
16057      2 Round to +inf
16058      3 Round to -inf
16059
16060   To perform the conversion, we do:
16061     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16062   */
16063
16064   MachineFunction &MF = DAG.getMachineFunction();
16065   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16066   unsigned StackAlignment = TFI.getStackAlignment();
16067   MVT VT = Op.getSimpleValueType();
16068   SDLoc DL(Op);
16069
16070   // Save FP Control Word to stack slot
16071   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16072   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16073
16074   MachineMemOperand *MMO =
16075    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16076                            MachineMemOperand::MOStore, 2, 2);
16077
16078   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16079   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16080                                           DAG.getVTList(MVT::Other),
16081                                           Ops, MVT::i16, MMO);
16082
16083   // Load FP Control Word from stack slot
16084   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16085                             MachinePointerInfo(), false, false, false, 0);
16086
16087   // Transform as necessary
16088   SDValue CWD1 =
16089     DAG.getNode(ISD::SRL, DL, MVT::i16,
16090                 DAG.getNode(ISD::AND, DL, MVT::i16,
16091                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16092                 DAG.getConstant(11, DL, MVT::i8));
16093   SDValue CWD2 =
16094     DAG.getNode(ISD::SRL, DL, MVT::i16,
16095                 DAG.getNode(ISD::AND, DL, MVT::i16,
16096                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16097                 DAG.getConstant(9, DL, MVT::i8));
16098
16099   SDValue RetVal =
16100     DAG.getNode(ISD::AND, DL, MVT::i16,
16101                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16102                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16103                             DAG.getConstant(1, DL, MVT::i16)),
16104                 DAG.getConstant(3, DL, MVT::i16));
16105
16106   return DAG.getNode((VT.getSizeInBits() < 16 ?
16107                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16108 }
16109
16110 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16111   MVT VT = Op.getSimpleValueType();
16112   EVT OpVT = VT;
16113   unsigned NumBits = VT.getSizeInBits();
16114   SDLoc dl(Op);
16115
16116   Op = Op.getOperand(0);
16117   if (VT == MVT::i8) {
16118     // Zero extend to i32 since there is not an i8 bsr.
16119     OpVT = MVT::i32;
16120     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16121   }
16122
16123   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16124   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16125   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16126
16127   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16128   SDValue Ops[] = {
16129     Op,
16130     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16131     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16132     Op.getValue(1)
16133   };
16134   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16135
16136   // Finally xor with NumBits-1.
16137   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16138                    DAG.getConstant(NumBits - 1, dl, OpVT));
16139
16140   if (VT == MVT::i8)
16141     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16142   return Op;
16143 }
16144
16145 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16146   MVT VT = Op.getSimpleValueType();
16147   EVT OpVT = VT;
16148   unsigned NumBits = VT.getSizeInBits();
16149   SDLoc dl(Op);
16150
16151   Op = Op.getOperand(0);
16152   if (VT == MVT::i8) {
16153     // Zero extend to i32 since there is not an i8 bsr.
16154     OpVT = MVT::i32;
16155     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16156   }
16157
16158   // Issue a bsr (scan bits in reverse).
16159   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16160   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16161
16162   // And xor with NumBits-1.
16163   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16164                    DAG.getConstant(NumBits - 1, dl, OpVT));
16165
16166   if (VT == MVT::i8)
16167     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16168   return Op;
16169 }
16170
16171 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16172   MVT VT = Op.getSimpleValueType();
16173   unsigned NumBits = VT.getSizeInBits();
16174   SDLoc dl(Op);
16175   Op = Op.getOperand(0);
16176
16177   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16178   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16179   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16180
16181   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16182   SDValue Ops[] = {
16183     Op,
16184     DAG.getConstant(NumBits, dl, VT),
16185     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16186     Op.getValue(1)
16187   };
16188   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16189 }
16190
16191 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16192 // ones, and then concatenate the result back.
16193 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16194   MVT VT = Op.getSimpleValueType();
16195
16196   assert(VT.is256BitVector() && VT.isInteger() &&
16197          "Unsupported value type for operation");
16198
16199   unsigned NumElems = VT.getVectorNumElements();
16200   SDLoc dl(Op);
16201
16202   // Extract the LHS vectors
16203   SDValue LHS = Op.getOperand(0);
16204   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16205   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16206
16207   // Extract the RHS vectors
16208   SDValue RHS = Op.getOperand(1);
16209   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16210   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16211
16212   MVT EltVT = VT.getVectorElementType();
16213   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16214
16215   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16216                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16217                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16218 }
16219
16220 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16221   if (Op.getValueType() == MVT::i1)
16222     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16223                        Op.getOperand(0), Op.getOperand(1));
16224   assert(Op.getSimpleValueType().is256BitVector() &&
16225          Op.getSimpleValueType().isInteger() &&
16226          "Only handle AVX 256-bit vector integer operation");
16227   return Lower256IntArith(Op, DAG);
16228 }
16229
16230 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16231   if (Op.getValueType() == MVT::i1)
16232     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16233                        Op.getOperand(0), Op.getOperand(1));
16234   assert(Op.getSimpleValueType().is256BitVector() &&
16235          Op.getSimpleValueType().isInteger() &&
16236          "Only handle AVX 256-bit vector integer operation");
16237   return Lower256IntArith(Op, DAG);
16238 }
16239
16240 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16241                         SelectionDAG &DAG) {
16242   SDLoc dl(Op);
16243   MVT VT = Op.getSimpleValueType();
16244
16245   if (VT == MVT::i1)
16246     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16247
16248   // Decompose 256-bit ops into smaller 128-bit ops.
16249   if (VT.is256BitVector() && !Subtarget->hasInt256())
16250     return Lower256IntArith(Op, DAG);
16251
16252   SDValue A = Op.getOperand(0);
16253   SDValue B = Op.getOperand(1);
16254
16255   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16256   // pairs, multiply and truncate.
16257   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16258     if (Subtarget->hasInt256()) {
16259       if (VT == MVT::v32i8) {
16260         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16261         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16262         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16263         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16264         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16265         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16266         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16267         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16268                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16269                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16270       }
16271
16272       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16273       return DAG.getNode(
16274           ISD::TRUNCATE, dl, VT,
16275           DAG.getNode(ISD::MUL, dl, ExVT,
16276                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16277                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16278     }
16279
16280     assert(VT == MVT::v16i8 &&
16281            "Pre-AVX2 support only supports v16i8 multiplication");
16282     MVT ExVT = MVT::v8i16;
16283
16284     // Extract the lo parts and sign extend to i16
16285     SDValue ALo, BLo;
16286     if (Subtarget->hasSSE41()) {
16287       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16288       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16289     } else {
16290       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16291                               -1, 4, -1, 5, -1, 6, -1, 7};
16292       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16293       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16294       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16295       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16296       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16297       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16298     }
16299
16300     // Extract the hi parts and sign extend to i16
16301     SDValue AHi, BHi;
16302     if (Subtarget->hasSSE41()) {
16303       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16304                               -1, -1, -1, -1, -1, -1, -1, -1};
16305       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16306       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16307       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16308       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16309     } else {
16310       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16311                               -1, 12, -1, 13, -1, 14, -1, 15};
16312       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16313       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16314       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16315       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16316       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16317       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16318     }
16319
16320     // Multiply, mask the lower 8bits of the lo/hi results and pack
16321     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16322     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16323     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16324     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16325     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16326   }
16327
16328   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16329   if (VT == MVT::v4i32) {
16330     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16331            "Should not custom lower when pmuldq is available!");
16332
16333     // Extract the odd parts.
16334     static const int UnpackMask[] = { 1, -1, 3, -1 };
16335     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16336     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16337
16338     // Multiply the even parts.
16339     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16340     // Now multiply odd parts.
16341     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16342
16343     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16344     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16345
16346     // Merge the two vectors back together with a shuffle. This expands into 2
16347     // shuffles.
16348     static const int ShufMask[] = { 0, 4, 2, 6 };
16349     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16350   }
16351
16352   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16353          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16354
16355   //  Ahi = psrlqi(a, 32);
16356   //  Bhi = psrlqi(b, 32);
16357   //
16358   //  AloBlo = pmuludq(a, b);
16359   //  AloBhi = pmuludq(a, Bhi);
16360   //  AhiBlo = pmuludq(Ahi, b);
16361
16362   //  AloBhi = psllqi(AloBhi, 32);
16363   //  AhiBlo = psllqi(AhiBlo, 32);
16364   //  return AloBlo + AloBhi + AhiBlo;
16365
16366   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16367   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16368
16369   // Bit cast to 32-bit vectors for MULUDQ
16370   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16371                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16372   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16373   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16374   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16375   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16376
16377   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16378   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16379   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16380
16381   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16382   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16383
16384   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16385   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16386 }
16387
16388 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16389   assert(Subtarget->isTargetWin64() && "Unexpected target");
16390   EVT VT = Op.getValueType();
16391   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16392          "Unexpected return type for lowering");
16393
16394   RTLIB::Libcall LC;
16395   bool isSigned;
16396   switch (Op->getOpcode()) {
16397   default: llvm_unreachable("Unexpected request for libcall!");
16398   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16399   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16400   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16401   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16402   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16403   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16404   }
16405
16406   SDLoc dl(Op);
16407   SDValue InChain = DAG.getEntryNode();
16408
16409   TargetLowering::ArgListTy Args;
16410   TargetLowering::ArgListEntry Entry;
16411   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16412     EVT ArgVT = Op->getOperand(i).getValueType();
16413     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16414            "Unexpected argument type for lowering");
16415     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16416     Entry.Node = StackPtr;
16417     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16418                            false, false, 16);
16419     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16420     Entry.Ty = PointerType::get(ArgTy,0);
16421     Entry.isSExt = false;
16422     Entry.isZExt = false;
16423     Args.push_back(Entry);
16424   }
16425
16426   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16427                                          getPointerTy());
16428
16429   TargetLowering::CallLoweringInfo CLI(DAG);
16430   CLI.setDebugLoc(dl).setChain(InChain)
16431     .setCallee(getLibcallCallingConv(LC),
16432                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16433                Callee, std::move(Args), 0)
16434     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16435
16436   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16437   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16438 }
16439
16440 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16441                              SelectionDAG &DAG) {
16442   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16443   EVT VT = Op0.getValueType();
16444   SDLoc dl(Op);
16445
16446   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16447          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16448
16449   // PMULxD operations multiply each even value (starting at 0) of LHS with
16450   // the related value of RHS and produce a widen result.
16451   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16452   // => <2 x i64> <ae|cg>
16453   //
16454   // In other word, to have all the results, we need to perform two PMULxD:
16455   // 1. one with the even values.
16456   // 2. one with the odd values.
16457   // To achieve #2, with need to place the odd values at an even position.
16458   //
16459   // Place the odd value at an even position (basically, shift all values 1
16460   // step to the left):
16461   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16462   // <a|b|c|d> => <b|undef|d|undef>
16463   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16464   // <e|f|g|h> => <f|undef|h|undef>
16465   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16466
16467   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16468   // ints.
16469   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16470   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16471   unsigned Opcode =
16472       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16473   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16474   // => <2 x i64> <ae|cg>
16475   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16476                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16477   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16478   // => <2 x i64> <bf|dh>
16479   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16480                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16481
16482   // Shuffle it back into the right order.
16483   SDValue Highs, Lows;
16484   if (VT == MVT::v8i32) {
16485     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16486     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16487     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16488     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16489   } else {
16490     const int HighMask[] = {1, 5, 3, 7};
16491     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16492     const int LowMask[] = {0, 4, 2, 6};
16493     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16494   }
16495
16496   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16497   // unsigned multiply.
16498   if (IsSigned && !Subtarget->hasSSE41()) {
16499     SDValue ShAmt =
16500         DAG.getConstant(31, dl,
16501                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16502     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16503                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16504     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16505                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16506
16507     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16508     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16509   }
16510
16511   // The first result of MUL_LOHI is actually the low value, followed by the
16512   // high value.
16513   SDValue Ops[] = {Lows, Highs};
16514   return DAG.getMergeValues(Ops, dl);
16515 }
16516
16517 // Return true if the requred (according to Opcode) shift-imm form is natively
16518 // supported by the Subtarget
16519 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16520                                         unsigned Opcode) {
16521   if (VT.getScalarSizeInBits() < 16)
16522     return false;
16523  
16524   if (VT.is512BitVector() &&
16525       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16526     return true;
16527
16528   bool LShift = VT.is128BitVector() || 
16529     (VT.is256BitVector() && Subtarget->hasInt256());
16530
16531   bool AShift = LShift && (Subtarget->hasVLX() ||
16532     (VT != MVT::v2i64 && VT != MVT::v4i64));
16533   return (Opcode == ISD::SRA) ? AShift : LShift;
16534 }
16535
16536 // The shift amount is a variable, but it is the same for all vector lanes.
16537 // These instrcutions are defined together with shift-immediate.
16538 static 
16539 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16540                                       unsigned Opcode) {
16541   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16542 }
16543
16544 // Return true if the requred (according to Opcode) variable-shift form is
16545 // natively supported by the Subtarget
16546 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16547                                     unsigned Opcode) {
16548
16549   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16550     return false;
16551
16552   // vXi16 supported only on AVX-512, BWI
16553   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16554     return false;
16555
16556   if (VT.is512BitVector() || Subtarget->hasVLX())
16557     return true;
16558
16559   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16560   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16561   return (Opcode == ISD::SRA) ? AShift : LShift;
16562 }
16563
16564 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16565                                          const X86Subtarget *Subtarget) {
16566   MVT VT = Op.getSimpleValueType();
16567   SDLoc dl(Op);
16568   SDValue R = Op.getOperand(0);
16569   SDValue Amt = Op.getOperand(1);
16570
16571   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16572     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16573
16574   // Optimize shl/srl/sra with constant shift amount.
16575   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16576     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16577       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16578
16579       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16580         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16581
16582       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16583         unsigned NumElts = VT.getVectorNumElements();
16584         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16585
16586         if (Op.getOpcode() == ISD::SHL) {
16587           // Simple i8 add case
16588           if (ShiftAmt == 1)
16589             return DAG.getNode(ISD::ADD, dl, VT, R, R);
16590
16591           // Make a large shift.
16592           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16593                                                    R, ShiftAmt, DAG);
16594           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16595           // Zero out the rightmost bits.
16596           SmallVector<SDValue, 32> V(
16597               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16598           return DAG.getNode(ISD::AND, dl, VT, SHL,
16599                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16600         }
16601         if (Op.getOpcode() == ISD::SRL) {
16602           // Make a large shift.
16603           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16604                                                    R, ShiftAmt, DAG);
16605           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16606           // Zero out the leftmost bits.
16607           SmallVector<SDValue, 32> V(
16608               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16609           return DAG.getNode(ISD::AND, dl, VT, SRL,
16610                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16611         }
16612         if (Op.getOpcode() == ISD::SRA) {
16613           if (ShiftAmt == 7) {
16614             // R s>> 7  ===  R s< 0
16615             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16616             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16617           }
16618
16619           // R s>> a === ((R u>> a) ^ m) - m
16620           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16621           SmallVector<SDValue, 32> V(NumElts,
16622                                      DAG.getConstant(128 >> ShiftAmt, dl,
16623                                                      MVT::i8));
16624           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16625           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16626           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16627           return Res;
16628         }
16629         llvm_unreachable("Unknown shift opcode.");
16630       }
16631     }
16632   }
16633
16634   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16635   if (!Subtarget->is64Bit() &&
16636       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16637       Amt.getOpcode() == ISD::BITCAST &&
16638       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16639     Amt = Amt.getOperand(0);
16640     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16641                      VT.getVectorNumElements();
16642     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16643     uint64_t ShiftAmt = 0;
16644     for (unsigned i = 0; i != Ratio; ++i) {
16645       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16646       if (!C)
16647         return SDValue();
16648       // 6 == Log2(64)
16649       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16650     }
16651     // Check remaining shift amounts.
16652     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16653       uint64_t ShAmt = 0;
16654       for (unsigned j = 0; j != Ratio; ++j) {
16655         ConstantSDNode *C =
16656           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16657         if (!C)
16658           return SDValue();
16659         // 6 == Log2(64)
16660         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16661       }
16662       if (ShAmt != ShiftAmt)
16663         return SDValue();
16664     }
16665     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16666   }
16667
16668   return SDValue();
16669 }
16670
16671 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16672                                         const X86Subtarget* Subtarget) {
16673   MVT VT = Op.getSimpleValueType();
16674   SDLoc dl(Op);
16675   SDValue R = Op.getOperand(0);
16676   SDValue Amt = Op.getOperand(1);
16677
16678   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16679     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16680
16681   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16682     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16683
16684   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16685     SDValue BaseShAmt;
16686     EVT EltVT = VT.getVectorElementType();
16687
16688     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16689       // Check if this build_vector node is doing a splat.
16690       // If so, then set BaseShAmt equal to the splat value.
16691       BaseShAmt = BV->getSplatValue();
16692       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16693         BaseShAmt = SDValue();
16694     } else {
16695       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16696         Amt = Amt.getOperand(0);
16697
16698       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16699       if (SVN && SVN->isSplat()) {
16700         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16701         SDValue InVec = Amt.getOperand(0);
16702         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16703           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16704                  "Unexpected shuffle index found!");
16705           BaseShAmt = InVec.getOperand(SplatIdx);
16706         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16707            if (ConstantSDNode *C =
16708                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16709              if (C->getZExtValue() == SplatIdx)
16710                BaseShAmt = InVec.getOperand(1);
16711            }
16712         }
16713
16714         if (!BaseShAmt)
16715           // Avoid introducing an extract element from a shuffle.
16716           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16717                                   DAG.getIntPtrConstant(SplatIdx, dl));
16718       }
16719     }
16720
16721     if (BaseShAmt.getNode()) {
16722       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16723       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16724         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16725       else if (EltVT.bitsLT(MVT::i32))
16726         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16727
16728       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16729     }
16730   }
16731
16732   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16733   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16734       Amt.getOpcode() == ISD::BITCAST &&
16735       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16736     Amt = Amt.getOperand(0);
16737     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16738                      VT.getVectorNumElements();
16739     std::vector<SDValue> Vals(Ratio);
16740     for (unsigned i = 0; i != Ratio; ++i)
16741       Vals[i] = Amt.getOperand(i);
16742     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16743       for (unsigned j = 0; j != Ratio; ++j)
16744         if (Vals[j] != Amt.getOperand(i + j))
16745           return SDValue();
16746     }
16747     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16748   }
16749   return SDValue();
16750 }
16751
16752 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16753                           SelectionDAG &DAG) {
16754   MVT VT = Op.getSimpleValueType();
16755   SDLoc dl(Op);
16756   SDValue R = Op.getOperand(0);
16757   SDValue Amt = Op.getOperand(1);
16758
16759   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16760   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16761
16762   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16763     return V;
16764
16765   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16766       return V;
16767
16768   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16769     return Op;
16770
16771   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16772   // shifts per-lane and then shuffle the partial results back together.
16773   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16774     // Splat the shift amounts so the scalar shifts above will catch it.
16775     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16776     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16777     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16778     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16779     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16780   }
16781
16782   // If possible, lower this packed shift into a vector multiply instead of
16783   // expanding it into a sequence of scalar shifts.
16784   // Do this only if the vector shift count is a constant build_vector.
16785   if (Op.getOpcode() == ISD::SHL &&
16786       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16787        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16788       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16789     SmallVector<SDValue, 8> Elts;
16790     EVT SVT = VT.getScalarType();
16791     unsigned SVTBits = SVT.getSizeInBits();
16792     const APInt &One = APInt(SVTBits, 1);
16793     unsigned NumElems = VT.getVectorNumElements();
16794
16795     for (unsigned i=0; i !=NumElems; ++i) {
16796       SDValue Op = Amt->getOperand(i);
16797       if (Op->getOpcode() == ISD::UNDEF) {
16798         Elts.push_back(Op);
16799         continue;
16800       }
16801
16802       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16803       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16804       uint64_t ShAmt = C.getZExtValue();
16805       if (ShAmt >= SVTBits) {
16806         Elts.push_back(DAG.getUNDEF(SVT));
16807         continue;
16808       }
16809       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16810     }
16811     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16812     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16813   }
16814
16815   // Lower SHL with variable shift amount.
16816   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16817     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16818
16819     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16820                      DAG.getConstant(0x3f800000U, dl, VT));
16821     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16822     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16823     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16824   }
16825
16826   // If possible, lower this shift as a sequence of two shifts by
16827   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16828   // Example:
16829   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16830   //
16831   // Could be rewritten as:
16832   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16833   //
16834   // The advantage is that the two shifts from the example would be
16835   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16836   // the vector shift into four scalar shifts plus four pairs of vector
16837   // insert/extract.
16838   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16839       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16840     unsigned TargetOpcode = X86ISD::MOVSS;
16841     bool CanBeSimplified;
16842     // The splat value for the first packed shift (the 'X' from the example).
16843     SDValue Amt1 = Amt->getOperand(0);
16844     // The splat value for the second packed shift (the 'Y' from the example).
16845     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16846                                         Amt->getOperand(2);
16847
16848     // See if it is possible to replace this node with a sequence of
16849     // two shifts followed by a MOVSS/MOVSD
16850     if (VT == MVT::v4i32) {
16851       // Check if it is legal to use a MOVSS.
16852       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16853                         Amt2 == Amt->getOperand(3);
16854       if (!CanBeSimplified) {
16855         // Otherwise, check if we can still simplify this node using a MOVSD.
16856         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16857                           Amt->getOperand(2) == Amt->getOperand(3);
16858         TargetOpcode = X86ISD::MOVSD;
16859         Amt2 = Amt->getOperand(2);
16860       }
16861     } else {
16862       // Do similar checks for the case where the machine value type
16863       // is MVT::v8i16.
16864       CanBeSimplified = Amt1 == Amt->getOperand(1);
16865       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16866         CanBeSimplified = Amt2 == Amt->getOperand(i);
16867
16868       if (!CanBeSimplified) {
16869         TargetOpcode = X86ISD::MOVSD;
16870         CanBeSimplified = true;
16871         Amt2 = Amt->getOperand(4);
16872         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16873           CanBeSimplified = Amt1 == Amt->getOperand(i);
16874         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16875           CanBeSimplified = Amt2 == Amt->getOperand(j);
16876       }
16877     }
16878
16879     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16880         isa<ConstantSDNode>(Amt2)) {
16881       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16882       EVT CastVT = MVT::v4i32;
16883       SDValue Splat1 =
16884         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16885       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16886       SDValue Splat2 =
16887         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16888       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16889       if (TargetOpcode == X86ISD::MOVSD)
16890         CastVT = MVT::v2i64;
16891       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16892       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16893       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16894                                             BitCast1, DAG);
16895       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16896     }
16897   }
16898
16899   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16900     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16901     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16902
16903     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16904     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16905     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16906
16907     // r = VSELECT(r, shl(r, 4), a);
16908     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16909     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16910
16911     // a += a
16912     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16913     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16914     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16915
16916     // r = VSELECT(r, shl(r, 2), a);
16917     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16918     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16919
16920     // a += a
16921     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16922     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16923     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16924
16925     // return VSELECT(r, r+r, a);
16926     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16927                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16928     return R;
16929   }
16930
16931   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16932   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16933   // solution better.
16934   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16935     MVT ExtVT = MVT::v8i32;
16936     unsigned ExtOpc =
16937         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16938     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
16939     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
16940     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16941                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
16942   }
16943
16944   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
16945     MVT ExtVT = MVT::v8i32;
16946     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
16947     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
16948     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
16949     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
16950     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
16951     ALo = DAG.getNode(ISD::BITCAST, dl, ExtVT, ALo);
16952     AHi = DAG.getNode(ISD::BITCAST, dl, ExtVT, AHi);
16953     RLo = DAG.getNode(ISD::BITCAST, dl, ExtVT, RLo);
16954     RHi = DAG.getNode(ISD::BITCAST, dl, ExtVT, RHi);
16955     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
16956     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
16957     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
16958     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
16959     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
16960   }
16961
16962   // Decompose 256-bit shifts into smaller 128-bit shifts.
16963   if (VT.is256BitVector()) {
16964     unsigned NumElems = VT.getVectorNumElements();
16965     MVT EltVT = VT.getVectorElementType();
16966     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16967
16968     // Extract the two vectors
16969     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16970     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16971
16972     // Recreate the shift amount vectors
16973     SDValue Amt1, Amt2;
16974     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16975       // Constant shift amount
16976       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16977       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16978       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16979
16980       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16981       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16982     } else {
16983       // Variable shift amount
16984       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16985       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16986     }
16987
16988     // Issue new vector shifts for the smaller types
16989     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16990     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16991
16992     // Concatenate the result back
16993     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16994   }
16995
16996   return SDValue();
16997 }
16998
16999 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17000   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17001   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17002   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17003   // has only one use.
17004   SDNode *N = Op.getNode();
17005   SDValue LHS = N->getOperand(0);
17006   SDValue RHS = N->getOperand(1);
17007   unsigned BaseOp = 0;
17008   unsigned Cond = 0;
17009   SDLoc DL(Op);
17010   switch (Op.getOpcode()) {
17011   default: llvm_unreachable("Unknown ovf instruction!");
17012   case ISD::SADDO:
17013     // A subtract of one will be selected as a INC. Note that INC doesn't
17014     // set CF, so we can't do this for UADDO.
17015     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17016       if (C->isOne()) {
17017         BaseOp = X86ISD::INC;
17018         Cond = X86::COND_O;
17019         break;
17020       }
17021     BaseOp = X86ISD::ADD;
17022     Cond = X86::COND_O;
17023     break;
17024   case ISD::UADDO:
17025     BaseOp = X86ISD::ADD;
17026     Cond = X86::COND_B;
17027     break;
17028   case ISD::SSUBO:
17029     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17030     // set CF, so we can't do this for USUBO.
17031     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17032       if (C->isOne()) {
17033         BaseOp = X86ISD::DEC;
17034         Cond = X86::COND_O;
17035         break;
17036       }
17037     BaseOp = X86ISD::SUB;
17038     Cond = X86::COND_O;
17039     break;
17040   case ISD::USUBO:
17041     BaseOp = X86ISD::SUB;
17042     Cond = X86::COND_B;
17043     break;
17044   case ISD::SMULO:
17045     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17046     Cond = X86::COND_O;
17047     break;
17048   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17049     if (N->getValueType(0) == MVT::i8) {
17050       BaseOp = X86ISD::UMUL8;
17051       Cond = X86::COND_O;
17052       break;
17053     }
17054     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17055                                  MVT::i32);
17056     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17057
17058     SDValue SetCC =
17059       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17060                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17061                   SDValue(Sum.getNode(), 2));
17062
17063     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17064   }
17065   }
17066
17067   // Also sets EFLAGS.
17068   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17069   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17070
17071   SDValue SetCC =
17072     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17073                 DAG.getConstant(Cond, DL, MVT::i32),
17074                 SDValue(Sum.getNode(), 1));
17075
17076   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17077 }
17078
17079 /// Returns true if the operand type is exactly twice the native width, and
17080 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17081 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17082 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17083 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17084   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17085
17086   if (OpWidth == 64)
17087     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17088   else if (OpWidth == 128)
17089     return Subtarget->hasCmpxchg16b();
17090   else
17091     return false;
17092 }
17093
17094 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17095   return needsCmpXchgNb(SI->getValueOperand()->getType());
17096 }
17097
17098 // Note: this turns large loads into lock cmpxchg8b/16b.
17099 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17100 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17101   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17102   return needsCmpXchgNb(PTy->getElementType());
17103 }
17104
17105 TargetLoweringBase::AtomicRMWExpansionKind
17106 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17107   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17108   const Type *MemType = AI->getType();
17109
17110   // If the operand is too big, we must see if cmpxchg8/16b is available
17111   // and default to library calls otherwise.
17112   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17113     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17114                                    : AtomicRMWExpansionKind::None;
17115   }
17116
17117   AtomicRMWInst::BinOp Op = AI->getOperation();
17118   switch (Op) {
17119   default:
17120     llvm_unreachable("Unknown atomic operation");
17121   case AtomicRMWInst::Xchg:
17122   case AtomicRMWInst::Add:
17123   case AtomicRMWInst::Sub:
17124     // It's better to use xadd, xsub or xchg for these in all cases.
17125     return AtomicRMWExpansionKind::None;
17126   case AtomicRMWInst::Or:
17127   case AtomicRMWInst::And:
17128   case AtomicRMWInst::Xor:
17129     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17130     // prefix to a normal instruction for these operations.
17131     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17132                             : AtomicRMWExpansionKind::None;
17133   case AtomicRMWInst::Nand:
17134   case AtomicRMWInst::Max:
17135   case AtomicRMWInst::Min:
17136   case AtomicRMWInst::UMax:
17137   case AtomicRMWInst::UMin:
17138     // These always require a non-trivial set of data operations on x86. We must
17139     // use a cmpxchg loop.
17140     return AtomicRMWExpansionKind::CmpXChg;
17141   }
17142 }
17143
17144 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17145   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17146   // no-sse2). There isn't any reason to disable it if the target processor
17147   // supports it.
17148   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17149 }
17150
17151 LoadInst *
17152 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17153   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17154   const Type *MemType = AI->getType();
17155   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17156   // there is no benefit in turning such RMWs into loads, and it is actually
17157   // harmful as it introduces a mfence.
17158   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17159     return nullptr;
17160
17161   auto Builder = IRBuilder<>(AI);
17162   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17163   auto SynchScope = AI->getSynchScope();
17164   // We must restrict the ordering to avoid generating loads with Release or
17165   // ReleaseAcquire orderings.
17166   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17167   auto Ptr = AI->getPointerOperand();
17168
17169   // Before the load we need a fence. Here is an example lifted from
17170   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17171   // is required:
17172   // Thread 0:
17173   //   x.store(1, relaxed);
17174   //   r1 = y.fetch_add(0, release);
17175   // Thread 1:
17176   //   y.fetch_add(42, acquire);
17177   //   r2 = x.load(relaxed);
17178   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17179   // lowered to just a load without a fence. A mfence flushes the store buffer,
17180   // making the optimization clearly correct.
17181   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17182   // otherwise, we might be able to be more agressive on relaxed idempotent
17183   // rmw. In practice, they do not look useful, so we don't try to be
17184   // especially clever.
17185   if (SynchScope == SingleThread)
17186     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17187     // the IR level, so we must wrap it in an intrinsic.
17188     return nullptr;
17189
17190   if (!hasMFENCE(*Subtarget))
17191     // FIXME: it might make sense to use a locked operation here but on a
17192     // different cache-line to prevent cache-line bouncing. In practice it
17193     // is probably a small win, and x86 processors without mfence are rare
17194     // enough that we do not bother.
17195     return nullptr;
17196
17197   Function *MFence =
17198       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17199   Builder.CreateCall(MFence, {});
17200
17201   // Finally we can emit the atomic load.
17202   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17203           AI->getType()->getPrimitiveSizeInBits());
17204   Loaded->setAtomic(Order, SynchScope);
17205   AI->replaceAllUsesWith(Loaded);
17206   AI->eraseFromParent();
17207   return Loaded;
17208 }
17209
17210 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17211                                  SelectionDAG &DAG) {
17212   SDLoc dl(Op);
17213   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17214     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17215   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17216     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17217
17218   // The only fence that needs an instruction is a sequentially-consistent
17219   // cross-thread fence.
17220   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17221     if (hasMFENCE(*Subtarget))
17222       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17223
17224     SDValue Chain = Op.getOperand(0);
17225     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17226     SDValue Ops[] = {
17227       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17228       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17229       DAG.getRegister(0, MVT::i32),            // Index
17230       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17231       DAG.getRegister(0, MVT::i32),            // Segment.
17232       Zero,
17233       Chain
17234     };
17235     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17236     return SDValue(Res, 0);
17237   }
17238
17239   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17240   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17241 }
17242
17243 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17244                              SelectionDAG &DAG) {
17245   MVT T = Op.getSimpleValueType();
17246   SDLoc DL(Op);
17247   unsigned Reg = 0;
17248   unsigned size = 0;
17249   switch(T.SimpleTy) {
17250   default: llvm_unreachable("Invalid value type!");
17251   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17252   case MVT::i16: Reg = X86::AX;  size = 2; break;
17253   case MVT::i32: Reg = X86::EAX; size = 4; break;
17254   case MVT::i64:
17255     assert(Subtarget->is64Bit() && "Node not type legal!");
17256     Reg = X86::RAX; size = 8;
17257     break;
17258   }
17259   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17260                                   Op.getOperand(2), SDValue());
17261   SDValue Ops[] = { cpIn.getValue(0),
17262                     Op.getOperand(1),
17263                     Op.getOperand(3),
17264                     DAG.getTargetConstant(size, DL, MVT::i8),
17265                     cpIn.getValue(1) };
17266   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17267   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17268   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17269                                            Ops, T, MMO);
17270
17271   SDValue cpOut =
17272     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17273   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17274                                       MVT::i32, cpOut.getValue(2));
17275   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17276                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17277                                 EFLAGS);
17278
17279   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17280   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17281   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17282   return SDValue();
17283 }
17284
17285 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17286                             SelectionDAG &DAG) {
17287   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17288   MVT DstVT = Op.getSimpleValueType();
17289
17290   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17291     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17292     if (DstVT != MVT::f64)
17293       // This conversion needs to be expanded.
17294       return SDValue();
17295
17296     SDValue InVec = Op->getOperand(0);
17297     SDLoc dl(Op);
17298     unsigned NumElts = SrcVT.getVectorNumElements();
17299     EVT SVT = SrcVT.getVectorElementType();
17300
17301     // Widen the vector in input in the case of MVT::v2i32.
17302     // Example: from MVT::v2i32 to MVT::v4i32.
17303     SmallVector<SDValue, 16> Elts;
17304     for (unsigned i = 0, e = NumElts; i != e; ++i)
17305       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17306                                  DAG.getIntPtrConstant(i, dl)));
17307
17308     // Explicitly mark the extra elements as Undef.
17309     Elts.append(NumElts, DAG.getUNDEF(SVT));
17310
17311     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17312     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17313     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17314     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17315                        DAG.getIntPtrConstant(0, dl));
17316   }
17317
17318   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17319          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17320   assert((DstVT == MVT::i64 ||
17321           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17322          "Unexpected custom BITCAST");
17323   // i64 <=> MMX conversions are Legal.
17324   if (SrcVT==MVT::i64 && DstVT.isVector())
17325     return Op;
17326   if (DstVT==MVT::i64 && SrcVT.isVector())
17327     return Op;
17328   // MMX <=> MMX conversions are Legal.
17329   if (SrcVT.isVector() && DstVT.isVector())
17330     return Op;
17331   // All other conversions need to be expanded.
17332   return SDValue();
17333 }
17334
17335 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17336                           SelectionDAG &DAG) {
17337   SDNode *Node = Op.getNode();
17338   SDLoc dl(Node);
17339
17340   Op = Op.getOperand(0);
17341   EVT VT = Op.getValueType();
17342   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17343          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17344
17345   unsigned NumElts = VT.getVectorNumElements();
17346   EVT EltVT = VT.getVectorElementType();
17347   unsigned Len = EltVT.getSizeInBits();
17348
17349   // This is the vectorized version of the "best" algorithm from
17350   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17351   // with a minor tweak to use a series of adds + shifts instead of vector
17352   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17353   //
17354   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17355   //  v8i32 => Always profitable
17356   //
17357   // FIXME: There a couple of possible improvements:
17358   //
17359   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17360   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17361   //
17362   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17363          "CTPOP not implemented for this vector element type.");
17364
17365   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17366   // extra legalization.
17367   bool NeedsBitcast = EltVT == MVT::i32;
17368   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17369
17370   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17371                                   EltVT);
17372   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17373                                   EltVT);
17374   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17375                                   EltVT);
17376
17377   // v = v - ((v >> 1) & 0x55555555...)
17378   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17379   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17380   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17381   if (NeedsBitcast)
17382     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17383
17384   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17385   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17386   if (NeedsBitcast)
17387     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17388
17389   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17390   if (VT != And.getValueType())
17391     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17392   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17393
17394   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17395   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17396   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17397   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17398   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17399
17400   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17401   if (NeedsBitcast) {
17402     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17403     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17404     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17405   }
17406
17407   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17408   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17409   if (VT != AndRHS.getValueType()) {
17410     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17411     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17412   }
17413   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17414
17415   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17416   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17417   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17418   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17419   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17420
17421   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17422   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17423   if (NeedsBitcast) {
17424     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17425     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17426   }
17427   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17428   if (VT != And.getValueType())
17429     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17430
17431   // The algorithm mentioned above uses:
17432   //    v = (v * 0x01010101...) >> (Len - 8)
17433   //
17434   // Change it to use vector adds + vector shifts which yield faster results on
17435   // Haswell than using vector integer multiplication.
17436   //
17437   // For i32 elements:
17438   //    v = v + (v >> 8)
17439   //    v = v + (v >> 16)
17440   //
17441   // For i64 elements:
17442   //    v = v + (v >> 8)
17443   //    v = v + (v >> 16)
17444   //    v = v + (v >> 32)
17445   //
17446   Add = And;
17447   SmallVector<SDValue, 8> Csts;
17448   for (unsigned i = 8; i <= Len/2; i *= 2) {
17449     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17450     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17451     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17452     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17453     Csts.clear();
17454   }
17455
17456   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17457   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17458                                   EltVT);
17459   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17460   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17461   if (NeedsBitcast) {
17462     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17463     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17464   }
17465   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17466   if (VT != And.getValueType())
17467     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17468
17469   return And;
17470 }
17471
17472 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17473   SDNode *Node = Op.getNode();
17474   SDLoc dl(Node);
17475   EVT T = Node->getValueType(0);
17476   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17477                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17478   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17479                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17480                        Node->getOperand(0),
17481                        Node->getOperand(1), negOp,
17482                        cast<AtomicSDNode>(Node)->getMemOperand(),
17483                        cast<AtomicSDNode>(Node)->getOrdering(),
17484                        cast<AtomicSDNode>(Node)->getSynchScope());
17485 }
17486
17487 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17488   SDNode *Node = Op.getNode();
17489   SDLoc dl(Node);
17490   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17491
17492   // Convert seq_cst store -> xchg
17493   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17494   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17495   //        (The only way to get a 16-byte store is cmpxchg16b)
17496   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17497   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17498       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17499     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17500                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17501                                  Node->getOperand(0),
17502                                  Node->getOperand(1), Node->getOperand(2),
17503                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17504                                  cast<AtomicSDNode>(Node)->getOrdering(),
17505                                  cast<AtomicSDNode>(Node)->getSynchScope());
17506     return Swap.getValue(1);
17507   }
17508   // Other atomic stores have a simple pattern.
17509   return Op;
17510 }
17511
17512 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17513   EVT VT = Op.getNode()->getSimpleValueType(0);
17514
17515   // Let legalize expand this if it isn't a legal type yet.
17516   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17517     return SDValue();
17518
17519   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17520
17521   unsigned Opc;
17522   bool ExtraOp = false;
17523   switch (Op.getOpcode()) {
17524   default: llvm_unreachable("Invalid code");
17525   case ISD::ADDC: Opc = X86ISD::ADD; break;
17526   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17527   case ISD::SUBC: Opc = X86ISD::SUB; break;
17528   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17529   }
17530
17531   if (!ExtraOp)
17532     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17533                        Op.getOperand(1));
17534   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17535                      Op.getOperand(1), Op.getOperand(2));
17536 }
17537
17538 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17539                             SelectionDAG &DAG) {
17540   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17541
17542   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17543   // which returns the values as { float, float } (in XMM0) or
17544   // { double, double } (which is returned in XMM0, XMM1).
17545   SDLoc dl(Op);
17546   SDValue Arg = Op.getOperand(0);
17547   EVT ArgVT = Arg.getValueType();
17548   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17549
17550   TargetLowering::ArgListTy Args;
17551   TargetLowering::ArgListEntry Entry;
17552
17553   Entry.Node = Arg;
17554   Entry.Ty = ArgTy;
17555   Entry.isSExt = false;
17556   Entry.isZExt = false;
17557   Args.push_back(Entry);
17558
17559   bool isF64 = ArgVT == MVT::f64;
17560   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17561   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17562   // the results are returned via SRet in memory.
17563   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17564   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17565   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17566
17567   Type *RetTy = isF64
17568     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17569     : (Type*)VectorType::get(ArgTy, 4);
17570
17571   TargetLowering::CallLoweringInfo CLI(DAG);
17572   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17573     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17574
17575   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17576
17577   if (isF64)
17578     // Returned in xmm0 and xmm1.
17579     return CallResult.first;
17580
17581   // Returned in bits 0:31 and 32:64 xmm0.
17582   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17583                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17584   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17585                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17586   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17587   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17588 }
17589
17590 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17591                              SelectionDAG &DAG) {
17592   assert(Subtarget->hasAVX512() &&
17593          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17594
17595   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17596   EVT VT = N->getValue().getValueType();
17597   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17598   SDLoc dl(Op);
17599
17600   // X86 scatter kills mask register, so its type should be added to
17601   // the list of return values
17602   if (N->getNumValues() == 1) {
17603     SDValue Index = N->getIndex();
17604     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17605         !Index.getValueType().is512BitVector())
17606       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17607
17608     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17609     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17610                       N->getOperand(3), Index };
17611
17612     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17613     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17614     return SDValue(NewScatter.getNode(), 0);
17615   }
17616   return Op;
17617 }
17618
17619 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17620                             SelectionDAG &DAG) {
17621   assert(Subtarget->hasAVX512() &&
17622          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17623
17624   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17625   EVT VT = Op.getValueType();
17626   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17627   SDLoc dl(Op);
17628
17629   SDValue Index = N->getIndex();
17630   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17631       !Index.getValueType().is512BitVector()) {
17632     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17633     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17634                       N->getOperand(3), Index };
17635     DAG.UpdateNodeOperands(N, Ops);
17636   }
17637   return Op;
17638 }
17639
17640 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17641                                                     SelectionDAG &DAG) const {
17642   // TODO: Eventually, the lowering of these nodes should be informed by or
17643   // deferred to the GC strategy for the function in which they appear. For
17644   // now, however, they must be lowered to something. Since they are logically
17645   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17646   // require special handling for these nodes), lower them as literal NOOPs for
17647   // the time being.
17648   SmallVector<SDValue, 2> Ops;
17649
17650   Ops.push_back(Op.getOperand(0));
17651   if (Op->getGluedNode())
17652     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17653
17654   SDLoc OpDL(Op);
17655   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17656   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17657
17658   return NOOP;
17659 }
17660
17661 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17662                                                   SelectionDAG &DAG) const {
17663   // TODO: Eventually, the lowering of these nodes should be informed by or
17664   // deferred to the GC strategy for the function in which they appear. For
17665   // now, however, they must be lowered to something. Since they are logically
17666   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17667   // require special handling for these nodes), lower them as literal NOOPs for
17668   // the time being.
17669   SmallVector<SDValue, 2> Ops;
17670
17671   Ops.push_back(Op.getOperand(0));
17672   if (Op->getGluedNode())
17673     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17674
17675   SDLoc OpDL(Op);
17676   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17677   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17678
17679   return NOOP;
17680 }
17681
17682 /// LowerOperation - Provide custom lowering hooks for some operations.
17683 ///
17684 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17685   switch (Op.getOpcode()) {
17686   default: llvm_unreachable("Should not custom lower this!");
17687   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17688   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17689     return LowerCMP_SWAP(Op, Subtarget, DAG);
17690   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17691   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17692   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17693   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17694   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17695   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17696   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17697   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17698   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17699   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17700   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17701   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17702   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17703   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17704   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17705   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17706   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17707   case ISD::SHL_PARTS:
17708   case ISD::SRA_PARTS:
17709   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17710   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17711   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17712   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17713   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17714   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17715   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17716   case ISD::SIGN_EXTEND_VECTOR_INREG:
17717     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
17718   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17719   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17720   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17721   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17722   case ISD::FABS:
17723   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17724   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17725   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17726   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17727   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17728   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17729   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17730   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17731   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17732   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17733   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17734   case ISD::INTRINSIC_VOID:
17735   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17736   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17737   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17738   case ISD::FRAME_TO_ARGS_OFFSET:
17739                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17740   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17741   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17742   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17743   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17744   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17745   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17746   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17747   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17748   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17749   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17750   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17751   case ISD::UMUL_LOHI:
17752   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17753   case ISD::SRA:
17754   case ISD::SRL:
17755   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17756   case ISD::SADDO:
17757   case ISD::UADDO:
17758   case ISD::SSUBO:
17759   case ISD::USUBO:
17760   case ISD::SMULO:
17761   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17762   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17763   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17764   case ISD::ADDC:
17765   case ISD::ADDE:
17766   case ISD::SUBC:
17767   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17768   case ISD::ADD:                return LowerADD(Op, DAG);
17769   case ISD::SUB:                return LowerSUB(Op, DAG);
17770   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17771   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17772   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17773   case ISD::GC_TRANSITION_START:
17774                                 return LowerGC_TRANSITION_START(Op, DAG);
17775   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17776   }
17777 }
17778
17779 /// ReplaceNodeResults - Replace a node with an illegal result type
17780 /// with a new node built out of custom code.
17781 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17782                                            SmallVectorImpl<SDValue>&Results,
17783                                            SelectionDAG &DAG) const {
17784   SDLoc dl(N);
17785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17786   switch (N->getOpcode()) {
17787   default:
17788     llvm_unreachable("Do not know how to custom type legalize this operation!");
17789   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17790   case X86ISD::FMINC:
17791   case X86ISD::FMIN:
17792   case X86ISD::FMAXC:
17793   case X86ISD::FMAX: {
17794     EVT VT = N->getValueType(0);
17795     if (VT != MVT::v2f32)
17796       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17797     SDValue UNDEF = DAG.getUNDEF(VT);
17798     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17799                               N->getOperand(0), UNDEF);
17800     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17801                               N->getOperand(1), UNDEF);
17802     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17803     return;
17804   }
17805   case ISD::SIGN_EXTEND_INREG:
17806   case ISD::ADDC:
17807   case ISD::ADDE:
17808   case ISD::SUBC:
17809   case ISD::SUBE:
17810     // We don't want to expand or promote these.
17811     return;
17812   case ISD::SDIV:
17813   case ISD::UDIV:
17814   case ISD::SREM:
17815   case ISD::UREM:
17816   case ISD::SDIVREM:
17817   case ISD::UDIVREM: {
17818     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17819     Results.push_back(V);
17820     return;
17821   }
17822   case ISD::FP_TO_SINT:
17823     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17824     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17825     if (N->getOperand(0).getValueType() == MVT::f16)
17826       break;
17827     // fallthrough
17828   case ISD::FP_TO_UINT: {
17829     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17830
17831     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17832       return;
17833
17834     std::pair<SDValue,SDValue> Vals =
17835         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17836     SDValue FIST = Vals.first, StackSlot = Vals.second;
17837     if (FIST.getNode()) {
17838       EVT VT = N->getValueType(0);
17839       // Return a load from the stack slot.
17840       if (StackSlot.getNode())
17841         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17842                                       MachinePointerInfo(),
17843                                       false, false, false, 0));
17844       else
17845         Results.push_back(FIST);
17846     }
17847     return;
17848   }
17849   case ISD::UINT_TO_FP: {
17850     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17851     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17852         N->getValueType(0) != MVT::v2f32)
17853       return;
17854     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17855                                  N->getOperand(0));
17856     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17857                                      MVT::f64);
17858     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17859     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17860                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17861     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17862     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17863     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17864     return;
17865   }
17866   case ISD::FP_ROUND: {
17867     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17868         return;
17869     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17870     Results.push_back(V);
17871     return;
17872   }
17873   case ISD::FP_EXTEND: {
17874     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17875     // No other ValueType for FP_EXTEND should reach this point.
17876     assert(N->getValueType(0) == MVT::v2f32 &&
17877            "Do not know how to legalize this Node");
17878     return;
17879   }
17880   case ISD::INTRINSIC_W_CHAIN: {
17881     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17882     switch (IntNo) {
17883     default : llvm_unreachable("Do not know how to custom type "
17884                                "legalize this intrinsic operation!");
17885     case Intrinsic::x86_rdtsc:
17886       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17887                                      Results);
17888     case Intrinsic::x86_rdtscp:
17889       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17890                                      Results);
17891     case Intrinsic::x86_rdpmc:
17892       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17893     }
17894   }
17895   case ISD::READCYCLECOUNTER: {
17896     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17897                                    Results);
17898   }
17899   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17900     EVT T = N->getValueType(0);
17901     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17902     bool Regs64bit = T == MVT::i128;
17903     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17904     SDValue cpInL, cpInH;
17905     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17906                         DAG.getConstant(0, dl, HalfT));
17907     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17908                         DAG.getConstant(1, dl, HalfT));
17909     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17910                              Regs64bit ? X86::RAX : X86::EAX,
17911                              cpInL, SDValue());
17912     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17913                              Regs64bit ? X86::RDX : X86::EDX,
17914                              cpInH, cpInL.getValue(1));
17915     SDValue swapInL, swapInH;
17916     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17917                           DAG.getConstant(0, dl, HalfT));
17918     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17919                           DAG.getConstant(1, dl, HalfT));
17920     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17921                                Regs64bit ? X86::RBX : X86::EBX,
17922                                swapInL, cpInH.getValue(1));
17923     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17924                                Regs64bit ? X86::RCX : X86::ECX,
17925                                swapInH, swapInL.getValue(1));
17926     SDValue Ops[] = { swapInH.getValue(0),
17927                       N->getOperand(1),
17928                       swapInH.getValue(1) };
17929     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17930     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17931     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17932                                   X86ISD::LCMPXCHG8_DAG;
17933     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17934     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17935                                         Regs64bit ? X86::RAX : X86::EAX,
17936                                         HalfT, Result.getValue(1));
17937     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17938                                         Regs64bit ? X86::RDX : X86::EDX,
17939                                         HalfT, cpOutL.getValue(2));
17940     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17941
17942     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17943                                         MVT::i32, cpOutH.getValue(2));
17944     SDValue Success =
17945         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17946                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17947     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17948
17949     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17950     Results.push_back(Success);
17951     Results.push_back(EFLAGS.getValue(1));
17952     return;
17953   }
17954   case ISD::ATOMIC_SWAP:
17955   case ISD::ATOMIC_LOAD_ADD:
17956   case ISD::ATOMIC_LOAD_SUB:
17957   case ISD::ATOMIC_LOAD_AND:
17958   case ISD::ATOMIC_LOAD_OR:
17959   case ISD::ATOMIC_LOAD_XOR:
17960   case ISD::ATOMIC_LOAD_NAND:
17961   case ISD::ATOMIC_LOAD_MIN:
17962   case ISD::ATOMIC_LOAD_MAX:
17963   case ISD::ATOMIC_LOAD_UMIN:
17964   case ISD::ATOMIC_LOAD_UMAX:
17965   case ISD::ATOMIC_LOAD: {
17966     // Delegate to generic TypeLegalization. Situations we can really handle
17967     // should have already been dealt with by AtomicExpandPass.cpp.
17968     break;
17969   }
17970   case ISD::BITCAST: {
17971     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17972     EVT DstVT = N->getValueType(0);
17973     EVT SrcVT = N->getOperand(0)->getValueType(0);
17974
17975     if (SrcVT != MVT::f64 ||
17976         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17977       return;
17978
17979     unsigned NumElts = DstVT.getVectorNumElements();
17980     EVT SVT = DstVT.getVectorElementType();
17981     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17982     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17983                                    MVT::v2f64, N->getOperand(0));
17984     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17985
17986     if (ExperimentalVectorWideningLegalization) {
17987       // If we are legalizing vectors by widening, we already have the desired
17988       // legal vector type, just return it.
17989       Results.push_back(ToVecInt);
17990       return;
17991     }
17992
17993     SmallVector<SDValue, 8> Elts;
17994     for (unsigned i = 0, e = NumElts; i != e; ++i)
17995       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17996                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17997
17998     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17999   }
18000   }
18001 }
18002
18003 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18004   switch ((X86ISD::NodeType)Opcode) {
18005   case X86ISD::FIRST_NUMBER:       break;
18006   case X86ISD::BSF:                return "X86ISD::BSF";
18007   case X86ISD::BSR:                return "X86ISD::BSR";
18008   case X86ISD::SHLD:               return "X86ISD::SHLD";
18009   case X86ISD::SHRD:               return "X86ISD::SHRD";
18010   case X86ISD::FAND:               return "X86ISD::FAND";
18011   case X86ISD::FANDN:              return "X86ISD::FANDN";
18012   case X86ISD::FOR:                return "X86ISD::FOR";
18013   case X86ISD::FXOR:               return "X86ISD::FXOR";
18014   case X86ISD::FSRL:               return "X86ISD::FSRL";
18015   case X86ISD::FILD:               return "X86ISD::FILD";
18016   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18017   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18018   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18019   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18020   case X86ISD::FLD:                return "X86ISD::FLD";
18021   case X86ISD::FST:                return "X86ISD::FST";
18022   case X86ISD::CALL:               return "X86ISD::CALL";
18023   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18024   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18025   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18026   case X86ISD::BT:                 return "X86ISD::BT";
18027   case X86ISD::CMP:                return "X86ISD::CMP";
18028   case X86ISD::COMI:               return "X86ISD::COMI";
18029   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18030   case X86ISD::CMPM:               return "X86ISD::CMPM";
18031   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18032   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18033   case X86ISD::SETCC:              return "X86ISD::SETCC";
18034   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18035   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18036   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18037   case X86ISD::CMOV:               return "X86ISD::CMOV";
18038   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18039   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18040   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18041   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18042   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18043   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18044   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18045   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18046   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18047   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18048   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18049   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18050   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18051   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18052   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18053   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18054   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18055   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18056   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18057   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18058   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18059   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18060   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18061   case X86ISD::HADD:               return "X86ISD::HADD";
18062   case X86ISD::HSUB:               return "X86ISD::HSUB";
18063   case X86ISD::FHADD:              return "X86ISD::FHADD";
18064   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18065   case X86ISD::UMAX:               return "X86ISD::UMAX";
18066   case X86ISD::UMIN:               return "X86ISD::UMIN";
18067   case X86ISD::SMAX:               return "X86ISD::SMAX";
18068   case X86ISD::SMIN:               return "X86ISD::SMIN";
18069   case X86ISD::FMAX:               return "X86ISD::FMAX";
18070   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18071   case X86ISD::FMIN:               return "X86ISD::FMIN";
18072   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18073   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18074   case X86ISD::FMINC:              return "X86ISD::FMINC";
18075   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18076   case X86ISD::FRCP:               return "X86ISD::FRCP";
18077   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18078   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18079   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18080   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18081   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18082   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18083   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18084   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18085   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18086   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18087   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18088   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18089   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18090   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18091   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18092   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18093   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18094   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18095   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18096   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18097   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18098   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18099   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18100   case X86ISD::VSHL:               return "X86ISD::VSHL";
18101   case X86ISD::VSRL:               return "X86ISD::VSRL";
18102   case X86ISD::VSRA:               return "X86ISD::VSRA";
18103   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18104   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18105   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18106   case X86ISD::CMPP:               return "X86ISD::CMPP";
18107   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18108   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18109   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18110   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18111   case X86ISD::ADD:                return "X86ISD::ADD";
18112   case X86ISD::SUB:                return "X86ISD::SUB";
18113   case X86ISD::ADC:                return "X86ISD::ADC";
18114   case X86ISD::SBB:                return "X86ISD::SBB";
18115   case X86ISD::SMUL:               return "X86ISD::SMUL";
18116   case X86ISD::UMUL:               return "X86ISD::UMUL";
18117   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18118   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18119   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18120   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18121   case X86ISD::INC:                return "X86ISD::INC";
18122   case X86ISD::DEC:                return "X86ISD::DEC";
18123   case X86ISD::OR:                 return "X86ISD::OR";
18124   case X86ISD::XOR:                return "X86ISD::XOR";
18125   case X86ISD::AND:                return "X86ISD::AND";
18126   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18127   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18128   case X86ISD::PTEST:              return "X86ISD::PTEST";
18129   case X86ISD::TESTP:              return "X86ISD::TESTP";
18130   case X86ISD::TESTM:              return "X86ISD::TESTM";
18131   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18132   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18133   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18134   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18135   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18136   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18137   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18138   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18139   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18140   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18141   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18142   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18143   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18144   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18145   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18146   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18147   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18148   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18149   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18150   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18151   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18152   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18153   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18154   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18155   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18156   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18157   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18158   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18159   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18160   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18161   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18162   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18163   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18164   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18165   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18166   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18167   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18168   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18169   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18170   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18171   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18172   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18173   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18174   case X86ISD::SAHF:               return "X86ISD::SAHF";
18175   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18176   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18177   case X86ISD::FMADD:              return "X86ISD::FMADD";
18178   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18179   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18180   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18181   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18182   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18183   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18184   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18185   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18186   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18187   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18188   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18189   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18190   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18191   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18192   case X86ISD::XTEST:              return "X86ISD::XTEST";
18193   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18194   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18195   case X86ISD::SELECT:             return "X86ISD::SELECT";
18196   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18197   case X86ISD::RCP28:              return "X86ISD::RCP28";
18198   case X86ISD::EXP2:               return "X86ISD::EXP2";
18199   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18200   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18201   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18202   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18203   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18204   case X86ISD::ADDS:               return "X86ISD::ADDS";
18205   case X86ISD::SUBS:               return "X86ISD::SUBS";
18206   }
18207   return nullptr;
18208 }
18209
18210 // isLegalAddressingMode - Return true if the addressing mode represented
18211 // by AM is legal for this target, for a load/store of the specified type.
18212 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18213                                               Type *Ty) const {
18214   // X86 supports extremely general addressing modes.
18215   CodeModel::Model M = getTargetMachine().getCodeModel();
18216   Reloc::Model R = getTargetMachine().getRelocationModel();
18217
18218   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18219   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18220     return false;
18221
18222   if (AM.BaseGV) {
18223     unsigned GVFlags =
18224       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18225
18226     // If a reference to this global requires an extra load, we can't fold it.
18227     if (isGlobalStubReference(GVFlags))
18228       return false;
18229
18230     // If BaseGV requires a register for the PIC base, we cannot also have a
18231     // BaseReg specified.
18232     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18233       return false;
18234
18235     // If lower 4G is not available, then we must use rip-relative addressing.
18236     if ((M != CodeModel::Small || R != Reloc::Static) &&
18237         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18238       return false;
18239   }
18240
18241   switch (AM.Scale) {
18242   case 0:
18243   case 1:
18244   case 2:
18245   case 4:
18246   case 8:
18247     // These scales always work.
18248     break;
18249   case 3:
18250   case 5:
18251   case 9:
18252     // These scales are formed with basereg+scalereg.  Only accept if there is
18253     // no basereg yet.
18254     if (AM.HasBaseReg)
18255       return false;
18256     break;
18257   default:  // Other stuff never works.
18258     return false;
18259   }
18260
18261   return true;
18262 }
18263
18264 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18265   unsigned Bits = Ty->getScalarSizeInBits();
18266
18267   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18268   // particularly cheaper than those without.
18269   if (Bits == 8)
18270     return false;
18271
18272   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18273   // variable shifts just as cheap as scalar ones.
18274   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18275     return false;
18276
18277   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18278   // fully general vector.
18279   return true;
18280 }
18281
18282 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18283   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18284     return false;
18285   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18286   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18287   return NumBits1 > NumBits2;
18288 }
18289
18290 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18291   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18292     return false;
18293
18294   if (!isTypeLegal(EVT::getEVT(Ty1)))
18295     return false;
18296
18297   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18298
18299   // Assuming the caller doesn't have a zeroext or signext return parameter,
18300   // truncation all the way down to i1 is valid.
18301   return true;
18302 }
18303
18304 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18305   return isInt<32>(Imm);
18306 }
18307
18308 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18309   // Can also use sub to handle negated immediates.
18310   return isInt<32>(Imm);
18311 }
18312
18313 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18314   if (!VT1.isInteger() || !VT2.isInteger())
18315     return false;
18316   unsigned NumBits1 = VT1.getSizeInBits();
18317   unsigned NumBits2 = VT2.getSizeInBits();
18318   return NumBits1 > NumBits2;
18319 }
18320
18321 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18322   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18323   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18324 }
18325
18326 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18327   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18328   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18329 }
18330
18331 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18332   EVT VT1 = Val.getValueType();
18333   if (isZExtFree(VT1, VT2))
18334     return true;
18335
18336   if (Val.getOpcode() != ISD::LOAD)
18337     return false;
18338
18339   if (!VT1.isSimple() || !VT1.isInteger() ||
18340       !VT2.isSimple() || !VT2.isInteger())
18341     return false;
18342
18343   switch (VT1.getSimpleVT().SimpleTy) {
18344   default: break;
18345   case MVT::i8:
18346   case MVT::i16:
18347   case MVT::i32:
18348     // X86 has 8, 16, and 32-bit zero-extending loads.
18349     return true;
18350   }
18351
18352   return false;
18353 }
18354
18355 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18356
18357 bool
18358 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18359   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18360     return false;
18361
18362   VT = VT.getScalarType();
18363
18364   if (!VT.isSimple())
18365     return false;
18366
18367   switch (VT.getSimpleVT().SimpleTy) {
18368   case MVT::f32:
18369   case MVT::f64:
18370     return true;
18371   default:
18372     break;
18373   }
18374
18375   return false;
18376 }
18377
18378 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18379   // i16 instructions are longer (0x66 prefix) and potentially slower.
18380   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18381 }
18382
18383 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18384 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18385 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18386 /// are assumed to be legal.
18387 bool
18388 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18389                                       EVT VT) const {
18390   if (!VT.isSimple())
18391     return false;
18392
18393   // Not for i1 vectors
18394   if (VT.getScalarType() == MVT::i1)
18395     return false;
18396
18397   // Very little shuffling can be done for 64-bit vectors right now.
18398   if (VT.getSizeInBits() == 64)
18399     return false;
18400
18401   // We only care that the types being shuffled are legal. The lowering can
18402   // handle any possible shuffle mask that results.
18403   return isTypeLegal(VT.getSimpleVT());
18404 }
18405
18406 bool
18407 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18408                                           EVT VT) const {
18409   // Just delegate to the generic legality, clear masks aren't special.
18410   return isShuffleMaskLegal(Mask, VT);
18411 }
18412
18413 //===----------------------------------------------------------------------===//
18414 //                           X86 Scheduler Hooks
18415 //===----------------------------------------------------------------------===//
18416
18417 /// Utility function to emit xbegin specifying the start of an RTM region.
18418 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18419                                      const TargetInstrInfo *TII) {
18420   DebugLoc DL = MI->getDebugLoc();
18421
18422   const BasicBlock *BB = MBB->getBasicBlock();
18423   MachineFunction::iterator I = MBB;
18424   ++I;
18425
18426   // For the v = xbegin(), we generate
18427   //
18428   // thisMBB:
18429   //  xbegin sinkMBB
18430   //
18431   // mainMBB:
18432   //  eax = -1
18433   //
18434   // sinkMBB:
18435   //  v = eax
18436
18437   MachineBasicBlock *thisMBB = MBB;
18438   MachineFunction *MF = MBB->getParent();
18439   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18440   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18441   MF->insert(I, mainMBB);
18442   MF->insert(I, sinkMBB);
18443
18444   // Transfer the remainder of BB and its successor edges to sinkMBB.
18445   sinkMBB->splice(sinkMBB->begin(), MBB,
18446                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18447   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18448
18449   // thisMBB:
18450   //  xbegin sinkMBB
18451   //  # fallthrough to mainMBB
18452   //  # abortion to sinkMBB
18453   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18454   thisMBB->addSuccessor(mainMBB);
18455   thisMBB->addSuccessor(sinkMBB);
18456
18457   // mainMBB:
18458   //  EAX = -1
18459   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18460   mainMBB->addSuccessor(sinkMBB);
18461
18462   // sinkMBB:
18463   // EAX is live into the sinkMBB
18464   sinkMBB->addLiveIn(X86::EAX);
18465   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18466           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18467     .addReg(X86::EAX);
18468
18469   MI->eraseFromParent();
18470   return sinkMBB;
18471 }
18472
18473 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18474 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18475 // in the .td file.
18476 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18477                                        const TargetInstrInfo *TII) {
18478   unsigned Opc;
18479   switch (MI->getOpcode()) {
18480   default: llvm_unreachable("illegal opcode!");
18481   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18482   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18483   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18484   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18485   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18486   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18487   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18488   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18489   }
18490
18491   DebugLoc dl = MI->getDebugLoc();
18492   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18493
18494   unsigned NumArgs = MI->getNumOperands();
18495   for (unsigned i = 1; i < NumArgs; ++i) {
18496     MachineOperand &Op = MI->getOperand(i);
18497     if (!(Op.isReg() && Op.isImplicit()))
18498       MIB.addOperand(Op);
18499   }
18500   if (MI->hasOneMemOperand())
18501     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18502
18503   BuildMI(*BB, MI, dl,
18504     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18505     .addReg(X86::XMM0);
18506
18507   MI->eraseFromParent();
18508   return BB;
18509 }
18510
18511 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18512 // defs in an instruction pattern
18513 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18514                                        const TargetInstrInfo *TII) {
18515   unsigned Opc;
18516   switch (MI->getOpcode()) {
18517   default: llvm_unreachable("illegal opcode!");
18518   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18519   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18520   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18521   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18522   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18523   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18524   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18525   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18526   }
18527
18528   DebugLoc dl = MI->getDebugLoc();
18529   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18530
18531   unsigned NumArgs = MI->getNumOperands(); // remove the results
18532   for (unsigned i = 1; i < NumArgs; ++i) {
18533     MachineOperand &Op = MI->getOperand(i);
18534     if (!(Op.isReg() && Op.isImplicit()))
18535       MIB.addOperand(Op);
18536   }
18537   if (MI->hasOneMemOperand())
18538     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18539
18540   BuildMI(*BB, MI, dl,
18541     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18542     .addReg(X86::ECX);
18543
18544   MI->eraseFromParent();
18545   return BB;
18546 }
18547
18548 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18549                                       const X86Subtarget *Subtarget) {
18550   DebugLoc dl = MI->getDebugLoc();
18551   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18552   // Address into RAX/EAX, other two args into ECX, EDX.
18553   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18554   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18555   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18556   for (int i = 0; i < X86::AddrNumOperands; ++i)
18557     MIB.addOperand(MI->getOperand(i));
18558
18559   unsigned ValOps = X86::AddrNumOperands;
18560   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18561     .addReg(MI->getOperand(ValOps).getReg());
18562   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18563     .addReg(MI->getOperand(ValOps+1).getReg());
18564
18565   // The instruction doesn't actually take any operands though.
18566   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18567
18568   MI->eraseFromParent(); // The pseudo is gone now.
18569   return BB;
18570 }
18571
18572 MachineBasicBlock *
18573 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18574                                                  MachineBasicBlock *MBB) const {
18575   // Emit va_arg instruction on X86-64.
18576
18577   // Operands to this pseudo-instruction:
18578   // 0  ) Output        : destination address (reg)
18579   // 1-5) Input         : va_list address (addr, i64mem)
18580   // 6  ) ArgSize       : Size (in bytes) of vararg type
18581   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18582   // 8  ) Align         : Alignment of type
18583   // 9  ) EFLAGS (implicit-def)
18584
18585   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18586   static_assert(X86::AddrNumOperands == 5,
18587                 "VAARG_64 assumes 5 address operands");
18588
18589   unsigned DestReg = MI->getOperand(0).getReg();
18590   MachineOperand &Base = MI->getOperand(1);
18591   MachineOperand &Scale = MI->getOperand(2);
18592   MachineOperand &Index = MI->getOperand(3);
18593   MachineOperand &Disp = MI->getOperand(4);
18594   MachineOperand &Segment = MI->getOperand(5);
18595   unsigned ArgSize = MI->getOperand(6).getImm();
18596   unsigned ArgMode = MI->getOperand(7).getImm();
18597   unsigned Align = MI->getOperand(8).getImm();
18598
18599   // Memory Reference
18600   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18601   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18602   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18603
18604   // Machine Information
18605   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18606   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18607   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18608   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18609   DebugLoc DL = MI->getDebugLoc();
18610
18611   // struct va_list {
18612   //   i32   gp_offset
18613   //   i32   fp_offset
18614   //   i64   overflow_area (address)
18615   //   i64   reg_save_area (address)
18616   // }
18617   // sizeof(va_list) = 24
18618   // alignment(va_list) = 8
18619
18620   unsigned TotalNumIntRegs = 6;
18621   unsigned TotalNumXMMRegs = 8;
18622   bool UseGPOffset = (ArgMode == 1);
18623   bool UseFPOffset = (ArgMode == 2);
18624   unsigned MaxOffset = TotalNumIntRegs * 8 +
18625                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18626
18627   /* Align ArgSize to a multiple of 8 */
18628   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18629   bool NeedsAlign = (Align > 8);
18630
18631   MachineBasicBlock *thisMBB = MBB;
18632   MachineBasicBlock *overflowMBB;
18633   MachineBasicBlock *offsetMBB;
18634   MachineBasicBlock *endMBB;
18635
18636   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18637   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18638   unsigned OffsetReg = 0;
18639
18640   if (!UseGPOffset && !UseFPOffset) {
18641     // If we only pull from the overflow region, we don't create a branch.
18642     // We don't need to alter control flow.
18643     OffsetDestReg = 0; // unused
18644     OverflowDestReg = DestReg;
18645
18646     offsetMBB = nullptr;
18647     overflowMBB = thisMBB;
18648     endMBB = thisMBB;
18649   } else {
18650     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18651     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18652     // If not, pull from overflow_area. (branch to overflowMBB)
18653     //
18654     //       thisMBB
18655     //         |     .
18656     //         |        .
18657     //     offsetMBB   overflowMBB
18658     //         |        .
18659     //         |     .
18660     //        endMBB
18661
18662     // Registers for the PHI in endMBB
18663     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18664     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18665
18666     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18667     MachineFunction *MF = MBB->getParent();
18668     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18669     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18670     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18671
18672     MachineFunction::iterator MBBIter = MBB;
18673     ++MBBIter;
18674
18675     // Insert the new basic blocks
18676     MF->insert(MBBIter, offsetMBB);
18677     MF->insert(MBBIter, overflowMBB);
18678     MF->insert(MBBIter, endMBB);
18679
18680     // Transfer the remainder of MBB and its successor edges to endMBB.
18681     endMBB->splice(endMBB->begin(), thisMBB,
18682                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18683     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18684
18685     // Make offsetMBB and overflowMBB successors of thisMBB
18686     thisMBB->addSuccessor(offsetMBB);
18687     thisMBB->addSuccessor(overflowMBB);
18688
18689     // endMBB is a successor of both offsetMBB and overflowMBB
18690     offsetMBB->addSuccessor(endMBB);
18691     overflowMBB->addSuccessor(endMBB);
18692
18693     // Load the offset value into a register
18694     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18695     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18696       .addOperand(Base)
18697       .addOperand(Scale)
18698       .addOperand(Index)
18699       .addDisp(Disp, UseFPOffset ? 4 : 0)
18700       .addOperand(Segment)
18701       .setMemRefs(MMOBegin, MMOEnd);
18702
18703     // Check if there is enough room left to pull this argument.
18704     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18705       .addReg(OffsetReg)
18706       .addImm(MaxOffset + 8 - ArgSizeA8);
18707
18708     // Branch to "overflowMBB" if offset >= max
18709     // Fall through to "offsetMBB" otherwise
18710     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18711       .addMBB(overflowMBB);
18712   }
18713
18714   // In offsetMBB, emit code to use the reg_save_area.
18715   if (offsetMBB) {
18716     assert(OffsetReg != 0);
18717
18718     // Read the reg_save_area address.
18719     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18720     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18721       .addOperand(Base)
18722       .addOperand(Scale)
18723       .addOperand(Index)
18724       .addDisp(Disp, 16)
18725       .addOperand(Segment)
18726       .setMemRefs(MMOBegin, MMOEnd);
18727
18728     // Zero-extend the offset
18729     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18730       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18731         .addImm(0)
18732         .addReg(OffsetReg)
18733         .addImm(X86::sub_32bit);
18734
18735     // Add the offset to the reg_save_area to get the final address.
18736     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18737       .addReg(OffsetReg64)
18738       .addReg(RegSaveReg);
18739
18740     // Compute the offset for the next argument
18741     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18742     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18743       .addReg(OffsetReg)
18744       .addImm(UseFPOffset ? 16 : 8);
18745
18746     // Store it back into the va_list.
18747     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18748       .addOperand(Base)
18749       .addOperand(Scale)
18750       .addOperand(Index)
18751       .addDisp(Disp, UseFPOffset ? 4 : 0)
18752       .addOperand(Segment)
18753       .addReg(NextOffsetReg)
18754       .setMemRefs(MMOBegin, MMOEnd);
18755
18756     // Jump to endMBB
18757     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18758       .addMBB(endMBB);
18759   }
18760
18761   //
18762   // Emit code to use overflow area
18763   //
18764
18765   // Load the overflow_area address into a register.
18766   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18767   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18768     .addOperand(Base)
18769     .addOperand(Scale)
18770     .addOperand(Index)
18771     .addDisp(Disp, 8)
18772     .addOperand(Segment)
18773     .setMemRefs(MMOBegin, MMOEnd);
18774
18775   // If we need to align it, do so. Otherwise, just copy the address
18776   // to OverflowDestReg.
18777   if (NeedsAlign) {
18778     // Align the overflow address
18779     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18780     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18781
18782     // aligned_addr = (addr + (align-1)) & ~(align-1)
18783     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18784       .addReg(OverflowAddrReg)
18785       .addImm(Align-1);
18786
18787     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18788       .addReg(TmpReg)
18789       .addImm(~(uint64_t)(Align-1));
18790   } else {
18791     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18792       .addReg(OverflowAddrReg);
18793   }
18794
18795   // Compute the next overflow address after this argument.
18796   // (the overflow address should be kept 8-byte aligned)
18797   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18798   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18799     .addReg(OverflowDestReg)
18800     .addImm(ArgSizeA8);
18801
18802   // Store the new overflow address.
18803   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18804     .addOperand(Base)
18805     .addOperand(Scale)
18806     .addOperand(Index)
18807     .addDisp(Disp, 8)
18808     .addOperand(Segment)
18809     .addReg(NextAddrReg)
18810     .setMemRefs(MMOBegin, MMOEnd);
18811
18812   // If we branched, emit the PHI to the front of endMBB.
18813   if (offsetMBB) {
18814     BuildMI(*endMBB, endMBB->begin(), DL,
18815             TII->get(X86::PHI), DestReg)
18816       .addReg(OffsetDestReg).addMBB(offsetMBB)
18817       .addReg(OverflowDestReg).addMBB(overflowMBB);
18818   }
18819
18820   // Erase the pseudo instruction
18821   MI->eraseFromParent();
18822
18823   return endMBB;
18824 }
18825
18826 MachineBasicBlock *
18827 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18828                                                  MachineInstr *MI,
18829                                                  MachineBasicBlock *MBB) const {
18830   // Emit code to save XMM registers to the stack. The ABI says that the
18831   // number of registers to save is given in %al, so it's theoretically
18832   // possible to do an indirect jump trick to avoid saving all of them,
18833   // however this code takes a simpler approach and just executes all
18834   // of the stores if %al is non-zero. It's less code, and it's probably
18835   // easier on the hardware branch predictor, and stores aren't all that
18836   // expensive anyway.
18837
18838   // Create the new basic blocks. One block contains all the XMM stores,
18839   // and one block is the final destination regardless of whether any
18840   // stores were performed.
18841   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18842   MachineFunction *F = MBB->getParent();
18843   MachineFunction::iterator MBBIter = MBB;
18844   ++MBBIter;
18845   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18846   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18847   F->insert(MBBIter, XMMSaveMBB);
18848   F->insert(MBBIter, EndMBB);
18849
18850   // Transfer the remainder of MBB and its successor edges to EndMBB.
18851   EndMBB->splice(EndMBB->begin(), MBB,
18852                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18853   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18854
18855   // The original block will now fall through to the XMM save block.
18856   MBB->addSuccessor(XMMSaveMBB);
18857   // The XMMSaveMBB will fall through to the end block.
18858   XMMSaveMBB->addSuccessor(EndMBB);
18859
18860   // Now add the instructions.
18861   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18862   DebugLoc DL = MI->getDebugLoc();
18863
18864   unsigned CountReg = MI->getOperand(0).getReg();
18865   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18866   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18867
18868   if (!Subtarget->isTargetWin64()) {
18869     // If %al is 0, branch around the XMM save block.
18870     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18871     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18872     MBB->addSuccessor(EndMBB);
18873   }
18874
18875   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18876   // that was just emitted, but clearly shouldn't be "saved".
18877   assert((MI->getNumOperands() <= 3 ||
18878           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18879           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18880          && "Expected last argument to be EFLAGS");
18881   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18882   // In the XMM save block, save all the XMM argument registers.
18883   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18884     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18885     MachineMemOperand *MMO =
18886       F->getMachineMemOperand(
18887           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18888         MachineMemOperand::MOStore,
18889         /*Size=*/16, /*Align=*/16);
18890     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18891       .addFrameIndex(RegSaveFrameIndex)
18892       .addImm(/*Scale=*/1)
18893       .addReg(/*IndexReg=*/0)
18894       .addImm(/*Disp=*/Offset)
18895       .addReg(/*Segment=*/0)
18896       .addReg(MI->getOperand(i).getReg())
18897       .addMemOperand(MMO);
18898   }
18899
18900   MI->eraseFromParent();   // The pseudo instruction is gone now.
18901
18902   return EndMBB;
18903 }
18904
18905 // The EFLAGS operand of SelectItr might be missing a kill marker
18906 // because there were multiple uses of EFLAGS, and ISel didn't know
18907 // which to mark. Figure out whether SelectItr should have had a
18908 // kill marker, and set it if it should. Returns the correct kill
18909 // marker value.
18910 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18911                                      MachineBasicBlock* BB,
18912                                      const TargetRegisterInfo* TRI) {
18913   // Scan forward through BB for a use/def of EFLAGS.
18914   MachineBasicBlock::iterator miI(std::next(SelectItr));
18915   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18916     const MachineInstr& mi = *miI;
18917     if (mi.readsRegister(X86::EFLAGS))
18918       return false;
18919     if (mi.definesRegister(X86::EFLAGS))
18920       break; // Should have kill-flag - update below.
18921   }
18922
18923   // If we hit the end of the block, check whether EFLAGS is live into a
18924   // successor.
18925   if (miI == BB->end()) {
18926     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18927                                           sEnd = BB->succ_end();
18928          sItr != sEnd; ++sItr) {
18929       MachineBasicBlock* succ = *sItr;
18930       if (succ->isLiveIn(X86::EFLAGS))
18931         return false;
18932     }
18933   }
18934
18935   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18936   // out. SelectMI should have a kill flag on EFLAGS.
18937   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18938   return true;
18939 }
18940
18941 MachineBasicBlock *
18942 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18943                                      MachineBasicBlock *BB) const {
18944   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18945   DebugLoc DL = MI->getDebugLoc();
18946
18947   // To "insert" a SELECT_CC instruction, we actually have to insert the
18948   // diamond control-flow pattern.  The incoming instruction knows the
18949   // destination vreg to set, the condition code register to branch on, the
18950   // true/false values to select between, and a branch opcode to use.
18951   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18952   MachineFunction::iterator It = BB;
18953   ++It;
18954
18955   //  thisMBB:
18956   //  ...
18957   //   TrueVal = ...
18958   //   cmpTY ccX, r1, r2
18959   //   bCC copy1MBB
18960   //   fallthrough --> copy0MBB
18961   MachineBasicBlock *thisMBB = BB;
18962   MachineFunction *F = BB->getParent();
18963
18964   // We also lower double CMOVs:
18965   //   (CMOV (CMOV F, T, cc1), T, cc2)
18966   // to two successives branches.  For that, we look for another CMOV as the
18967   // following instruction.
18968   //
18969   // Without this, we would add a PHI between the two jumps, which ends up
18970   // creating a few copies all around. For instance, for
18971   //
18972   //    (sitofp (zext (fcmp une)))
18973   //
18974   // we would generate:
18975   //
18976   //         ucomiss %xmm1, %xmm0
18977   //         movss  <1.0f>, %xmm0
18978   //         movaps  %xmm0, %xmm1
18979   //         jne     .LBB5_2
18980   //         xorps   %xmm1, %xmm1
18981   // .LBB5_2:
18982   //         jp      .LBB5_4
18983   //         movaps  %xmm1, %xmm0
18984   // .LBB5_4:
18985   //         retq
18986   //
18987   // because this custom-inserter would have generated:
18988   //
18989   //   A
18990   //   | \
18991   //   |  B
18992   //   | /
18993   //   C
18994   //   | \
18995   //   |  D
18996   //   | /
18997   //   E
18998   //
18999   // A: X = ...; Y = ...
19000   // B: empty
19001   // C: Z = PHI [X, A], [Y, B]
19002   // D: empty
19003   // E: PHI [X, C], [Z, D]
19004   //
19005   // If we lower both CMOVs in a single step, we can instead generate:
19006   //
19007   //   A
19008   //   | \
19009   //   |  C
19010   //   | /|
19011   //   |/ |
19012   //   |  |
19013   //   |  D
19014   //   | /
19015   //   E
19016   //
19017   // A: X = ...; Y = ...
19018   // D: empty
19019   // E: PHI [X, A], [X, C], [Y, D]
19020   //
19021   // Which, in our sitofp/fcmp example, gives us something like:
19022   //
19023   //         ucomiss %xmm1, %xmm0
19024   //         movss  <1.0f>, %xmm0
19025   //         jne     .LBB5_4
19026   //         jp      .LBB5_4
19027   //         xorps   %xmm0, %xmm0
19028   // .LBB5_4:
19029   //         retq
19030   //
19031   MachineInstr *NextCMOV = nullptr;
19032   MachineBasicBlock::iterator NextMIIt =
19033       std::next(MachineBasicBlock::iterator(MI));
19034   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19035       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19036       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19037     NextCMOV = &*NextMIIt;
19038
19039   MachineBasicBlock *jcc1MBB = nullptr;
19040
19041   // If we have a double CMOV, we lower it to two successive branches to
19042   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19043   if (NextCMOV) {
19044     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19045     F->insert(It, jcc1MBB);
19046     jcc1MBB->addLiveIn(X86::EFLAGS);
19047   }
19048
19049   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19050   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19051   F->insert(It, copy0MBB);
19052   F->insert(It, sinkMBB);
19053
19054   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19055   // live into the sink and copy blocks.
19056   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19057
19058   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19059   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19060       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19061     copy0MBB->addLiveIn(X86::EFLAGS);
19062     sinkMBB->addLiveIn(X86::EFLAGS);
19063   }
19064
19065   // Transfer the remainder of BB and its successor edges to sinkMBB.
19066   sinkMBB->splice(sinkMBB->begin(), BB,
19067                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19068   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19069
19070   // Add the true and fallthrough blocks as its successors.
19071   if (NextCMOV) {
19072     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19073     BB->addSuccessor(jcc1MBB);
19074
19075     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19076     // jump to the sinkMBB.
19077     jcc1MBB->addSuccessor(copy0MBB);
19078     jcc1MBB->addSuccessor(sinkMBB);
19079   } else {
19080     BB->addSuccessor(copy0MBB);
19081   }
19082
19083   // The true block target of the first (or only) branch is always sinkMBB.
19084   BB->addSuccessor(sinkMBB);
19085
19086   // Create the conditional branch instruction.
19087   unsigned Opc =
19088     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19089   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19090
19091   if (NextCMOV) {
19092     unsigned Opc2 = X86::GetCondBranchFromCond(
19093         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19094     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19095   }
19096
19097   //  copy0MBB:
19098   //   %FalseValue = ...
19099   //   # fallthrough to sinkMBB
19100   copy0MBB->addSuccessor(sinkMBB);
19101
19102   //  sinkMBB:
19103   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19104   //  ...
19105   MachineInstrBuilder MIB =
19106       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19107               MI->getOperand(0).getReg())
19108           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19109           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19110
19111   // If we have a double CMOV, the second Jcc provides the same incoming
19112   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19113   if (NextCMOV) {
19114     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19115     // Copy the PHI result to the register defined by the second CMOV.
19116     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19117             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19118         .addReg(MI->getOperand(0).getReg());
19119     NextCMOV->eraseFromParent();
19120   }
19121
19122   MI->eraseFromParent();   // The pseudo instruction is gone now.
19123   return sinkMBB;
19124 }
19125
19126 MachineBasicBlock *
19127 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19128                                         MachineBasicBlock *BB) const {
19129   MachineFunction *MF = BB->getParent();
19130   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19131   DebugLoc DL = MI->getDebugLoc();
19132   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19133
19134   assert(MF->shouldSplitStack());
19135
19136   const bool Is64Bit = Subtarget->is64Bit();
19137   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19138
19139   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19140   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19141
19142   // BB:
19143   //  ... [Till the alloca]
19144   // If stacklet is not large enough, jump to mallocMBB
19145   //
19146   // bumpMBB:
19147   //  Allocate by subtracting from RSP
19148   //  Jump to continueMBB
19149   //
19150   // mallocMBB:
19151   //  Allocate by call to runtime
19152   //
19153   // continueMBB:
19154   //  ...
19155   //  [rest of original BB]
19156   //
19157
19158   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19159   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19160   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19161
19162   MachineRegisterInfo &MRI = MF->getRegInfo();
19163   const TargetRegisterClass *AddrRegClass =
19164     getRegClassFor(getPointerTy());
19165
19166   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19167     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19168     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19169     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19170     sizeVReg = MI->getOperand(1).getReg(),
19171     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19172
19173   MachineFunction::iterator MBBIter = BB;
19174   ++MBBIter;
19175
19176   MF->insert(MBBIter, bumpMBB);
19177   MF->insert(MBBIter, mallocMBB);
19178   MF->insert(MBBIter, continueMBB);
19179
19180   continueMBB->splice(continueMBB->begin(), BB,
19181                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19182   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19183
19184   // Add code to the main basic block to check if the stack limit has been hit,
19185   // and if so, jump to mallocMBB otherwise to bumpMBB.
19186   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19187   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19188     .addReg(tmpSPVReg).addReg(sizeVReg);
19189   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19190     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19191     .addReg(SPLimitVReg);
19192   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19193
19194   // bumpMBB simply decreases the stack pointer, since we know the current
19195   // stacklet has enough space.
19196   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19197     .addReg(SPLimitVReg);
19198   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19199     .addReg(SPLimitVReg);
19200   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19201
19202   // Calls into a routine in libgcc to allocate more space from the heap.
19203   const uint32_t *RegMask =
19204       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19205   if (IsLP64) {
19206     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19207       .addReg(sizeVReg);
19208     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19209       .addExternalSymbol("__morestack_allocate_stack_space")
19210       .addRegMask(RegMask)
19211       .addReg(X86::RDI, RegState::Implicit)
19212       .addReg(X86::RAX, RegState::ImplicitDefine);
19213   } else if (Is64Bit) {
19214     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19215       .addReg(sizeVReg);
19216     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19217       .addExternalSymbol("__morestack_allocate_stack_space")
19218       .addRegMask(RegMask)
19219       .addReg(X86::EDI, RegState::Implicit)
19220       .addReg(X86::EAX, RegState::ImplicitDefine);
19221   } else {
19222     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19223       .addImm(12);
19224     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19225     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19226       .addExternalSymbol("__morestack_allocate_stack_space")
19227       .addRegMask(RegMask)
19228       .addReg(X86::EAX, RegState::ImplicitDefine);
19229   }
19230
19231   if (!Is64Bit)
19232     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19233       .addImm(16);
19234
19235   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19236     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19237   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19238
19239   // Set up the CFG correctly.
19240   BB->addSuccessor(bumpMBB);
19241   BB->addSuccessor(mallocMBB);
19242   mallocMBB->addSuccessor(continueMBB);
19243   bumpMBB->addSuccessor(continueMBB);
19244
19245   // Take care of the PHI nodes.
19246   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19247           MI->getOperand(0).getReg())
19248     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19249     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19250
19251   // Delete the original pseudo instruction.
19252   MI->eraseFromParent();
19253
19254   // And we're done.
19255   return continueMBB;
19256 }
19257
19258 MachineBasicBlock *
19259 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19260                                         MachineBasicBlock *BB) const {
19261   DebugLoc DL = MI->getDebugLoc();
19262
19263   assert(!Subtarget->isTargetMachO());
19264
19265   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19266
19267   MI->eraseFromParent();   // The pseudo instruction is gone now.
19268   return BB;
19269 }
19270
19271 MachineBasicBlock *
19272 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19273                                       MachineBasicBlock *BB) const {
19274   // This is pretty easy.  We're taking the value that we received from
19275   // our load from the relocation, sticking it in either RDI (x86-64)
19276   // or EAX and doing an indirect call.  The return value will then
19277   // be in the normal return register.
19278   MachineFunction *F = BB->getParent();
19279   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19280   DebugLoc DL = MI->getDebugLoc();
19281
19282   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19283   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19284
19285   // Get a register mask for the lowered call.
19286   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19287   // proper register mask.
19288   const uint32_t *RegMask =
19289       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19290   if (Subtarget->is64Bit()) {
19291     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19292                                       TII->get(X86::MOV64rm), X86::RDI)
19293     .addReg(X86::RIP)
19294     .addImm(0).addReg(0)
19295     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19296                       MI->getOperand(3).getTargetFlags())
19297     .addReg(0);
19298     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19299     addDirectMem(MIB, X86::RDI);
19300     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19301   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19302     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19303                                       TII->get(X86::MOV32rm), X86::EAX)
19304     .addReg(0)
19305     .addImm(0).addReg(0)
19306     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19307                       MI->getOperand(3).getTargetFlags())
19308     .addReg(0);
19309     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19310     addDirectMem(MIB, X86::EAX);
19311     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19312   } else {
19313     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19314                                       TII->get(X86::MOV32rm), X86::EAX)
19315     .addReg(TII->getGlobalBaseReg(F))
19316     .addImm(0).addReg(0)
19317     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19318                       MI->getOperand(3).getTargetFlags())
19319     .addReg(0);
19320     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19321     addDirectMem(MIB, X86::EAX);
19322     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19323   }
19324
19325   MI->eraseFromParent(); // The pseudo instruction is gone now.
19326   return BB;
19327 }
19328
19329 MachineBasicBlock *
19330 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19331                                     MachineBasicBlock *MBB) const {
19332   DebugLoc DL = MI->getDebugLoc();
19333   MachineFunction *MF = MBB->getParent();
19334   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19335   MachineRegisterInfo &MRI = MF->getRegInfo();
19336
19337   const BasicBlock *BB = MBB->getBasicBlock();
19338   MachineFunction::iterator I = MBB;
19339   ++I;
19340
19341   // Memory Reference
19342   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19343   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19344
19345   unsigned DstReg;
19346   unsigned MemOpndSlot = 0;
19347
19348   unsigned CurOp = 0;
19349
19350   DstReg = MI->getOperand(CurOp++).getReg();
19351   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19352   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19353   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19354   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19355
19356   MemOpndSlot = CurOp;
19357
19358   MVT PVT = getPointerTy();
19359   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19360          "Invalid Pointer Size!");
19361
19362   // For v = setjmp(buf), we generate
19363   //
19364   // thisMBB:
19365   //  buf[LabelOffset] = restoreMBB
19366   //  SjLjSetup restoreMBB
19367   //
19368   // mainMBB:
19369   //  v_main = 0
19370   //
19371   // sinkMBB:
19372   //  v = phi(main, restore)
19373   //
19374   // restoreMBB:
19375   //  if base pointer being used, load it from frame
19376   //  v_restore = 1
19377
19378   MachineBasicBlock *thisMBB = MBB;
19379   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19380   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19381   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19382   MF->insert(I, mainMBB);
19383   MF->insert(I, sinkMBB);
19384   MF->push_back(restoreMBB);
19385
19386   MachineInstrBuilder MIB;
19387
19388   // Transfer the remainder of BB and its successor edges to sinkMBB.
19389   sinkMBB->splice(sinkMBB->begin(), MBB,
19390                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19391   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19392
19393   // thisMBB:
19394   unsigned PtrStoreOpc = 0;
19395   unsigned LabelReg = 0;
19396   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19397   Reloc::Model RM = MF->getTarget().getRelocationModel();
19398   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19399                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19400
19401   // Prepare IP either in reg or imm.
19402   if (!UseImmLabel) {
19403     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19404     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19405     LabelReg = MRI.createVirtualRegister(PtrRC);
19406     if (Subtarget->is64Bit()) {
19407       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19408               .addReg(X86::RIP)
19409               .addImm(0)
19410               .addReg(0)
19411               .addMBB(restoreMBB)
19412               .addReg(0);
19413     } else {
19414       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19415       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19416               .addReg(XII->getGlobalBaseReg(MF))
19417               .addImm(0)
19418               .addReg(0)
19419               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19420               .addReg(0);
19421     }
19422   } else
19423     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19424   // Store IP
19425   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19426   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19427     if (i == X86::AddrDisp)
19428       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19429     else
19430       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19431   }
19432   if (!UseImmLabel)
19433     MIB.addReg(LabelReg);
19434   else
19435     MIB.addMBB(restoreMBB);
19436   MIB.setMemRefs(MMOBegin, MMOEnd);
19437   // Setup
19438   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19439           .addMBB(restoreMBB);
19440
19441   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19442   MIB.addRegMask(RegInfo->getNoPreservedMask());
19443   thisMBB->addSuccessor(mainMBB);
19444   thisMBB->addSuccessor(restoreMBB);
19445
19446   // mainMBB:
19447   //  EAX = 0
19448   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19449   mainMBB->addSuccessor(sinkMBB);
19450
19451   // sinkMBB:
19452   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19453           TII->get(X86::PHI), DstReg)
19454     .addReg(mainDstReg).addMBB(mainMBB)
19455     .addReg(restoreDstReg).addMBB(restoreMBB);
19456
19457   // restoreMBB:
19458   if (RegInfo->hasBasePointer(*MF)) {
19459     const bool Uses64BitFramePtr =
19460         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19461     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19462     X86FI->setRestoreBasePointer(MF);
19463     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19464     unsigned BasePtr = RegInfo->getBaseRegister();
19465     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19466     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19467                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19468       .setMIFlag(MachineInstr::FrameSetup);
19469   }
19470   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19471   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19472   restoreMBB->addSuccessor(sinkMBB);
19473
19474   MI->eraseFromParent();
19475   return sinkMBB;
19476 }
19477
19478 MachineBasicBlock *
19479 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19480                                      MachineBasicBlock *MBB) const {
19481   DebugLoc DL = MI->getDebugLoc();
19482   MachineFunction *MF = MBB->getParent();
19483   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19484   MachineRegisterInfo &MRI = MF->getRegInfo();
19485
19486   // Memory Reference
19487   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19488   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19489
19490   MVT PVT = getPointerTy();
19491   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19492          "Invalid Pointer Size!");
19493
19494   const TargetRegisterClass *RC =
19495     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19496   unsigned Tmp = MRI.createVirtualRegister(RC);
19497   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19498   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19499   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19500   unsigned SP = RegInfo->getStackRegister();
19501
19502   MachineInstrBuilder MIB;
19503
19504   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19505   const int64_t SPOffset = 2 * PVT.getStoreSize();
19506
19507   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19508   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19509
19510   // Reload FP
19511   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19512   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19513     MIB.addOperand(MI->getOperand(i));
19514   MIB.setMemRefs(MMOBegin, MMOEnd);
19515   // Reload IP
19516   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19517   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19518     if (i == X86::AddrDisp)
19519       MIB.addDisp(MI->getOperand(i), LabelOffset);
19520     else
19521       MIB.addOperand(MI->getOperand(i));
19522   }
19523   MIB.setMemRefs(MMOBegin, MMOEnd);
19524   // Reload SP
19525   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19526   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19527     if (i == X86::AddrDisp)
19528       MIB.addDisp(MI->getOperand(i), SPOffset);
19529     else
19530       MIB.addOperand(MI->getOperand(i));
19531   }
19532   MIB.setMemRefs(MMOBegin, MMOEnd);
19533   // Jump
19534   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19535
19536   MI->eraseFromParent();
19537   return MBB;
19538 }
19539
19540 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19541 // accumulator loops. Writing back to the accumulator allows the coalescer
19542 // to remove extra copies in the loop.
19543 MachineBasicBlock *
19544 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19545                                  MachineBasicBlock *MBB) const {
19546   MachineOperand &AddendOp = MI->getOperand(3);
19547
19548   // Bail out early if the addend isn't a register - we can't switch these.
19549   if (!AddendOp.isReg())
19550     return MBB;
19551
19552   MachineFunction &MF = *MBB->getParent();
19553   MachineRegisterInfo &MRI = MF.getRegInfo();
19554
19555   // Check whether the addend is defined by a PHI:
19556   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19557   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19558   if (!AddendDef.isPHI())
19559     return MBB;
19560
19561   // Look for the following pattern:
19562   // loop:
19563   //   %addend = phi [%entry, 0], [%loop, %result]
19564   //   ...
19565   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19566
19567   // Replace with:
19568   //   loop:
19569   //   %addend = phi [%entry, 0], [%loop, %result]
19570   //   ...
19571   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19572
19573   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19574     assert(AddendDef.getOperand(i).isReg());
19575     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19576     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19577     if (&PHISrcInst == MI) {
19578       // Found a matching instruction.
19579       unsigned NewFMAOpc = 0;
19580       switch (MI->getOpcode()) {
19581         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19582         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19583         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19584         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19585         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19586         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19587         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19588         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19589         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19590         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19591         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19592         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19593         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19594         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19595         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19596         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19597         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19598         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19599         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19600         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19601
19602         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19603         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19604         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19605         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19606         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19607         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19608         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19609         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19610         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19611         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19612         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19613         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19614         default: llvm_unreachable("Unrecognized FMA variant.");
19615       }
19616
19617       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19618       MachineInstrBuilder MIB =
19619         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19620         .addOperand(MI->getOperand(0))
19621         .addOperand(MI->getOperand(3))
19622         .addOperand(MI->getOperand(2))
19623         .addOperand(MI->getOperand(1));
19624       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19625       MI->eraseFromParent();
19626     }
19627   }
19628
19629   return MBB;
19630 }
19631
19632 MachineBasicBlock *
19633 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19634                                                MachineBasicBlock *BB) const {
19635   switch (MI->getOpcode()) {
19636   default: llvm_unreachable("Unexpected instr type to insert");
19637   case X86::TAILJMPd64:
19638   case X86::TAILJMPr64:
19639   case X86::TAILJMPm64:
19640   case X86::TAILJMPd64_REX:
19641   case X86::TAILJMPr64_REX:
19642   case X86::TAILJMPm64_REX:
19643     llvm_unreachable("TAILJMP64 would not be touched here.");
19644   case X86::TCRETURNdi64:
19645   case X86::TCRETURNri64:
19646   case X86::TCRETURNmi64:
19647     return BB;
19648   case X86::WIN_ALLOCA:
19649     return EmitLoweredWinAlloca(MI, BB);
19650   case X86::SEG_ALLOCA_32:
19651   case X86::SEG_ALLOCA_64:
19652     return EmitLoweredSegAlloca(MI, BB);
19653   case X86::TLSCall_32:
19654   case X86::TLSCall_64:
19655     return EmitLoweredTLSCall(MI, BB);
19656   case X86::CMOV_GR8:
19657   case X86::CMOV_FR32:
19658   case X86::CMOV_FR64:
19659   case X86::CMOV_V4F32:
19660   case X86::CMOV_V2F64:
19661   case X86::CMOV_V2I64:
19662   case X86::CMOV_V8F32:
19663   case X86::CMOV_V4F64:
19664   case X86::CMOV_V4I64:
19665   case X86::CMOV_V16F32:
19666   case X86::CMOV_V8F64:
19667   case X86::CMOV_V8I64:
19668   case X86::CMOV_GR16:
19669   case X86::CMOV_GR32:
19670   case X86::CMOV_RFP32:
19671   case X86::CMOV_RFP64:
19672   case X86::CMOV_RFP80:
19673   case X86::CMOV_V8I1:
19674   case X86::CMOV_V16I1:
19675   case X86::CMOV_V32I1:
19676   case X86::CMOV_V64I1:
19677     return EmitLoweredSelect(MI, BB);
19678
19679   case X86::FP32_TO_INT16_IN_MEM:
19680   case X86::FP32_TO_INT32_IN_MEM:
19681   case X86::FP32_TO_INT64_IN_MEM:
19682   case X86::FP64_TO_INT16_IN_MEM:
19683   case X86::FP64_TO_INT32_IN_MEM:
19684   case X86::FP64_TO_INT64_IN_MEM:
19685   case X86::FP80_TO_INT16_IN_MEM:
19686   case X86::FP80_TO_INT32_IN_MEM:
19687   case X86::FP80_TO_INT64_IN_MEM: {
19688     MachineFunction *F = BB->getParent();
19689     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19690     DebugLoc DL = MI->getDebugLoc();
19691
19692     // Change the floating point control register to use "round towards zero"
19693     // mode when truncating to an integer value.
19694     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19695     addFrameReference(BuildMI(*BB, MI, DL,
19696                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19697
19698     // Load the old value of the high byte of the control word...
19699     unsigned OldCW =
19700       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19701     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19702                       CWFrameIdx);
19703
19704     // Set the high part to be round to zero...
19705     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19706       .addImm(0xC7F);
19707
19708     // Reload the modified control word now...
19709     addFrameReference(BuildMI(*BB, MI, DL,
19710                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19711
19712     // Restore the memory image of control word to original value
19713     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19714       .addReg(OldCW);
19715
19716     // Get the X86 opcode to use.
19717     unsigned Opc;
19718     switch (MI->getOpcode()) {
19719     default: llvm_unreachable("illegal opcode!");
19720     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19721     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19722     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19723     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19724     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19725     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19726     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19727     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19728     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19729     }
19730
19731     X86AddressMode AM;
19732     MachineOperand &Op = MI->getOperand(0);
19733     if (Op.isReg()) {
19734       AM.BaseType = X86AddressMode::RegBase;
19735       AM.Base.Reg = Op.getReg();
19736     } else {
19737       AM.BaseType = X86AddressMode::FrameIndexBase;
19738       AM.Base.FrameIndex = Op.getIndex();
19739     }
19740     Op = MI->getOperand(1);
19741     if (Op.isImm())
19742       AM.Scale = Op.getImm();
19743     Op = MI->getOperand(2);
19744     if (Op.isImm())
19745       AM.IndexReg = Op.getImm();
19746     Op = MI->getOperand(3);
19747     if (Op.isGlobal()) {
19748       AM.GV = Op.getGlobal();
19749     } else {
19750       AM.Disp = Op.getImm();
19751     }
19752     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19753                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19754
19755     // Reload the original control word now.
19756     addFrameReference(BuildMI(*BB, MI, DL,
19757                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19758
19759     MI->eraseFromParent();   // The pseudo instruction is gone now.
19760     return BB;
19761   }
19762     // String/text processing lowering.
19763   case X86::PCMPISTRM128REG:
19764   case X86::VPCMPISTRM128REG:
19765   case X86::PCMPISTRM128MEM:
19766   case X86::VPCMPISTRM128MEM:
19767   case X86::PCMPESTRM128REG:
19768   case X86::VPCMPESTRM128REG:
19769   case X86::PCMPESTRM128MEM:
19770   case X86::VPCMPESTRM128MEM:
19771     assert(Subtarget->hasSSE42() &&
19772            "Target must have SSE4.2 or AVX features enabled");
19773     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19774
19775   // String/text processing lowering.
19776   case X86::PCMPISTRIREG:
19777   case X86::VPCMPISTRIREG:
19778   case X86::PCMPISTRIMEM:
19779   case X86::VPCMPISTRIMEM:
19780   case X86::PCMPESTRIREG:
19781   case X86::VPCMPESTRIREG:
19782   case X86::PCMPESTRIMEM:
19783   case X86::VPCMPESTRIMEM:
19784     assert(Subtarget->hasSSE42() &&
19785            "Target must have SSE4.2 or AVX features enabled");
19786     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19787
19788   // Thread synchronization.
19789   case X86::MONITOR:
19790     return EmitMonitor(MI, BB, Subtarget);
19791
19792   // xbegin
19793   case X86::XBEGIN:
19794     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19795
19796   case X86::VASTART_SAVE_XMM_REGS:
19797     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19798
19799   case X86::VAARG_64:
19800     return EmitVAARG64WithCustomInserter(MI, BB);
19801
19802   case X86::EH_SjLj_SetJmp32:
19803   case X86::EH_SjLj_SetJmp64:
19804     return emitEHSjLjSetJmp(MI, BB);
19805
19806   case X86::EH_SjLj_LongJmp32:
19807   case X86::EH_SjLj_LongJmp64:
19808     return emitEHSjLjLongJmp(MI, BB);
19809
19810   case TargetOpcode::STATEPOINT:
19811     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19812     // this point in the process.  We diverge later.
19813     return emitPatchPoint(MI, BB);
19814
19815   case TargetOpcode::STACKMAP:
19816   case TargetOpcode::PATCHPOINT:
19817     return emitPatchPoint(MI, BB);
19818
19819   case X86::VFMADDPDr213r:
19820   case X86::VFMADDPSr213r:
19821   case X86::VFMADDSDr213r:
19822   case X86::VFMADDSSr213r:
19823   case X86::VFMSUBPDr213r:
19824   case X86::VFMSUBPSr213r:
19825   case X86::VFMSUBSDr213r:
19826   case X86::VFMSUBSSr213r:
19827   case X86::VFNMADDPDr213r:
19828   case X86::VFNMADDPSr213r:
19829   case X86::VFNMADDSDr213r:
19830   case X86::VFNMADDSSr213r:
19831   case X86::VFNMSUBPDr213r:
19832   case X86::VFNMSUBPSr213r:
19833   case X86::VFNMSUBSDr213r:
19834   case X86::VFNMSUBSSr213r:
19835   case X86::VFMADDSUBPDr213r:
19836   case X86::VFMADDSUBPSr213r:
19837   case X86::VFMSUBADDPDr213r:
19838   case X86::VFMSUBADDPSr213r:
19839   case X86::VFMADDPDr213rY:
19840   case X86::VFMADDPSr213rY:
19841   case X86::VFMSUBPDr213rY:
19842   case X86::VFMSUBPSr213rY:
19843   case X86::VFNMADDPDr213rY:
19844   case X86::VFNMADDPSr213rY:
19845   case X86::VFNMSUBPDr213rY:
19846   case X86::VFNMSUBPSr213rY:
19847   case X86::VFMADDSUBPDr213rY:
19848   case X86::VFMADDSUBPSr213rY:
19849   case X86::VFMSUBADDPDr213rY:
19850   case X86::VFMSUBADDPSr213rY:
19851     return emitFMA3Instr(MI, BB);
19852   }
19853 }
19854
19855 //===----------------------------------------------------------------------===//
19856 //                           X86 Optimization Hooks
19857 //===----------------------------------------------------------------------===//
19858
19859 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19860                                                       APInt &KnownZero,
19861                                                       APInt &KnownOne,
19862                                                       const SelectionDAG &DAG,
19863                                                       unsigned Depth) const {
19864   unsigned BitWidth = KnownZero.getBitWidth();
19865   unsigned Opc = Op.getOpcode();
19866   assert((Opc >= ISD::BUILTIN_OP_END ||
19867           Opc == ISD::INTRINSIC_WO_CHAIN ||
19868           Opc == ISD::INTRINSIC_W_CHAIN ||
19869           Opc == ISD::INTRINSIC_VOID) &&
19870          "Should use MaskedValueIsZero if you don't know whether Op"
19871          " is a target node!");
19872
19873   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19874   switch (Opc) {
19875   default: break;
19876   case X86ISD::ADD:
19877   case X86ISD::SUB:
19878   case X86ISD::ADC:
19879   case X86ISD::SBB:
19880   case X86ISD::SMUL:
19881   case X86ISD::UMUL:
19882   case X86ISD::INC:
19883   case X86ISD::DEC:
19884   case X86ISD::OR:
19885   case X86ISD::XOR:
19886   case X86ISD::AND:
19887     // These nodes' second result is a boolean.
19888     if (Op.getResNo() == 0)
19889       break;
19890     // Fallthrough
19891   case X86ISD::SETCC:
19892     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19893     break;
19894   case ISD::INTRINSIC_WO_CHAIN: {
19895     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19896     unsigned NumLoBits = 0;
19897     switch (IntId) {
19898     default: break;
19899     case Intrinsic::x86_sse_movmsk_ps:
19900     case Intrinsic::x86_avx_movmsk_ps_256:
19901     case Intrinsic::x86_sse2_movmsk_pd:
19902     case Intrinsic::x86_avx_movmsk_pd_256:
19903     case Intrinsic::x86_mmx_pmovmskb:
19904     case Intrinsic::x86_sse2_pmovmskb_128:
19905     case Intrinsic::x86_avx2_pmovmskb: {
19906       // High bits of movmskp{s|d}, pmovmskb are known zero.
19907       switch (IntId) {
19908         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19909         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19910         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19911         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19912         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19913         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19914         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19915         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19916       }
19917       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19918       break;
19919     }
19920     }
19921     break;
19922   }
19923   }
19924 }
19925
19926 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19927   SDValue Op,
19928   const SelectionDAG &,
19929   unsigned Depth) const {
19930   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19931   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19932     return Op.getValueType().getScalarType().getSizeInBits();
19933
19934   // Fallback case.
19935   return 1;
19936 }
19937
19938 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19939 /// node is a GlobalAddress + offset.
19940 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19941                                        const GlobalValue* &GA,
19942                                        int64_t &Offset) const {
19943   if (N->getOpcode() == X86ISD::Wrapper) {
19944     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19945       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19946       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19947       return true;
19948     }
19949   }
19950   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19951 }
19952
19953 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19954 /// same as extracting the high 128-bit part of 256-bit vector and then
19955 /// inserting the result into the low part of a new 256-bit vector
19956 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19957   EVT VT = SVOp->getValueType(0);
19958   unsigned NumElems = VT.getVectorNumElements();
19959
19960   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19961   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19962     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19963         SVOp->getMaskElt(j) >= 0)
19964       return false;
19965
19966   return true;
19967 }
19968
19969 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19970 /// same as extracting the low 128-bit part of 256-bit vector and then
19971 /// inserting the result into the high part of a new 256-bit vector
19972 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19973   EVT VT = SVOp->getValueType(0);
19974   unsigned NumElems = VT.getVectorNumElements();
19975
19976   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19977   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19978     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19979         SVOp->getMaskElt(j) >= 0)
19980       return false;
19981
19982   return true;
19983 }
19984
19985 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19986 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19987                                         TargetLowering::DAGCombinerInfo &DCI,
19988                                         const X86Subtarget* Subtarget) {
19989   SDLoc dl(N);
19990   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19991   SDValue V1 = SVOp->getOperand(0);
19992   SDValue V2 = SVOp->getOperand(1);
19993   EVT VT = SVOp->getValueType(0);
19994   unsigned NumElems = VT.getVectorNumElements();
19995
19996   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19997       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19998     //
19999     //                   0,0,0,...
20000     //                      |
20001     //    V      UNDEF    BUILD_VECTOR    UNDEF
20002     //     \      /           \           /
20003     //  CONCAT_VECTOR         CONCAT_VECTOR
20004     //         \                  /
20005     //          \                /
20006     //          RESULT: V + zero extended
20007     //
20008     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20009         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20010         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20011       return SDValue();
20012
20013     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20014       return SDValue();
20015
20016     // To match the shuffle mask, the first half of the mask should
20017     // be exactly the first vector, and all the rest a splat with the
20018     // first element of the second one.
20019     for (unsigned i = 0; i != NumElems/2; ++i)
20020       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20021           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20022         return SDValue();
20023
20024     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20025     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20026       if (Ld->hasNUsesOfValue(1, 0)) {
20027         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20028         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20029         SDValue ResNode =
20030           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20031                                   Ld->getMemoryVT(),
20032                                   Ld->getPointerInfo(),
20033                                   Ld->getAlignment(),
20034                                   false/*isVolatile*/, true/*ReadMem*/,
20035                                   false/*WriteMem*/);
20036
20037         // Make sure the newly-created LOAD is in the same position as Ld in
20038         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20039         // and update uses of Ld's output chain to use the TokenFactor.
20040         if (Ld->hasAnyUseOfValue(1)) {
20041           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20042                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20043           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20044           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20045                                  SDValue(ResNode.getNode(), 1));
20046         }
20047
20048         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
20049       }
20050     }
20051
20052     // Emit a zeroed vector and insert the desired subvector on its
20053     // first half.
20054     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20055     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20056     return DCI.CombineTo(N, InsV);
20057   }
20058
20059   //===--------------------------------------------------------------------===//
20060   // Combine some shuffles into subvector extracts and inserts:
20061   //
20062
20063   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20064   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20065     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20066     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20067     return DCI.CombineTo(N, InsV);
20068   }
20069
20070   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20071   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20072     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20073     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20074     return DCI.CombineTo(N, InsV);
20075   }
20076
20077   return SDValue();
20078 }
20079
20080 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20081 /// possible.
20082 ///
20083 /// This is the leaf of the recursive combinine below. When we have found some
20084 /// chain of single-use x86 shuffle instructions and accumulated the combined
20085 /// shuffle mask represented by them, this will try to pattern match that mask
20086 /// into either a single instruction if there is a special purpose instruction
20087 /// for this operation, or into a PSHUFB instruction which is a fully general
20088 /// instruction but should only be used to replace chains over a certain depth.
20089 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20090                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20091                                    TargetLowering::DAGCombinerInfo &DCI,
20092                                    const X86Subtarget *Subtarget) {
20093   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20094
20095   // Find the operand that enters the chain. Note that multiple uses are OK
20096   // here, we're not going to remove the operand we find.
20097   SDValue Input = Op.getOperand(0);
20098   while (Input.getOpcode() == ISD::BITCAST)
20099     Input = Input.getOperand(0);
20100
20101   MVT VT = Input.getSimpleValueType();
20102   MVT RootVT = Root.getSimpleValueType();
20103   SDLoc DL(Root);
20104
20105   // Just remove no-op shuffle masks.
20106   if (Mask.size() == 1) {
20107     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
20108                   /*AddTo*/ true);
20109     return true;
20110   }
20111
20112   // Use the float domain if the operand type is a floating point type.
20113   bool FloatDomain = VT.isFloatingPoint();
20114
20115   // For floating point shuffles, we don't have free copies in the shuffle
20116   // instructions or the ability to load as part of the instruction, so
20117   // canonicalize their shuffles to UNPCK or MOV variants.
20118   //
20119   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20120   // vectors because it can have a load folded into it that UNPCK cannot. This
20121   // doesn't preclude something switching to the shorter encoding post-RA.
20122   //
20123   // FIXME: Should teach these routines about AVX vector widths.
20124   if (FloatDomain && VT.getSizeInBits() == 128) {
20125     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20126       bool Lo = Mask.equals({0, 0});
20127       unsigned Shuffle;
20128       MVT ShuffleVT;
20129       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20130       // is no slower than UNPCKLPD but has the option to fold the input operand
20131       // into even an unaligned memory load.
20132       if (Lo && Subtarget->hasSSE3()) {
20133         Shuffle = X86ISD::MOVDDUP;
20134         ShuffleVT = MVT::v2f64;
20135       } else {
20136         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20137         // than the UNPCK variants.
20138         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20139         ShuffleVT = MVT::v4f32;
20140       }
20141       if (Depth == 1 && Root->getOpcode() == Shuffle)
20142         return false; // Nothing to do!
20143       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20144       DCI.AddToWorklist(Op.getNode());
20145       if (Shuffle == X86ISD::MOVDDUP)
20146         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20147       else
20148         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20149       DCI.AddToWorklist(Op.getNode());
20150       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20151                     /*AddTo*/ true);
20152       return true;
20153     }
20154     if (Subtarget->hasSSE3() &&
20155         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20156       bool Lo = Mask.equals({0, 0, 2, 2});
20157       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20158       MVT ShuffleVT = MVT::v4f32;
20159       if (Depth == 1 && Root->getOpcode() == Shuffle)
20160         return false; // Nothing to do!
20161       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20162       DCI.AddToWorklist(Op.getNode());
20163       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20164       DCI.AddToWorklist(Op.getNode());
20165       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20166                     /*AddTo*/ true);
20167       return true;
20168     }
20169     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20170       bool Lo = Mask.equals({0, 0, 1, 1});
20171       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20172       MVT ShuffleVT = MVT::v4f32;
20173       if (Depth == 1 && Root->getOpcode() == Shuffle)
20174         return false; // Nothing to do!
20175       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20176       DCI.AddToWorklist(Op.getNode());
20177       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20178       DCI.AddToWorklist(Op.getNode());
20179       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20180                     /*AddTo*/ true);
20181       return true;
20182     }
20183   }
20184
20185   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20186   // variants as none of these have single-instruction variants that are
20187   // superior to the UNPCK formulation.
20188   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20189       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20190        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20191        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20192        Mask.equals(
20193            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20194     bool Lo = Mask[0] == 0;
20195     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20196     if (Depth == 1 && Root->getOpcode() == Shuffle)
20197       return false; // Nothing to do!
20198     MVT ShuffleVT;
20199     switch (Mask.size()) {
20200     case 8:
20201       ShuffleVT = MVT::v8i16;
20202       break;
20203     case 16:
20204       ShuffleVT = MVT::v16i8;
20205       break;
20206     default:
20207       llvm_unreachable("Impossible mask size!");
20208     };
20209     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20210     DCI.AddToWorklist(Op.getNode());
20211     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20212     DCI.AddToWorklist(Op.getNode());
20213     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20214                   /*AddTo*/ true);
20215     return true;
20216   }
20217
20218   // Don't try to re-form single instruction chains under any circumstances now
20219   // that we've done encoding canonicalization for them.
20220   if (Depth < 2)
20221     return false;
20222
20223   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20224   // can replace them with a single PSHUFB instruction profitably. Intel's
20225   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20226   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20227   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20228     SmallVector<SDValue, 16> PSHUFBMask;
20229     int NumBytes = VT.getSizeInBits() / 8;
20230     int Ratio = NumBytes / Mask.size();
20231     for (int i = 0; i < NumBytes; ++i) {
20232       if (Mask[i / Ratio] == SM_SentinelUndef) {
20233         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20234         continue;
20235       }
20236       int M = Mask[i / Ratio] != SM_SentinelZero
20237                   ? Ratio * Mask[i / Ratio] + i % Ratio
20238                   : 255;
20239       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20240     }
20241     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20242     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20243     DCI.AddToWorklist(Op.getNode());
20244     SDValue PSHUFBMaskOp =
20245         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20246     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20247     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20248     DCI.AddToWorklist(Op.getNode());
20249     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20250                   /*AddTo*/ true);
20251     return true;
20252   }
20253
20254   // Failed to find any combines.
20255   return false;
20256 }
20257
20258 /// \brief Fully generic combining of x86 shuffle instructions.
20259 ///
20260 /// This should be the last combine run over the x86 shuffle instructions. Once
20261 /// they have been fully optimized, this will recursively consider all chains
20262 /// of single-use shuffle instructions, build a generic model of the cumulative
20263 /// shuffle operation, and check for simpler instructions which implement this
20264 /// operation. We use this primarily for two purposes:
20265 ///
20266 /// 1) Collapse generic shuffles to specialized single instructions when
20267 ///    equivalent. In most cases, this is just an encoding size win, but
20268 ///    sometimes we will collapse multiple generic shuffles into a single
20269 ///    special-purpose shuffle.
20270 /// 2) Look for sequences of shuffle instructions with 3 or more total
20271 ///    instructions, and replace them with the slightly more expensive SSSE3
20272 ///    PSHUFB instruction if available. We do this as the last combining step
20273 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20274 ///    a suitable short sequence of other instructions. The PHUFB will either
20275 ///    use a register or have to read from memory and so is slightly (but only
20276 ///    slightly) more expensive than the other shuffle instructions.
20277 ///
20278 /// Because this is inherently a quadratic operation (for each shuffle in
20279 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20280 /// This should never be an issue in practice as the shuffle lowering doesn't
20281 /// produce sequences of more than 8 instructions.
20282 ///
20283 /// FIXME: We will currently miss some cases where the redundant shuffling
20284 /// would simplify under the threshold for PSHUFB formation because of
20285 /// combine-ordering. To fix this, we should do the redundant instruction
20286 /// combining in this recursive walk.
20287 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20288                                           ArrayRef<int> RootMask,
20289                                           int Depth, bool HasPSHUFB,
20290                                           SelectionDAG &DAG,
20291                                           TargetLowering::DAGCombinerInfo &DCI,
20292                                           const X86Subtarget *Subtarget) {
20293   // Bound the depth of our recursive combine because this is ultimately
20294   // quadratic in nature.
20295   if (Depth > 8)
20296     return false;
20297
20298   // Directly rip through bitcasts to find the underlying operand.
20299   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20300     Op = Op.getOperand(0);
20301
20302   MVT VT = Op.getSimpleValueType();
20303   if (!VT.isVector())
20304     return false; // Bail if we hit a non-vector.
20305
20306   assert(Root.getSimpleValueType().isVector() &&
20307          "Shuffles operate on vector types!");
20308   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20309          "Can only combine shuffles of the same vector register size.");
20310
20311   if (!isTargetShuffle(Op.getOpcode()))
20312     return false;
20313   SmallVector<int, 16> OpMask;
20314   bool IsUnary;
20315   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20316   // We only can combine unary shuffles which we can decode the mask for.
20317   if (!HaveMask || !IsUnary)
20318     return false;
20319
20320   assert(VT.getVectorNumElements() == OpMask.size() &&
20321          "Different mask size from vector size!");
20322   assert(((RootMask.size() > OpMask.size() &&
20323            RootMask.size() % OpMask.size() == 0) ||
20324           (OpMask.size() > RootMask.size() &&
20325            OpMask.size() % RootMask.size() == 0) ||
20326           OpMask.size() == RootMask.size()) &&
20327          "The smaller number of elements must divide the larger.");
20328   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20329   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20330   assert(((RootRatio == 1 && OpRatio == 1) ||
20331           (RootRatio == 1) != (OpRatio == 1)) &&
20332          "Must not have a ratio for both incoming and op masks!");
20333
20334   SmallVector<int, 16> Mask;
20335   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20336
20337   // Merge this shuffle operation's mask into our accumulated mask. Note that
20338   // this shuffle's mask will be the first applied to the input, followed by the
20339   // root mask to get us all the way to the root value arrangement. The reason
20340   // for this order is that we are recursing up the operation chain.
20341   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20342     int RootIdx = i / RootRatio;
20343     if (RootMask[RootIdx] < 0) {
20344       // This is a zero or undef lane, we're done.
20345       Mask.push_back(RootMask[RootIdx]);
20346       continue;
20347     }
20348
20349     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20350     int OpIdx = RootMaskedIdx / OpRatio;
20351     if (OpMask[OpIdx] < 0) {
20352       // The incoming lanes are zero or undef, it doesn't matter which ones we
20353       // are using.
20354       Mask.push_back(OpMask[OpIdx]);
20355       continue;
20356     }
20357
20358     // Ok, we have non-zero lanes, map them through.
20359     Mask.push_back(OpMask[OpIdx] * OpRatio +
20360                    RootMaskedIdx % OpRatio);
20361   }
20362
20363   // See if we can recurse into the operand to combine more things.
20364   switch (Op.getOpcode()) {
20365     case X86ISD::PSHUFB:
20366       HasPSHUFB = true;
20367     case X86ISD::PSHUFD:
20368     case X86ISD::PSHUFHW:
20369     case X86ISD::PSHUFLW:
20370       if (Op.getOperand(0).hasOneUse() &&
20371           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20372                                         HasPSHUFB, DAG, DCI, Subtarget))
20373         return true;
20374       break;
20375
20376     case X86ISD::UNPCKL:
20377     case X86ISD::UNPCKH:
20378       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20379       // We can't check for single use, we have to check that this shuffle is the only user.
20380       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20381           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20382                                         HasPSHUFB, DAG, DCI, Subtarget))
20383           return true;
20384       break;
20385   }
20386
20387   // Minor canonicalization of the accumulated shuffle mask to make it easier
20388   // to match below. All this does is detect masks with squential pairs of
20389   // elements, and shrink them to the half-width mask. It does this in a loop
20390   // so it will reduce the size of the mask to the minimal width mask which
20391   // performs an equivalent shuffle.
20392   SmallVector<int, 16> WidenedMask;
20393   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20394     Mask = std::move(WidenedMask);
20395     WidenedMask.clear();
20396   }
20397
20398   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20399                                 Subtarget);
20400 }
20401
20402 /// \brief Get the PSHUF-style mask from PSHUF node.
20403 ///
20404 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20405 /// PSHUF-style masks that can be reused with such instructions.
20406 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20407   MVT VT = N.getSimpleValueType();
20408   SmallVector<int, 4> Mask;
20409   bool IsUnary;
20410   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20411   (void)HaveMask;
20412   assert(HaveMask);
20413
20414   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20415   // matter. Check that the upper masks are repeats and remove them.
20416   if (VT.getSizeInBits() > 128) {
20417     int LaneElts = 128 / VT.getScalarSizeInBits();
20418 #ifndef NDEBUG
20419     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20420       for (int j = 0; j < LaneElts; ++j)
20421         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20422                "Mask doesn't repeat in high 128-bit lanes!");
20423 #endif
20424     Mask.resize(LaneElts);
20425   }
20426
20427   switch (N.getOpcode()) {
20428   case X86ISD::PSHUFD:
20429     return Mask;
20430   case X86ISD::PSHUFLW:
20431     Mask.resize(4);
20432     return Mask;
20433   case X86ISD::PSHUFHW:
20434     Mask.erase(Mask.begin(), Mask.begin() + 4);
20435     for (int &M : Mask)
20436       M -= 4;
20437     return Mask;
20438   default:
20439     llvm_unreachable("No valid shuffle instruction found!");
20440   }
20441 }
20442
20443 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20444 ///
20445 /// We walk up the chain and look for a combinable shuffle, skipping over
20446 /// shuffles that we could hoist this shuffle's transformation past without
20447 /// altering anything.
20448 static SDValue
20449 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20450                              SelectionDAG &DAG,
20451                              TargetLowering::DAGCombinerInfo &DCI) {
20452   assert(N.getOpcode() == X86ISD::PSHUFD &&
20453          "Called with something other than an x86 128-bit half shuffle!");
20454   SDLoc DL(N);
20455
20456   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20457   // of the shuffles in the chain so that we can form a fresh chain to replace
20458   // this one.
20459   SmallVector<SDValue, 8> Chain;
20460   SDValue V = N.getOperand(0);
20461   for (; V.hasOneUse(); V = V.getOperand(0)) {
20462     switch (V.getOpcode()) {
20463     default:
20464       return SDValue(); // Nothing combined!
20465
20466     case ISD::BITCAST:
20467       // Skip bitcasts as we always know the type for the target specific
20468       // instructions.
20469       continue;
20470
20471     case X86ISD::PSHUFD:
20472       // Found another dword shuffle.
20473       break;
20474
20475     case X86ISD::PSHUFLW:
20476       // Check that the low words (being shuffled) are the identity in the
20477       // dword shuffle, and the high words are self-contained.
20478       if (Mask[0] != 0 || Mask[1] != 1 ||
20479           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20480         return SDValue();
20481
20482       Chain.push_back(V);
20483       continue;
20484
20485     case X86ISD::PSHUFHW:
20486       // Check that the high words (being shuffled) are the identity in the
20487       // dword shuffle, and the low words are self-contained.
20488       if (Mask[2] != 2 || Mask[3] != 3 ||
20489           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20490         return SDValue();
20491
20492       Chain.push_back(V);
20493       continue;
20494
20495     case X86ISD::UNPCKL:
20496     case X86ISD::UNPCKH:
20497       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20498       // shuffle into a preceding word shuffle.
20499       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20500           V.getSimpleValueType().getScalarType() != MVT::i16)
20501         return SDValue();
20502
20503       // Search for a half-shuffle which we can combine with.
20504       unsigned CombineOp =
20505           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20506       if (V.getOperand(0) != V.getOperand(1) ||
20507           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20508         return SDValue();
20509       Chain.push_back(V);
20510       V = V.getOperand(0);
20511       do {
20512         switch (V.getOpcode()) {
20513         default:
20514           return SDValue(); // Nothing to combine.
20515
20516         case X86ISD::PSHUFLW:
20517         case X86ISD::PSHUFHW:
20518           if (V.getOpcode() == CombineOp)
20519             break;
20520
20521           Chain.push_back(V);
20522
20523           // Fallthrough!
20524         case ISD::BITCAST:
20525           V = V.getOperand(0);
20526           continue;
20527         }
20528         break;
20529       } while (V.hasOneUse());
20530       break;
20531     }
20532     // Break out of the loop if we break out of the switch.
20533     break;
20534   }
20535
20536   if (!V.hasOneUse())
20537     // We fell out of the loop without finding a viable combining instruction.
20538     return SDValue();
20539
20540   // Merge this node's mask and our incoming mask.
20541   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20542   for (int &M : Mask)
20543     M = VMask[M];
20544   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20545                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20546
20547   // Rebuild the chain around this new shuffle.
20548   while (!Chain.empty()) {
20549     SDValue W = Chain.pop_back_val();
20550
20551     if (V.getValueType() != W.getOperand(0).getValueType())
20552       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20553
20554     switch (W.getOpcode()) {
20555     default:
20556       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20557
20558     case X86ISD::UNPCKL:
20559     case X86ISD::UNPCKH:
20560       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20561       break;
20562
20563     case X86ISD::PSHUFD:
20564     case X86ISD::PSHUFLW:
20565     case X86ISD::PSHUFHW:
20566       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20567       break;
20568     }
20569   }
20570   if (V.getValueType() != N.getValueType())
20571     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20572
20573   // Return the new chain to replace N.
20574   return V;
20575 }
20576
20577 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20578 ///
20579 /// We walk up the chain, skipping shuffles of the other half and looking
20580 /// through shuffles which switch halves trying to find a shuffle of the same
20581 /// pair of dwords.
20582 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20583                                         SelectionDAG &DAG,
20584                                         TargetLowering::DAGCombinerInfo &DCI) {
20585   assert(
20586       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20587       "Called with something other than an x86 128-bit half shuffle!");
20588   SDLoc DL(N);
20589   unsigned CombineOpcode = N.getOpcode();
20590
20591   // Walk up a single-use chain looking for a combinable shuffle.
20592   SDValue V = N.getOperand(0);
20593   for (; V.hasOneUse(); V = V.getOperand(0)) {
20594     switch (V.getOpcode()) {
20595     default:
20596       return false; // Nothing combined!
20597
20598     case ISD::BITCAST:
20599       // Skip bitcasts as we always know the type for the target specific
20600       // instructions.
20601       continue;
20602
20603     case X86ISD::PSHUFLW:
20604     case X86ISD::PSHUFHW:
20605       if (V.getOpcode() == CombineOpcode)
20606         break;
20607
20608       // Other-half shuffles are no-ops.
20609       continue;
20610     }
20611     // Break out of the loop if we break out of the switch.
20612     break;
20613   }
20614
20615   if (!V.hasOneUse())
20616     // We fell out of the loop without finding a viable combining instruction.
20617     return false;
20618
20619   // Combine away the bottom node as its shuffle will be accumulated into
20620   // a preceding shuffle.
20621   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20622
20623   // Record the old value.
20624   SDValue Old = V;
20625
20626   // Merge this node's mask and our incoming mask (adjusted to account for all
20627   // the pshufd instructions encountered).
20628   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20629   for (int &M : Mask)
20630     M = VMask[M];
20631   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20632                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20633
20634   // Check that the shuffles didn't cancel each other out. If not, we need to
20635   // combine to the new one.
20636   if (Old != V)
20637     // Replace the combinable shuffle with the combined one, updating all users
20638     // so that we re-evaluate the chain here.
20639     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20640
20641   return true;
20642 }
20643
20644 /// \brief Try to combine x86 target specific shuffles.
20645 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20646                                            TargetLowering::DAGCombinerInfo &DCI,
20647                                            const X86Subtarget *Subtarget) {
20648   SDLoc DL(N);
20649   MVT VT = N.getSimpleValueType();
20650   SmallVector<int, 4> Mask;
20651
20652   switch (N.getOpcode()) {
20653   case X86ISD::PSHUFD:
20654   case X86ISD::PSHUFLW:
20655   case X86ISD::PSHUFHW:
20656     Mask = getPSHUFShuffleMask(N);
20657     assert(Mask.size() == 4);
20658     break;
20659   default:
20660     return SDValue();
20661   }
20662
20663   // Nuke no-op shuffles that show up after combining.
20664   if (isNoopShuffleMask(Mask))
20665     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20666
20667   // Look for simplifications involving one or two shuffle instructions.
20668   SDValue V = N.getOperand(0);
20669   switch (N.getOpcode()) {
20670   default:
20671     break;
20672   case X86ISD::PSHUFLW:
20673   case X86ISD::PSHUFHW:
20674     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20675
20676     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20677       return SDValue(); // We combined away this shuffle, so we're done.
20678
20679     // See if this reduces to a PSHUFD which is no more expensive and can
20680     // combine with more operations. Note that it has to at least flip the
20681     // dwords as otherwise it would have been removed as a no-op.
20682     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20683       int DMask[] = {0, 1, 2, 3};
20684       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20685       DMask[DOffset + 0] = DOffset + 1;
20686       DMask[DOffset + 1] = DOffset + 0;
20687       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20688       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20689       DCI.AddToWorklist(V.getNode());
20690       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20691                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20692       DCI.AddToWorklist(V.getNode());
20693       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20694     }
20695
20696     // Look for shuffle patterns which can be implemented as a single unpack.
20697     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20698     // only works when we have a PSHUFD followed by two half-shuffles.
20699     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20700         (V.getOpcode() == X86ISD::PSHUFLW ||
20701          V.getOpcode() == X86ISD::PSHUFHW) &&
20702         V.getOpcode() != N.getOpcode() &&
20703         V.hasOneUse()) {
20704       SDValue D = V.getOperand(0);
20705       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20706         D = D.getOperand(0);
20707       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20708         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20709         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20710         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20711         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20712         int WordMask[8];
20713         for (int i = 0; i < 4; ++i) {
20714           WordMask[i + NOffset] = Mask[i] + NOffset;
20715           WordMask[i + VOffset] = VMask[i] + VOffset;
20716         }
20717         // Map the word mask through the DWord mask.
20718         int MappedMask[8];
20719         for (int i = 0; i < 8; ++i)
20720           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20721         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20722             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20723           // We can replace all three shuffles with an unpack.
20724           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20725           DCI.AddToWorklist(V.getNode());
20726           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20727                                                 : X86ISD::UNPCKH,
20728                              DL, VT, V, V);
20729         }
20730       }
20731     }
20732
20733     break;
20734
20735   case X86ISD::PSHUFD:
20736     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20737       return NewN;
20738
20739     break;
20740   }
20741
20742   return SDValue();
20743 }
20744
20745 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20746 ///
20747 /// We combine this directly on the abstract vector shuffle nodes so it is
20748 /// easier to generically match. We also insert dummy vector shuffle nodes for
20749 /// the operands which explicitly discard the lanes which are unused by this
20750 /// operation to try to flow through the rest of the combiner the fact that
20751 /// they're unused.
20752 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20753   SDLoc DL(N);
20754   EVT VT = N->getValueType(0);
20755
20756   // We only handle target-independent shuffles.
20757   // FIXME: It would be easy and harmless to use the target shuffle mask
20758   // extraction tool to support more.
20759   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20760     return SDValue();
20761
20762   auto *SVN = cast<ShuffleVectorSDNode>(N);
20763   ArrayRef<int> Mask = SVN->getMask();
20764   SDValue V1 = N->getOperand(0);
20765   SDValue V2 = N->getOperand(1);
20766
20767   // We require the first shuffle operand to be the SUB node, and the second to
20768   // be the ADD node.
20769   // FIXME: We should support the commuted patterns.
20770   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20771     return SDValue();
20772
20773   // If there are other uses of these operations we can't fold them.
20774   if (!V1->hasOneUse() || !V2->hasOneUse())
20775     return SDValue();
20776
20777   // Ensure that both operations have the same operands. Note that we can
20778   // commute the FADD operands.
20779   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20780   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20781       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20782     return SDValue();
20783
20784   // We're looking for blends between FADD and FSUB nodes. We insist on these
20785   // nodes being lined up in a specific expected pattern.
20786   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20787         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20788         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20789     return SDValue();
20790
20791   // Only specific types are legal at this point, assert so we notice if and
20792   // when these change.
20793   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20794           VT == MVT::v4f64) &&
20795          "Unknown vector type encountered!");
20796
20797   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20798 }
20799
20800 /// PerformShuffleCombine - Performs several different shuffle combines.
20801 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20802                                      TargetLowering::DAGCombinerInfo &DCI,
20803                                      const X86Subtarget *Subtarget) {
20804   SDLoc dl(N);
20805   SDValue N0 = N->getOperand(0);
20806   SDValue N1 = N->getOperand(1);
20807   EVT VT = N->getValueType(0);
20808
20809   // Don't create instructions with illegal types after legalize types has run.
20810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20811   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20812     return SDValue();
20813
20814   // If we have legalized the vector types, look for blends of FADD and FSUB
20815   // nodes that we can fuse into an ADDSUB node.
20816   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20817     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20818       return AddSub;
20819
20820   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20821   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20822       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20823     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20824
20825   // During Type Legalization, when promoting illegal vector types,
20826   // the backend might introduce new shuffle dag nodes and bitcasts.
20827   //
20828   // This code performs the following transformation:
20829   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20830   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20831   //
20832   // We do this only if both the bitcast and the BINOP dag nodes have
20833   // one use. Also, perform this transformation only if the new binary
20834   // operation is legal. This is to avoid introducing dag nodes that
20835   // potentially need to be further expanded (or custom lowered) into a
20836   // less optimal sequence of dag nodes.
20837   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20838       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20839       N0.getOpcode() == ISD::BITCAST) {
20840     SDValue BC0 = N0.getOperand(0);
20841     EVT SVT = BC0.getValueType();
20842     unsigned Opcode = BC0.getOpcode();
20843     unsigned NumElts = VT.getVectorNumElements();
20844
20845     if (BC0.hasOneUse() && SVT.isVector() &&
20846         SVT.getVectorNumElements() * 2 == NumElts &&
20847         TLI.isOperationLegal(Opcode, VT)) {
20848       bool CanFold = false;
20849       switch (Opcode) {
20850       default : break;
20851       case ISD::ADD :
20852       case ISD::FADD :
20853       case ISD::SUB :
20854       case ISD::FSUB :
20855       case ISD::MUL :
20856       case ISD::FMUL :
20857         CanFold = true;
20858       }
20859
20860       unsigned SVTNumElts = SVT.getVectorNumElements();
20861       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20862       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20863         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20864       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20865         CanFold = SVOp->getMaskElt(i) < 0;
20866
20867       if (CanFold) {
20868         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20869         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20870         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20871         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20872       }
20873     }
20874   }
20875
20876   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20877   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20878   // consecutive, non-overlapping, and in the right order.
20879   SmallVector<SDValue, 16> Elts;
20880   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20881     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20882
20883   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20884   if (LD.getNode())
20885     return LD;
20886
20887   if (isTargetShuffle(N->getOpcode())) {
20888     SDValue Shuffle =
20889         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20890     if (Shuffle.getNode())
20891       return Shuffle;
20892
20893     // Try recursively combining arbitrary sequences of x86 shuffle
20894     // instructions into higher-order shuffles. We do this after combining
20895     // specific PSHUF instruction sequences into their minimal form so that we
20896     // can evaluate how many specialized shuffle instructions are involved in
20897     // a particular chain.
20898     SmallVector<int, 1> NonceMask; // Just a placeholder.
20899     NonceMask.push_back(0);
20900     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20901                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20902                                       DCI, Subtarget))
20903       return SDValue(); // This routine will use CombineTo to replace N.
20904   }
20905
20906   return SDValue();
20907 }
20908
20909 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20910 /// specific shuffle of a load can be folded into a single element load.
20911 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20912 /// shuffles have been custom lowered so we need to handle those here.
20913 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20914                                          TargetLowering::DAGCombinerInfo &DCI) {
20915   if (DCI.isBeforeLegalizeOps())
20916     return SDValue();
20917
20918   SDValue InVec = N->getOperand(0);
20919   SDValue EltNo = N->getOperand(1);
20920
20921   if (!isa<ConstantSDNode>(EltNo))
20922     return SDValue();
20923
20924   EVT OriginalVT = InVec.getValueType();
20925
20926   if (InVec.getOpcode() == ISD::BITCAST) {
20927     // Don't duplicate a load with other uses.
20928     if (!InVec.hasOneUse())
20929       return SDValue();
20930     EVT BCVT = InVec.getOperand(0).getValueType();
20931     if (!BCVT.isVector() ||
20932         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20933       return SDValue();
20934     InVec = InVec.getOperand(0);
20935   }
20936
20937   EVT CurrentVT = InVec.getValueType();
20938
20939   if (!isTargetShuffle(InVec.getOpcode()))
20940     return SDValue();
20941
20942   // Don't duplicate a load with other uses.
20943   if (!InVec.hasOneUse())
20944     return SDValue();
20945
20946   SmallVector<int, 16> ShuffleMask;
20947   bool UnaryShuffle;
20948   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20949                             ShuffleMask, UnaryShuffle))
20950     return SDValue();
20951
20952   // Select the input vector, guarding against out of range extract vector.
20953   unsigned NumElems = CurrentVT.getVectorNumElements();
20954   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20955   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20956   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20957                                          : InVec.getOperand(1);
20958
20959   // If inputs to shuffle are the same for both ops, then allow 2 uses
20960   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20961                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20962
20963   if (LdNode.getOpcode() == ISD::BITCAST) {
20964     // Don't duplicate a load with other uses.
20965     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20966       return SDValue();
20967
20968     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20969     LdNode = LdNode.getOperand(0);
20970   }
20971
20972   if (!ISD::isNormalLoad(LdNode.getNode()))
20973     return SDValue();
20974
20975   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20976
20977   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20978     return SDValue();
20979
20980   EVT EltVT = N->getValueType(0);
20981   // If there's a bitcast before the shuffle, check if the load type and
20982   // alignment is valid.
20983   unsigned Align = LN0->getAlignment();
20984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20985   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20986       EltVT.getTypeForEVT(*DAG.getContext()));
20987
20988   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20989     return SDValue();
20990
20991   // All checks match so transform back to vector_shuffle so that DAG combiner
20992   // can finish the job
20993   SDLoc dl(N);
20994
20995   // Create shuffle node taking into account the case that its a unary shuffle
20996   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20997                                    : InVec.getOperand(1);
20998   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20999                                  InVec.getOperand(0), Shuffle,
21000                                  &ShuffleMask[0]);
21001   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
21002   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21003                      EltNo);
21004 }
21005
21006 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21007 /// special and don't usually play with other vector types, it's better to
21008 /// handle them early to be sure we emit efficient code by avoiding
21009 /// store-load conversions.
21010 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21011   if (N->getValueType(0) != MVT::x86mmx ||
21012       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21013       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21014     return SDValue();
21015
21016   SDValue V = N->getOperand(0);
21017   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21018   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21019     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21020                        N->getValueType(0), V.getOperand(0));
21021
21022   return SDValue();
21023 }
21024
21025 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21026 /// generation and convert it from being a bunch of shuffles and extracts
21027 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21028 /// storing the value and loading scalars back, while for x64 we should
21029 /// use 64-bit extracts and shifts.
21030 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21031                                          TargetLowering::DAGCombinerInfo &DCI) {
21032   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
21033   if (NewOp.getNode())
21034     return NewOp;
21035
21036   SDValue InputVector = N->getOperand(0);
21037   SDLoc dl(InputVector);
21038   // Detect mmx to i32 conversion through a v2i32 elt extract.
21039   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21040       N->getValueType(0) == MVT::i32 &&
21041       InputVector.getValueType() == MVT::v2i32) {
21042
21043     // The bitcast source is a direct mmx result.
21044     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21045     if (MMXSrc.getValueType() == MVT::x86mmx)
21046       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21047                          N->getValueType(0),
21048                          InputVector.getNode()->getOperand(0));
21049
21050     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21051     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21052     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21053         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21054         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21055         MMXSrcOp.getValueType() == MVT::v1i64 &&
21056         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21057       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21058                          N->getValueType(0),
21059                          MMXSrcOp.getOperand(0));
21060   }
21061
21062   EVT VT = N->getValueType(0);
21063
21064   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21065       InputVector.getOpcode() == ISD::BITCAST &&
21066       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21067     uint64_t ExtractedElt =
21068           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21069     uint64_t InputValue =
21070           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21071     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21072     return DAG.getConstant(Res, dl, MVT::i1);
21073   }
21074   // Only operate on vectors of 4 elements, where the alternative shuffling
21075   // gets to be more expensive.
21076   if (InputVector.getValueType() != MVT::v4i32)
21077     return SDValue();
21078
21079   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21080   // single use which is a sign-extend or zero-extend, and all elements are
21081   // used.
21082   SmallVector<SDNode *, 4> Uses;
21083   unsigned ExtractedElements = 0;
21084   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21085        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21086     if (UI.getUse().getResNo() != InputVector.getResNo())
21087       return SDValue();
21088
21089     SDNode *Extract = *UI;
21090     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21091       return SDValue();
21092
21093     if (Extract->getValueType(0) != MVT::i32)
21094       return SDValue();
21095     if (!Extract->hasOneUse())
21096       return SDValue();
21097     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21098         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21099       return SDValue();
21100     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21101       return SDValue();
21102
21103     // Record which element was extracted.
21104     ExtractedElements |=
21105       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21106
21107     Uses.push_back(Extract);
21108   }
21109
21110   // If not all the elements were used, this may not be worthwhile.
21111   if (ExtractedElements != 15)
21112     return SDValue();
21113
21114   // Ok, we've now decided to do the transformation.
21115   // If 64-bit shifts are legal, use the extract-shift sequence,
21116   // otherwise bounce the vector off the cache.
21117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21118   SDValue Vals[4];
21119
21120   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21121     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
21122     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21123     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21124       DAG.getConstant(0, dl, VecIdxTy));
21125     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21126       DAG.getConstant(1, dl, VecIdxTy));
21127
21128     SDValue ShAmt = DAG.getConstant(32, dl,
21129       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21130     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21131     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21132       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21133     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21134     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21135       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21136   } else {
21137     // Store the value to a temporary stack slot.
21138     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21139     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21140       MachinePointerInfo(), false, false, 0);
21141
21142     EVT ElementType = InputVector.getValueType().getVectorElementType();
21143     unsigned EltSize = ElementType.getSizeInBits() / 8;
21144
21145     // Replace each use (extract) with a load of the appropriate element.
21146     for (unsigned i = 0; i < 4; ++i) {
21147       uint64_t Offset = EltSize * i;
21148       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21149
21150       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21151                                        StackPtr, OffsetVal);
21152
21153       // Load the scalar.
21154       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21155                             ScalarAddr, MachinePointerInfo(),
21156                             false, false, false, 0);
21157
21158     }
21159   }
21160
21161   // Replace the extracts
21162   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21163     UE = Uses.end(); UI != UE; ++UI) {
21164     SDNode *Extract = *UI;
21165
21166     SDValue Idx = Extract->getOperand(1);
21167     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21168     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21169   }
21170
21171   // The replacement was made in place; don't return anything.
21172   return SDValue();
21173 }
21174
21175 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21176 static std::pair<unsigned, bool>
21177 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21178                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21179   if (!VT.isVector())
21180     return std::make_pair(0, false);
21181
21182   bool NeedSplit = false;
21183   switch (VT.getSimpleVT().SimpleTy) {
21184   default: return std::make_pair(0, false);
21185   case MVT::v4i64:
21186   case MVT::v2i64:
21187     if (!Subtarget->hasVLX())
21188       return std::make_pair(0, false);
21189     break;
21190   case MVT::v64i8:
21191   case MVT::v32i16:
21192     if (!Subtarget->hasBWI())
21193       return std::make_pair(0, false);
21194     break;
21195   case MVT::v16i32:
21196   case MVT::v8i64:
21197     if (!Subtarget->hasAVX512())
21198       return std::make_pair(0, false);
21199     break;
21200   case MVT::v32i8:
21201   case MVT::v16i16:
21202   case MVT::v8i32:
21203     if (!Subtarget->hasAVX2())
21204       NeedSplit = true;
21205     if (!Subtarget->hasAVX())
21206       return std::make_pair(0, false);
21207     break;
21208   case MVT::v16i8:
21209   case MVT::v8i16:
21210   case MVT::v4i32:
21211     if (!Subtarget->hasSSE2())
21212       return std::make_pair(0, false);
21213   }
21214
21215   // SSE2 has only a small subset of the operations.
21216   bool hasUnsigned = Subtarget->hasSSE41() ||
21217                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21218   bool hasSigned = Subtarget->hasSSE41() ||
21219                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21220
21221   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21222
21223   unsigned Opc = 0;
21224   // Check for x CC y ? x : y.
21225   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21226       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21227     switch (CC) {
21228     default: break;
21229     case ISD::SETULT:
21230     case ISD::SETULE:
21231       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21232     case ISD::SETUGT:
21233     case ISD::SETUGE:
21234       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21235     case ISD::SETLT:
21236     case ISD::SETLE:
21237       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21238     case ISD::SETGT:
21239     case ISD::SETGE:
21240       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21241     }
21242   // Check for x CC y ? y : x -- a min/max with reversed arms.
21243   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21244              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21245     switch (CC) {
21246     default: break;
21247     case ISD::SETULT:
21248     case ISD::SETULE:
21249       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21250     case ISD::SETUGT:
21251     case ISD::SETUGE:
21252       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21253     case ISD::SETLT:
21254     case ISD::SETLE:
21255       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21256     case ISD::SETGT:
21257     case ISD::SETGE:
21258       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21259     }
21260   }
21261
21262   return std::make_pair(Opc, NeedSplit);
21263 }
21264
21265 static SDValue
21266 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21267                                       const X86Subtarget *Subtarget) {
21268   SDLoc dl(N);
21269   SDValue Cond = N->getOperand(0);
21270   SDValue LHS = N->getOperand(1);
21271   SDValue RHS = N->getOperand(2);
21272
21273   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21274     SDValue CondSrc = Cond->getOperand(0);
21275     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21276       Cond = CondSrc->getOperand(0);
21277   }
21278
21279   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21280     return SDValue();
21281
21282   // A vselect where all conditions and data are constants can be optimized into
21283   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21284   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21285       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21286     return SDValue();
21287
21288   unsigned MaskValue = 0;
21289   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21290     return SDValue();
21291
21292   MVT VT = N->getSimpleValueType(0);
21293   unsigned NumElems = VT.getVectorNumElements();
21294   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21295   for (unsigned i = 0; i < NumElems; ++i) {
21296     // Be sure we emit undef where we can.
21297     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21298       ShuffleMask[i] = -1;
21299     else
21300       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21301   }
21302
21303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21304   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21305     return SDValue();
21306   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21307 }
21308
21309 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21310 /// nodes.
21311 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21312                                     TargetLowering::DAGCombinerInfo &DCI,
21313                                     const X86Subtarget *Subtarget) {
21314   SDLoc DL(N);
21315   SDValue Cond = N->getOperand(0);
21316   // Get the LHS/RHS of the select.
21317   SDValue LHS = N->getOperand(1);
21318   SDValue RHS = N->getOperand(2);
21319   EVT VT = LHS.getValueType();
21320   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21321
21322   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21323   // instructions match the semantics of the common C idiom x<y?x:y but not
21324   // x<=y?x:y, because of how they handle negative zero (which can be
21325   // ignored in unsafe-math mode).
21326   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21327   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21328       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21329       (Subtarget->hasSSE2() ||
21330        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21331     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21332
21333     unsigned Opcode = 0;
21334     // Check for x CC y ? x : y.
21335     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21336         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21337       switch (CC) {
21338       default: break;
21339       case ISD::SETULT:
21340         // Converting this to a min would handle NaNs incorrectly, and swapping
21341         // the operands would cause it to handle comparisons between positive
21342         // and negative zero incorrectly.
21343         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21344           if (!DAG.getTarget().Options.UnsafeFPMath &&
21345               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21346             break;
21347           std::swap(LHS, RHS);
21348         }
21349         Opcode = X86ISD::FMIN;
21350         break;
21351       case ISD::SETOLE:
21352         // Converting this to a min would handle comparisons between positive
21353         // and negative zero incorrectly.
21354         if (!DAG.getTarget().Options.UnsafeFPMath &&
21355             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21356           break;
21357         Opcode = X86ISD::FMIN;
21358         break;
21359       case ISD::SETULE:
21360         // Converting this to a min would handle both negative zeros and NaNs
21361         // incorrectly, but we can swap the operands to fix both.
21362         std::swap(LHS, RHS);
21363       case ISD::SETOLT:
21364       case ISD::SETLT:
21365       case ISD::SETLE:
21366         Opcode = X86ISD::FMIN;
21367         break;
21368
21369       case ISD::SETOGE:
21370         // Converting this to a max would handle comparisons between positive
21371         // and negative zero incorrectly.
21372         if (!DAG.getTarget().Options.UnsafeFPMath &&
21373             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21374           break;
21375         Opcode = X86ISD::FMAX;
21376         break;
21377       case ISD::SETUGT:
21378         // Converting this to a max would handle NaNs incorrectly, and swapping
21379         // the operands would cause it to handle comparisons between positive
21380         // and negative zero incorrectly.
21381         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21382           if (!DAG.getTarget().Options.UnsafeFPMath &&
21383               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21384             break;
21385           std::swap(LHS, RHS);
21386         }
21387         Opcode = X86ISD::FMAX;
21388         break;
21389       case ISD::SETUGE:
21390         // Converting this to a max would handle both negative zeros and NaNs
21391         // incorrectly, but we can swap the operands to fix both.
21392         std::swap(LHS, RHS);
21393       case ISD::SETOGT:
21394       case ISD::SETGT:
21395       case ISD::SETGE:
21396         Opcode = X86ISD::FMAX;
21397         break;
21398       }
21399     // Check for x CC y ? y : x -- a min/max with reversed arms.
21400     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21401                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21402       switch (CC) {
21403       default: break;
21404       case ISD::SETOGE:
21405         // Converting this to a min would handle comparisons between positive
21406         // and negative zero incorrectly, and swapping the operands would
21407         // cause it to handle NaNs incorrectly.
21408         if (!DAG.getTarget().Options.UnsafeFPMath &&
21409             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21410           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21411             break;
21412           std::swap(LHS, RHS);
21413         }
21414         Opcode = X86ISD::FMIN;
21415         break;
21416       case ISD::SETUGT:
21417         // Converting this to a min would handle NaNs incorrectly.
21418         if (!DAG.getTarget().Options.UnsafeFPMath &&
21419             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21420           break;
21421         Opcode = X86ISD::FMIN;
21422         break;
21423       case ISD::SETUGE:
21424         // Converting this to a min would handle both negative zeros and NaNs
21425         // incorrectly, but we can swap the operands to fix both.
21426         std::swap(LHS, RHS);
21427       case ISD::SETOGT:
21428       case ISD::SETGT:
21429       case ISD::SETGE:
21430         Opcode = X86ISD::FMIN;
21431         break;
21432
21433       case ISD::SETULT:
21434         // Converting this to a max would handle NaNs incorrectly.
21435         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21436           break;
21437         Opcode = X86ISD::FMAX;
21438         break;
21439       case ISD::SETOLE:
21440         // Converting this to a max would handle comparisons between positive
21441         // and negative zero incorrectly, and swapping the operands would
21442         // cause it to handle NaNs incorrectly.
21443         if (!DAG.getTarget().Options.UnsafeFPMath &&
21444             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21445           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21446             break;
21447           std::swap(LHS, RHS);
21448         }
21449         Opcode = X86ISD::FMAX;
21450         break;
21451       case ISD::SETULE:
21452         // Converting this to a max would handle both negative zeros and NaNs
21453         // incorrectly, but we can swap the operands to fix both.
21454         std::swap(LHS, RHS);
21455       case ISD::SETOLT:
21456       case ISD::SETLT:
21457       case ISD::SETLE:
21458         Opcode = X86ISD::FMAX;
21459         break;
21460       }
21461     }
21462
21463     if (Opcode)
21464       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21465   }
21466
21467   EVT CondVT = Cond.getValueType();
21468   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21469       CondVT.getVectorElementType() == MVT::i1) {
21470     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21471     // lowering on KNL. In this case we convert it to
21472     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21473     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21474     // Since SKX these selects have a proper lowering.
21475     EVT OpVT = LHS.getValueType();
21476     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21477         (OpVT.getVectorElementType() == MVT::i8 ||
21478          OpVT.getVectorElementType() == MVT::i16) &&
21479         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21480       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21481       DCI.AddToWorklist(Cond.getNode());
21482       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21483     }
21484   }
21485   // If this is a select between two integer constants, try to do some
21486   // optimizations.
21487   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21488     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21489       // Don't do this for crazy integer types.
21490       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21491         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21492         // so that TrueC (the true value) is larger than FalseC.
21493         bool NeedsCondInvert = false;
21494
21495         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21496             // Efficiently invertible.
21497             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21498              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21499               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21500           NeedsCondInvert = true;
21501           std::swap(TrueC, FalseC);
21502         }
21503
21504         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21505         if (FalseC->getAPIntValue() == 0 &&
21506             TrueC->getAPIntValue().isPowerOf2()) {
21507           if (NeedsCondInvert) // Invert the condition if needed.
21508             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21509                                DAG.getConstant(1, DL, Cond.getValueType()));
21510
21511           // Zero extend the condition if needed.
21512           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21513
21514           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21515           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21516                              DAG.getConstant(ShAmt, DL, MVT::i8));
21517         }
21518
21519         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21520         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21521           if (NeedsCondInvert) // Invert the condition if needed.
21522             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21523                                DAG.getConstant(1, DL, Cond.getValueType()));
21524
21525           // Zero extend the condition if needed.
21526           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21527                              FalseC->getValueType(0), Cond);
21528           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21529                              SDValue(FalseC, 0));
21530         }
21531
21532         // Optimize cases that will turn into an LEA instruction.  This requires
21533         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21534         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21535           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21536           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21537
21538           bool isFastMultiplier = false;
21539           if (Diff < 10) {
21540             switch ((unsigned char)Diff) {
21541               default: break;
21542               case 1:  // result = add base, cond
21543               case 2:  // result = lea base(    , cond*2)
21544               case 3:  // result = lea base(cond, cond*2)
21545               case 4:  // result = lea base(    , cond*4)
21546               case 5:  // result = lea base(cond, cond*4)
21547               case 8:  // result = lea base(    , cond*8)
21548               case 9:  // result = lea base(cond, cond*8)
21549                 isFastMultiplier = true;
21550                 break;
21551             }
21552           }
21553
21554           if (isFastMultiplier) {
21555             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21556             if (NeedsCondInvert) // Invert the condition if needed.
21557               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21558                                  DAG.getConstant(1, DL, Cond.getValueType()));
21559
21560             // Zero extend the condition if needed.
21561             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21562                                Cond);
21563             // Scale the condition by the difference.
21564             if (Diff != 1)
21565               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21566                                  DAG.getConstant(Diff, DL,
21567                                                  Cond.getValueType()));
21568
21569             // Add the base if non-zero.
21570             if (FalseC->getAPIntValue() != 0)
21571               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21572                                  SDValue(FalseC, 0));
21573             return Cond;
21574           }
21575         }
21576       }
21577   }
21578
21579   // Canonicalize max and min:
21580   // (x > y) ? x : y -> (x >= y) ? x : y
21581   // (x < y) ? x : y -> (x <= y) ? x : y
21582   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21583   // the need for an extra compare
21584   // against zero. e.g.
21585   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21586   // subl   %esi, %edi
21587   // testl  %edi, %edi
21588   // movl   $0, %eax
21589   // cmovgl %edi, %eax
21590   // =>
21591   // xorl   %eax, %eax
21592   // subl   %esi, $edi
21593   // cmovsl %eax, %edi
21594   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21595       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21596       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21597     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21598     switch (CC) {
21599     default: break;
21600     case ISD::SETLT:
21601     case ISD::SETGT: {
21602       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21603       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21604                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21605       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21606     }
21607     }
21608   }
21609
21610   // Early exit check
21611   if (!TLI.isTypeLegal(VT))
21612     return SDValue();
21613
21614   // Match VSELECTs into subs with unsigned saturation.
21615   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21616       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21617       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21618        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21619     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21620
21621     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21622     // left side invert the predicate to simplify logic below.
21623     SDValue Other;
21624     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21625       Other = RHS;
21626       CC = ISD::getSetCCInverse(CC, true);
21627     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21628       Other = LHS;
21629     }
21630
21631     if (Other.getNode() && Other->getNumOperands() == 2 &&
21632         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21633       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21634       SDValue CondRHS = Cond->getOperand(1);
21635
21636       // Look for a general sub with unsigned saturation first.
21637       // x >= y ? x-y : 0 --> subus x, y
21638       // x >  y ? x-y : 0 --> subus x, y
21639       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21640           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21641         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21642
21643       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21644         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21645           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21646             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21647               // If the RHS is a constant we have to reverse the const
21648               // canonicalization.
21649               // x > C-1 ? x+-C : 0 --> subus x, C
21650               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21651                   CondRHSConst->getAPIntValue() ==
21652                       (-OpRHSConst->getAPIntValue() - 1))
21653                 return DAG.getNode(
21654                     X86ISD::SUBUS, DL, VT, OpLHS,
21655                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21656
21657           // Another special case: If C was a sign bit, the sub has been
21658           // canonicalized into a xor.
21659           // FIXME: Would it be better to use computeKnownBits to determine
21660           //        whether it's safe to decanonicalize the xor?
21661           // x s< 0 ? x^C : 0 --> subus x, C
21662           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21663               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21664               OpRHSConst->getAPIntValue().isSignBit())
21665             // Note that we have to rebuild the RHS constant here to ensure we
21666             // don't rely on particular values of undef lanes.
21667             return DAG.getNode(
21668                 X86ISD::SUBUS, DL, VT, OpLHS,
21669                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21670         }
21671     }
21672   }
21673
21674   // Try to match a min/max vector operation.
21675   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21676     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21677     unsigned Opc = ret.first;
21678     bool NeedSplit = ret.second;
21679
21680     if (Opc && NeedSplit) {
21681       unsigned NumElems = VT.getVectorNumElements();
21682       // Extract the LHS vectors
21683       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21684       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21685
21686       // Extract the RHS vectors
21687       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21688       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21689
21690       // Create min/max for each subvector
21691       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21692       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21693
21694       // Merge the result
21695       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21696     } else if (Opc)
21697       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21698   }
21699
21700   // Simplify vector selection if condition value type matches vselect
21701   // operand type
21702   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21703     assert(Cond.getValueType().isVector() &&
21704            "vector select expects a vector selector!");
21705
21706     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21707     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21708
21709     // Try invert the condition if true value is not all 1s and false value
21710     // is not all 0s.
21711     if (!TValIsAllOnes && !FValIsAllZeros &&
21712         // Check if the selector will be produced by CMPP*/PCMP*
21713         Cond.getOpcode() == ISD::SETCC &&
21714         // Check if SETCC has already been promoted
21715         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21716       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21717       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21718
21719       if (TValIsAllZeros || FValIsAllOnes) {
21720         SDValue CC = Cond.getOperand(2);
21721         ISD::CondCode NewCC =
21722           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21723                                Cond.getOperand(0).getValueType().isInteger());
21724         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21725         std::swap(LHS, RHS);
21726         TValIsAllOnes = FValIsAllOnes;
21727         FValIsAllZeros = TValIsAllZeros;
21728       }
21729     }
21730
21731     if (TValIsAllOnes || FValIsAllZeros) {
21732       SDValue Ret;
21733
21734       if (TValIsAllOnes && FValIsAllZeros)
21735         Ret = Cond;
21736       else if (TValIsAllOnes)
21737         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21738                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21739       else if (FValIsAllZeros)
21740         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21741                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21742
21743       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21744     }
21745   }
21746
21747   // We should generate an X86ISD::BLENDI from a vselect if its argument
21748   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21749   // constants. This specific pattern gets generated when we split a
21750   // selector for a 512 bit vector in a machine without AVX512 (but with
21751   // 256-bit vectors), during legalization:
21752   //
21753   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21754   //
21755   // Iff we find this pattern and the build_vectors are built from
21756   // constants, we translate the vselect into a shuffle_vector that we
21757   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21758   if ((N->getOpcode() == ISD::VSELECT ||
21759        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21760       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
21761     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21762     if (Shuffle.getNode())
21763       return Shuffle;
21764   }
21765
21766   // If this is a *dynamic* select (non-constant condition) and we can match
21767   // this node with one of the variable blend instructions, restructure the
21768   // condition so that the blends can use the high bit of each element and use
21769   // SimplifyDemandedBits to simplify the condition operand.
21770   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21771       !DCI.isBeforeLegalize() &&
21772       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21773     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21774
21775     // Don't optimize vector selects that map to mask-registers.
21776     if (BitWidth == 1)
21777       return SDValue();
21778
21779     // We can only handle the cases where VSELECT is directly legal on the
21780     // subtarget. We custom lower VSELECT nodes with constant conditions and
21781     // this makes it hard to see whether a dynamic VSELECT will correctly
21782     // lower, so we both check the operation's status and explicitly handle the
21783     // cases where a *dynamic* blend will fail even though a constant-condition
21784     // blend could be custom lowered.
21785     // FIXME: We should find a better way to handle this class of problems.
21786     // Potentially, we should combine constant-condition vselect nodes
21787     // pre-legalization into shuffles and not mark as many types as custom
21788     // lowered.
21789     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21790       return SDValue();
21791     // FIXME: We don't support i16-element blends currently. We could and
21792     // should support them by making *all* the bits in the condition be set
21793     // rather than just the high bit and using an i8-element blend.
21794     if (VT.getScalarType() == MVT::i16)
21795       return SDValue();
21796     // Dynamic blending was only available from SSE4.1 onward.
21797     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21798       return SDValue();
21799     // Byte blends are only available in AVX2
21800     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21801         !Subtarget->hasAVX2())
21802       return SDValue();
21803
21804     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21805     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21806
21807     APInt KnownZero, KnownOne;
21808     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21809                                           DCI.isBeforeLegalizeOps());
21810     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21811         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21812                                  TLO)) {
21813       // If we changed the computation somewhere in the DAG, this change
21814       // will affect all users of Cond.
21815       // Make sure it is fine and update all the nodes so that we do not
21816       // use the generic VSELECT anymore. Otherwise, we may perform
21817       // wrong optimizations as we messed up with the actual expectation
21818       // for the vector boolean values.
21819       if (Cond != TLO.Old) {
21820         // Check all uses of that condition operand to check whether it will be
21821         // consumed by non-BLEND instructions, which may depend on all bits are
21822         // set properly.
21823         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21824              I != E; ++I)
21825           if (I->getOpcode() != ISD::VSELECT)
21826             // TODO: Add other opcodes eventually lowered into BLEND.
21827             return SDValue();
21828
21829         // Update all the users of the condition, before committing the change,
21830         // so that the VSELECT optimizations that expect the correct vector
21831         // boolean value will not be triggered.
21832         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21833              I != E; ++I)
21834           DAG.ReplaceAllUsesOfValueWith(
21835               SDValue(*I, 0),
21836               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21837                           Cond, I->getOperand(1), I->getOperand(2)));
21838         DCI.CommitTargetLoweringOpt(TLO);
21839         return SDValue();
21840       }
21841       // At this point, only Cond is changed. Change the condition
21842       // just for N to keep the opportunity to optimize all other
21843       // users their own way.
21844       DAG.ReplaceAllUsesOfValueWith(
21845           SDValue(N, 0),
21846           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21847                       TLO.New, N->getOperand(1), N->getOperand(2)));
21848       return SDValue();
21849     }
21850   }
21851
21852   return SDValue();
21853 }
21854
21855 // Check whether a boolean test is testing a boolean value generated by
21856 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21857 // code.
21858 //
21859 // Simplify the following patterns:
21860 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21861 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21862 // to (Op EFLAGS Cond)
21863 //
21864 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21865 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21866 // to (Op EFLAGS !Cond)
21867 //
21868 // where Op could be BRCOND or CMOV.
21869 //
21870 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21871   // Quit if not CMP and SUB with its value result used.
21872   if (Cmp.getOpcode() != X86ISD::CMP &&
21873       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21874       return SDValue();
21875
21876   // Quit if not used as a boolean value.
21877   if (CC != X86::COND_E && CC != X86::COND_NE)
21878     return SDValue();
21879
21880   // Check CMP operands. One of them should be 0 or 1 and the other should be
21881   // an SetCC or extended from it.
21882   SDValue Op1 = Cmp.getOperand(0);
21883   SDValue Op2 = Cmp.getOperand(1);
21884
21885   SDValue SetCC;
21886   const ConstantSDNode* C = nullptr;
21887   bool needOppositeCond = (CC == X86::COND_E);
21888   bool checkAgainstTrue = false; // Is it a comparison against 1?
21889
21890   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21891     SetCC = Op2;
21892   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21893     SetCC = Op1;
21894   else // Quit if all operands are not constants.
21895     return SDValue();
21896
21897   if (C->getZExtValue() == 1) {
21898     needOppositeCond = !needOppositeCond;
21899     checkAgainstTrue = true;
21900   } else if (C->getZExtValue() != 0)
21901     // Quit if the constant is neither 0 or 1.
21902     return SDValue();
21903
21904   bool truncatedToBoolWithAnd = false;
21905   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21906   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21907          SetCC.getOpcode() == ISD::TRUNCATE ||
21908          SetCC.getOpcode() == ISD::AND) {
21909     if (SetCC.getOpcode() == ISD::AND) {
21910       int OpIdx = -1;
21911       ConstantSDNode *CS;
21912       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21913           CS->getZExtValue() == 1)
21914         OpIdx = 1;
21915       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21916           CS->getZExtValue() == 1)
21917         OpIdx = 0;
21918       if (OpIdx == -1)
21919         break;
21920       SetCC = SetCC.getOperand(OpIdx);
21921       truncatedToBoolWithAnd = true;
21922     } else
21923       SetCC = SetCC.getOperand(0);
21924   }
21925
21926   switch (SetCC.getOpcode()) {
21927   case X86ISD::SETCC_CARRY:
21928     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21929     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21930     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21931     // truncated to i1 using 'and'.
21932     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21933       break;
21934     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21935            "Invalid use of SETCC_CARRY!");
21936     // FALL THROUGH
21937   case X86ISD::SETCC:
21938     // Set the condition code or opposite one if necessary.
21939     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21940     if (needOppositeCond)
21941       CC = X86::GetOppositeBranchCondition(CC);
21942     return SetCC.getOperand(1);
21943   case X86ISD::CMOV: {
21944     // Check whether false/true value has canonical one, i.e. 0 or 1.
21945     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21946     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21947     // Quit if true value is not a constant.
21948     if (!TVal)
21949       return SDValue();
21950     // Quit if false value is not a constant.
21951     if (!FVal) {
21952       SDValue Op = SetCC.getOperand(0);
21953       // Skip 'zext' or 'trunc' node.
21954       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21955           Op.getOpcode() == ISD::TRUNCATE)
21956         Op = Op.getOperand(0);
21957       // A special case for rdrand/rdseed, where 0 is set if false cond is
21958       // found.
21959       if ((Op.getOpcode() != X86ISD::RDRAND &&
21960            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21961         return SDValue();
21962     }
21963     // Quit if false value is not the constant 0 or 1.
21964     bool FValIsFalse = true;
21965     if (FVal && FVal->getZExtValue() != 0) {
21966       if (FVal->getZExtValue() != 1)
21967         return SDValue();
21968       // If FVal is 1, opposite cond is needed.
21969       needOppositeCond = !needOppositeCond;
21970       FValIsFalse = false;
21971     }
21972     // Quit if TVal is not the constant opposite of FVal.
21973     if (FValIsFalse && TVal->getZExtValue() != 1)
21974       return SDValue();
21975     if (!FValIsFalse && TVal->getZExtValue() != 0)
21976       return SDValue();
21977     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21978     if (needOppositeCond)
21979       CC = X86::GetOppositeBranchCondition(CC);
21980     return SetCC.getOperand(3);
21981   }
21982   }
21983
21984   return SDValue();
21985 }
21986
21987 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21988 /// Match:
21989 ///   (X86or (X86setcc) (X86setcc))
21990 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21991 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21992                                            X86::CondCode &CC1, SDValue &Flags,
21993                                            bool &isAnd) {
21994   if (Cond->getOpcode() == X86ISD::CMP) {
21995     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21996     if (!CondOp1C || !CondOp1C->isNullValue())
21997       return false;
21998
21999     Cond = Cond->getOperand(0);
22000   }
22001
22002   isAnd = false;
22003
22004   SDValue SetCC0, SetCC1;
22005   switch (Cond->getOpcode()) {
22006   default: return false;
22007   case ISD::AND:
22008   case X86ISD::AND:
22009     isAnd = true;
22010     // fallthru
22011   case ISD::OR:
22012   case X86ISD::OR:
22013     SetCC0 = Cond->getOperand(0);
22014     SetCC1 = Cond->getOperand(1);
22015     break;
22016   };
22017
22018   // Make sure we have SETCC nodes, using the same flags value.
22019   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22020       SetCC1.getOpcode() != X86ISD::SETCC ||
22021       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22022     return false;
22023
22024   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22025   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22026   Flags = SetCC0->getOperand(1);
22027   return true;
22028 }
22029
22030 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22031 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22032                                   TargetLowering::DAGCombinerInfo &DCI,
22033                                   const X86Subtarget *Subtarget) {
22034   SDLoc DL(N);
22035
22036   // If the flag operand isn't dead, don't touch this CMOV.
22037   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22038     return SDValue();
22039
22040   SDValue FalseOp = N->getOperand(0);
22041   SDValue TrueOp = N->getOperand(1);
22042   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22043   SDValue Cond = N->getOperand(3);
22044
22045   if (CC == X86::COND_E || CC == X86::COND_NE) {
22046     switch (Cond.getOpcode()) {
22047     default: break;
22048     case X86ISD::BSR:
22049     case X86ISD::BSF:
22050       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22051       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22052         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22053     }
22054   }
22055
22056   SDValue Flags;
22057
22058   Flags = checkBoolTestSetCCCombine(Cond, CC);
22059   if (Flags.getNode() &&
22060       // Extra check as FCMOV only supports a subset of X86 cond.
22061       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22062     SDValue Ops[] = { FalseOp, TrueOp,
22063                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22064     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22065   }
22066
22067   // If this is a select between two integer constants, try to do some
22068   // optimizations.  Note that the operands are ordered the opposite of SELECT
22069   // operands.
22070   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22071     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22072       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22073       // larger than FalseC (the false value).
22074       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22075         CC = X86::GetOppositeBranchCondition(CC);
22076         std::swap(TrueC, FalseC);
22077         std::swap(TrueOp, FalseOp);
22078       }
22079
22080       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22081       // This is efficient for any integer data type (including i8/i16) and
22082       // shift amount.
22083       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22084         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22085                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22086
22087         // Zero extend the condition if needed.
22088         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22089
22090         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22091         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22092                            DAG.getConstant(ShAmt, DL, MVT::i8));
22093         if (N->getNumValues() == 2)  // Dead flag value?
22094           return DCI.CombineTo(N, Cond, SDValue());
22095         return Cond;
22096       }
22097
22098       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22099       // for any integer data type, including i8/i16.
22100       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22101         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22102                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22103
22104         // Zero extend the condition if needed.
22105         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22106                            FalseC->getValueType(0), Cond);
22107         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22108                            SDValue(FalseC, 0));
22109
22110         if (N->getNumValues() == 2)  // Dead flag value?
22111           return DCI.CombineTo(N, Cond, SDValue());
22112         return Cond;
22113       }
22114
22115       // Optimize cases that will turn into an LEA instruction.  This requires
22116       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22117       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22118         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22119         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22120
22121         bool isFastMultiplier = false;
22122         if (Diff < 10) {
22123           switch ((unsigned char)Diff) {
22124           default: break;
22125           case 1:  // result = add base, cond
22126           case 2:  // result = lea base(    , cond*2)
22127           case 3:  // result = lea base(cond, cond*2)
22128           case 4:  // result = lea base(    , cond*4)
22129           case 5:  // result = lea base(cond, cond*4)
22130           case 8:  // result = lea base(    , cond*8)
22131           case 9:  // result = lea base(cond, cond*8)
22132             isFastMultiplier = true;
22133             break;
22134           }
22135         }
22136
22137         if (isFastMultiplier) {
22138           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22139           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22140                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22141           // Zero extend the condition if needed.
22142           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22143                              Cond);
22144           // Scale the condition by the difference.
22145           if (Diff != 1)
22146             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22147                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22148
22149           // Add the base if non-zero.
22150           if (FalseC->getAPIntValue() != 0)
22151             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22152                                SDValue(FalseC, 0));
22153           if (N->getNumValues() == 2)  // Dead flag value?
22154             return DCI.CombineTo(N, Cond, SDValue());
22155           return Cond;
22156         }
22157       }
22158     }
22159   }
22160
22161   // Handle these cases:
22162   //   (select (x != c), e, c) -> select (x != c), e, x),
22163   //   (select (x == c), c, e) -> select (x == c), x, e)
22164   // where the c is an integer constant, and the "select" is the combination
22165   // of CMOV and CMP.
22166   //
22167   // The rationale for this change is that the conditional-move from a constant
22168   // needs two instructions, however, conditional-move from a register needs
22169   // only one instruction.
22170   //
22171   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22172   //  some instruction-combining opportunities. This opt needs to be
22173   //  postponed as late as possible.
22174   //
22175   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22176     // the DCI.xxxx conditions are provided to postpone the optimization as
22177     // late as possible.
22178
22179     ConstantSDNode *CmpAgainst = nullptr;
22180     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22181         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22182         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22183
22184       if (CC == X86::COND_NE &&
22185           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22186         CC = X86::GetOppositeBranchCondition(CC);
22187         std::swap(TrueOp, FalseOp);
22188       }
22189
22190       if (CC == X86::COND_E &&
22191           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22192         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22193                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22194         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22195       }
22196     }
22197   }
22198
22199   // Fold and/or of setcc's to double CMOV:
22200   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22201   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22202   //
22203   // This combine lets us generate:
22204   //   cmovcc1 (jcc1 if we don't have CMOV)
22205   //   cmovcc2 (same)
22206   // instead of:
22207   //   setcc1
22208   //   setcc2
22209   //   and/or
22210   //   cmovne (jne if we don't have CMOV)
22211   // When we can't use the CMOV instruction, it might increase branch
22212   // mispredicts.
22213   // When we can use CMOV, or when there is no mispredict, this improves
22214   // throughput and reduces register pressure.
22215   //
22216   if (CC == X86::COND_NE) {
22217     SDValue Flags;
22218     X86::CondCode CC0, CC1;
22219     bool isAndSetCC;
22220     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22221       if (isAndSetCC) {
22222         std::swap(FalseOp, TrueOp);
22223         CC0 = X86::GetOppositeBranchCondition(CC0);
22224         CC1 = X86::GetOppositeBranchCondition(CC1);
22225       }
22226
22227       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22228         Flags};
22229       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22230       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22231       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22232       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22233       return CMOV;
22234     }
22235   }
22236
22237   return SDValue();
22238 }
22239
22240 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22241                                                 const X86Subtarget *Subtarget) {
22242   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22243   switch (IntNo) {
22244   default: return SDValue();
22245   // SSE/AVX/AVX2 blend intrinsics.
22246   case Intrinsic::x86_avx2_pblendvb:
22247     // Don't try to simplify this intrinsic if we don't have AVX2.
22248     if (!Subtarget->hasAVX2())
22249       return SDValue();
22250     // FALL-THROUGH
22251   case Intrinsic::x86_avx_blendv_pd_256:
22252   case Intrinsic::x86_avx_blendv_ps_256:
22253     // Don't try to simplify this intrinsic if we don't have AVX.
22254     if (!Subtarget->hasAVX())
22255       return SDValue();
22256     // FALL-THROUGH
22257   case Intrinsic::x86_sse41_blendvps:
22258   case Intrinsic::x86_sse41_blendvpd:
22259   case Intrinsic::x86_sse41_pblendvb: {
22260     SDValue Op0 = N->getOperand(1);
22261     SDValue Op1 = N->getOperand(2);
22262     SDValue Mask = N->getOperand(3);
22263
22264     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22265     if (!Subtarget->hasSSE41())
22266       return SDValue();
22267
22268     // fold (blend A, A, Mask) -> A
22269     if (Op0 == Op1)
22270       return Op0;
22271     // fold (blend A, B, allZeros) -> A
22272     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22273       return Op0;
22274     // fold (blend A, B, allOnes) -> B
22275     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22276       return Op1;
22277
22278     // Simplify the case where the mask is a constant i32 value.
22279     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22280       if (C->isNullValue())
22281         return Op0;
22282       if (C->isAllOnesValue())
22283         return Op1;
22284     }
22285
22286     return SDValue();
22287   }
22288
22289   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22290   case Intrinsic::x86_sse2_psrai_w:
22291   case Intrinsic::x86_sse2_psrai_d:
22292   case Intrinsic::x86_avx2_psrai_w:
22293   case Intrinsic::x86_avx2_psrai_d:
22294   case Intrinsic::x86_sse2_psra_w:
22295   case Intrinsic::x86_sse2_psra_d:
22296   case Intrinsic::x86_avx2_psra_w:
22297   case Intrinsic::x86_avx2_psra_d: {
22298     SDValue Op0 = N->getOperand(1);
22299     SDValue Op1 = N->getOperand(2);
22300     EVT VT = Op0.getValueType();
22301     assert(VT.isVector() && "Expected a vector type!");
22302
22303     if (isa<BuildVectorSDNode>(Op1))
22304       Op1 = Op1.getOperand(0);
22305
22306     if (!isa<ConstantSDNode>(Op1))
22307       return SDValue();
22308
22309     EVT SVT = VT.getVectorElementType();
22310     unsigned SVTBits = SVT.getSizeInBits();
22311
22312     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22313     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22314     uint64_t ShAmt = C.getZExtValue();
22315
22316     // Don't try to convert this shift into a ISD::SRA if the shift
22317     // count is bigger than or equal to the element size.
22318     if (ShAmt >= SVTBits)
22319       return SDValue();
22320
22321     // Trivial case: if the shift count is zero, then fold this
22322     // into the first operand.
22323     if (ShAmt == 0)
22324       return Op0;
22325
22326     // Replace this packed shift intrinsic with a target independent
22327     // shift dag node.
22328     SDLoc DL(N);
22329     SDValue Splat = DAG.getConstant(C, DL, VT);
22330     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22331   }
22332   }
22333 }
22334
22335 /// PerformMulCombine - Optimize a single multiply with constant into two
22336 /// in order to implement it with two cheaper instructions, e.g.
22337 /// LEA + SHL, LEA + LEA.
22338 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22339                                  TargetLowering::DAGCombinerInfo &DCI) {
22340   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22341     return SDValue();
22342
22343   EVT VT = N->getValueType(0);
22344   if (VT != MVT::i64 && VT != MVT::i32)
22345     return SDValue();
22346
22347   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22348   if (!C)
22349     return SDValue();
22350   uint64_t MulAmt = C->getZExtValue();
22351   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22352     return SDValue();
22353
22354   uint64_t MulAmt1 = 0;
22355   uint64_t MulAmt2 = 0;
22356   if ((MulAmt % 9) == 0) {
22357     MulAmt1 = 9;
22358     MulAmt2 = MulAmt / 9;
22359   } else if ((MulAmt % 5) == 0) {
22360     MulAmt1 = 5;
22361     MulAmt2 = MulAmt / 5;
22362   } else if ((MulAmt % 3) == 0) {
22363     MulAmt1 = 3;
22364     MulAmt2 = MulAmt / 3;
22365   }
22366   if (MulAmt2 &&
22367       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22368     SDLoc DL(N);
22369
22370     if (isPowerOf2_64(MulAmt2) &&
22371         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22372       // If second multiplifer is pow2, issue it first. We want the multiply by
22373       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22374       // is an add.
22375       std::swap(MulAmt1, MulAmt2);
22376
22377     SDValue NewMul;
22378     if (isPowerOf2_64(MulAmt1))
22379       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22380                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22381     else
22382       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22383                            DAG.getConstant(MulAmt1, DL, VT));
22384
22385     if (isPowerOf2_64(MulAmt2))
22386       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22387                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22388     else
22389       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22390                            DAG.getConstant(MulAmt2, DL, VT));
22391
22392     // Do not add new nodes to DAG combiner worklist.
22393     DCI.CombineTo(N, NewMul, false);
22394   }
22395   return SDValue();
22396 }
22397
22398 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22399   SDValue N0 = N->getOperand(0);
22400   SDValue N1 = N->getOperand(1);
22401   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22402   EVT VT = N0.getValueType();
22403
22404   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22405   // since the result of setcc_c is all zero's or all ones.
22406   if (VT.isInteger() && !VT.isVector() &&
22407       N1C && N0.getOpcode() == ISD::AND &&
22408       N0.getOperand(1).getOpcode() == ISD::Constant) {
22409     SDValue N00 = N0.getOperand(0);
22410     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22411         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22412           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22413          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22414       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22415       APInt ShAmt = N1C->getAPIntValue();
22416       Mask = Mask.shl(ShAmt);
22417       if (Mask != 0) {
22418         SDLoc DL(N);
22419         return DAG.getNode(ISD::AND, DL, VT,
22420                            N00, DAG.getConstant(Mask, DL, VT));
22421       }
22422     }
22423   }
22424
22425   // Hardware support for vector shifts is sparse which makes us scalarize the
22426   // vector operations in many cases. Also, on sandybridge ADD is faster than
22427   // shl.
22428   // (shl V, 1) -> add V,V
22429   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22430     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22431       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22432       // We shift all of the values by one. In many cases we do not have
22433       // hardware support for this operation. This is better expressed as an ADD
22434       // of two values.
22435       if (N1SplatC->getZExtValue() == 1)
22436         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22437     }
22438
22439   return SDValue();
22440 }
22441
22442 /// \brief Returns a vector of 0s if the node in input is a vector logical
22443 /// shift by a constant amount which is known to be bigger than or equal
22444 /// to the vector element size in bits.
22445 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22446                                       const X86Subtarget *Subtarget) {
22447   EVT VT = N->getValueType(0);
22448
22449   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22450       (!Subtarget->hasInt256() ||
22451        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22452     return SDValue();
22453
22454   SDValue Amt = N->getOperand(1);
22455   SDLoc DL(N);
22456   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22457     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22458       APInt ShiftAmt = AmtSplat->getAPIntValue();
22459       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22460
22461       // SSE2/AVX2 logical shifts always return a vector of 0s
22462       // if the shift amount is bigger than or equal to
22463       // the element size. The constant shift amount will be
22464       // encoded as a 8-bit immediate.
22465       if (ShiftAmt.trunc(8).uge(MaxAmount))
22466         return getZeroVector(VT, Subtarget, DAG, DL);
22467     }
22468
22469   return SDValue();
22470 }
22471
22472 /// PerformShiftCombine - Combine shifts.
22473 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22474                                    TargetLowering::DAGCombinerInfo &DCI,
22475                                    const X86Subtarget *Subtarget) {
22476   if (N->getOpcode() == ISD::SHL) {
22477     SDValue V = PerformSHLCombine(N, DAG);
22478     if (V.getNode()) return V;
22479   }
22480
22481   if (N->getOpcode() != ISD::SRA) {
22482     // Try to fold this logical shift into a zero vector.
22483     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22484     if (V.getNode()) return V;
22485   }
22486
22487   return SDValue();
22488 }
22489
22490 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22491 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22492 // and friends.  Likewise for OR -> CMPNEQSS.
22493 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22494                             TargetLowering::DAGCombinerInfo &DCI,
22495                             const X86Subtarget *Subtarget) {
22496   unsigned opcode;
22497
22498   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22499   // we're requiring SSE2 for both.
22500   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22501     SDValue N0 = N->getOperand(0);
22502     SDValue N1 = N->getOperand(1);
22503     SDValue CMP0 = N0->getOperand(1);
22504     SDValue CMP1 = N1->getOperand(1);
22505     SDLoc DL(N);
22506
22507     // The SETCCs should both refer to the same CMP.
22508     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22509       return SDValue();
22510
22511     SDValue CMP00 = CMP0->getOperand(0);
22512     SDValue CMP01 = CMP0->getOperand(1);
22513     EVT     VT    = CMP00.getValueType();
22514
22515     if (VT == MVT::f32 || VT == MVT::f64) {
22516       bool ExpectingFlags = false;
22517       // Check for any users that want flags:
22518       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22519            !ExpectingFlags && UI != UE; ++UI)
22520         switch (UI->getOpcode()) {
22521         default:
22522         case ISD::BR_CC:
22523         case ISD::BRCOND:
22524         case ISD::SELECT:
22525           ExpectingFlags = true;
22526           break;
22527         case ISD::CopyToReg:
22528         case ISD::SIGN_EXTEND:
22529         case ISD::ZERO_EXTEND:
22530         case ISD::ANY_EXTEND:
22531           break;
22532         }
22533
22534       if (!ExpectingFlags) {
22535         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22536         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22537
22538         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22539           X86::CondCode tmp = cc0;
22540           cc0 = cc1;
22541           cc1 = tmp;
22542         }
22543
22544         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22545             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22546           // FIXME: need symbolic constants for these magic numbers.
22547           // See X86ATTInstPrinter.cpp:printSSECC().
22548           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22549           if (Subtarget->hasAVX512()) {
22550             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22551                                          CMP01,
22552                                          DAG.getConstant(x86cc, DL, MVT::i8));
22553             if (N->getValueType(0) != MVT::i1)
22554               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22555                                  FSetCC);
22556             return FSetCC;
22557           }
22558           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22559                                               CMP00.getValueType(), CMP00, CMP01,
22560                                               DAG.getConstant(x86cc, DL,
22561                                                               MVT::i8));
22562
22563           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22564           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22565
22566           if (is64BitFP && !Subtarget->is64Bit()) {
22567             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22568             // 64-bit integer, since that's not a legal type. Since
22569             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22570             // bits, but can do this little dance to extract the lowest 32 bits
22571             // and work with those going forward.
22572             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22573                                            OnesOrZeroesF);
22574             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22575                                            Vector64);
22576             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22577                                         Vector32, DAG.getIntPtrConstant(0, DL));
22578             IntVT = MVT::i32;
22579           }
22580
22581           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22582                                               OnesOrZeroesF);
22583           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22584                                       DAG.getConstant(1, DL, IntVT));
22585           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22586                                               ANDed);
22587           return OneBitOfTruth;
22588         }
22589       }
22590     }
22591   }
22592   return SDValue();
22593 }
22594
22595 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22596 /// so it can be folded inside ANDNP.
22597 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22598   EVT VT = N->getValueType(0);
22599
22600   // Match direct AllOnes for 128 and 256-bit vectors
22601   if (ISD::isBuildVectorAllOnes(N))
22602     return true;
22603
22604   // Look through a bit convert.
22605   if (N->getOpcode() == ISD::BITCAST)
22606     N = N->getOperand(0).getNode();
22607
22608   // Sometimes the operand may come from a insert_subvector building a 256-bit
22609   // allones vector
22610   if (VT.is256BitVector() &&
22611       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22612     SDValue V1 = N->getOperand(0);
22613     SDValue V2 = N->getOperand(1);
22614
22615     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22616         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22617         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22618         ISD::isBuildVectorAllOnes(V2.getNode()))
22619       return true;
22620   }
22621
22622   return false;
22623 }
22624
22625 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22626 // register. In most cases we actually compare or select YMM-sized registers
22627 // and mixing the two types creates horrible code. This method optimizes
22628 // some of the transition sequences.
22629 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22630                                  TargetLowering::DAGCombinerInfo &DCI,
22631                                  const X86Subtarget *Subtarget) {
22632   EVT VT = N->getValueType(0);
22633   if (!VT.is256BitVector())
22634     return SDValue();
22635
22636   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22637           N->getOpcode() == ISD::ZERO_EXTEND ||
22638           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22639
22640   SDValue Narrow = N->getOperand(0);
22641   EVT NarrowVT = Narrow->getValueType(0);
22642   if (!NarrowVT.is128BitVector())
22643     return SDValue();
22644
22645   if (Narrow->getOpcode() != ISD::XOR &&
22646       Narrow->getOpcode() != ISD::AND &&
22647       Narrow->getOpcode() != ISD::OR)
22648     return SDValue();
22649
22650   SDValue N0  = Narrow->getOperand(0);
22651   SDValue N1  = Narrow->getOperand(1);
22652   SDLoc DL(Narrow);
22653
22654   // The Left side has to be a trunc.
22655   if (N0.getOpcode() != ISD::TRUNCATE)
22656     return SDValue();
22657
22658   // The type of the truncated inputs.
22659   EVT WideVT = N0->getOperand(0)->getValueType(0);
22660   if (WideVT != VT)
22661     return SDValue();
22662
22663   // The right side has to be a 'trunc' or a constant vector.
22664   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22665   ConstantSDNode *RHSConstSplat = nullptr;
22666   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22667     RHSConstSplat = RHSBV->getConstantSplatNode();
22668   if (!RHSTrunc && !RHSConstSplat)
22669     return SDValue();
22670
22671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22672
22673   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22674     return SDValue();
22675
22676   // Set N0 and N1 to hold the inputs to the new wide operation.
22677   N0 = N0->getOperand(0);
22678   if (RHSConstSplat) {
22679     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22680                      SDValue(RHSConstSplat, 0));
22681     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22682     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22683   } else if (RHSTrunc) {
22684     N1 = N1->getOperand(0);
22685   }
22686
22687   // Generate the wide operation.
22688   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22689   unsigned Opcode = N->getOpcode();
22690   switch (Opcode) {
22691   case ISD::ANY_EXTEND:
22692     return Op;
22693   case ISD::ZERO_EXTEND: {
22694     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22695     APInt Mask = APInt::getAllOnesValue(InBits);
22696     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22697     return DAG.getNode(ISD::AND, DL, VT,
22698                        Op, DAG.getConstant(Mask, DL, VT));
22699   }
22700   case ISD::SIGN_EXTEND:
22701     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22702                        Op, DAG.getValueType(NarrowVT));
22703   default:
22704     llvm_unreachable("Unexpected opcode");
22705   }
22706 }
22707
22708 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22709                                  TargetLowering::DAGCombinerInfo &DCI,
22710                                  const X86Subtarget *Subtarget) {
22711   SDValue N0 = N->getOperand(0);
22712   SDValue N1 = N->getOperand(1);
22713   SDLoc DL(N);
22714
22715   // A vector zext_in_reg may be represented as a shuffle,
22716   // feeding into a bitcast (this represents anyext) feeding into
22717   // an and with a mask.
22718   // We'd like to try to combine that into a shuffle with zero
22719   // plus a bitcast, removing the and.
22720   if (N0.getOpcode() != ISD::BITCAST ||
22721       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22722     return SDValue();
22723
22724   // The other side of the AND should be a splat of 2^C, where C
22725   // is the number of bits in the source type.
22726   if (N1.getOpcode() == ISD::BITCAST)
22727     N1 = N1.getOperand(0);
22728   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22729     return SDValue();
22730   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22731
22732   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22733   EVT SrcType = Shuffle->getValueType(0);
22734
22735   // We expect a single-source shuffle
22736   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22737     return SDValue();
22738
22739   unsigned SrcSize = SrcType.getScalarSizeInBits();
22740
22741   APInt SplatValue, SplatUndef;
22742   unsigned SplatBitSize;
22743   bool HasAnyUndefs;
22744   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22745                                 SplatBitSize, HasAnyUndefs))
22746     return SDValue();
22747
22748   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22749   // Make sure the splat matches the mask we expect
22750   if (SplatBitSize > ResSize ||
22751       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22752     return SDValue();
22753
22754   // Make sure the input and output size make sense
22755   if (SrcSize >= ResSize || ResSize % SrcSize)
22756     return SDValue();
22757
22758   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22759   // The number of u's between each two values depends on the ratio between
22760   // the source and dest type.
22761   unsigned ZextRatio = ResSize / SrcSize;
22762   bool IsZext = true;
22763   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22764     if (i % ZextRatio) {
22765       if (Shuffle->getMaskElt(i) > 0) {
22766         // Expected undef
22767         IsZext = false;
22768         break;
22769       }
22770     } else {
22771       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22772         // Expected element number
22773         IsZext = false;
22774         break;
22775       }
22776     }
22777   }
22778
22779   if (!IsZext)
22780     return SDValue();
22781
22782   // Ok, perform the transformation - replace the shuffle with
22783   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22784   // (instead of undef) where the k elements come from the zero vector.
22785   SmallVector<int, 8> Mask;
22786   unsigned NumElems = SrcType.getVectorNumElements();
22787   for (unsigned i = 0; i < NumElems; ++i)
22788     if (i % ZextRatio)
22789       Mask.push_back(NumElems);
22790     else
22791       Mask.push_back(i / ZextRatio);
22792
22793   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22794     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22795   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22796 }
22797
22798 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22799                                  TargetLowering::DAGCombinerInfo &DCI,
22800                                  const X86Subtarget *Subtarget) {
22801   if (DCI.isBeforeLegalizeOps())
22802     return SDValue();
22803
22804   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22805     return Zext;
22806
22807   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22808     return R;
22809
22810   EVT VT = N->getValueType(0);
22811   SDValue N0 = N->getOperand(0);
22812   SDValue N1 = N->getOperand(1);
22813   SDLoc DL(N);
22814
22815   // Create BEXTR instructions
22816   // BEXTR is ((X >> imm) & (2**size-1))
22817   if (VT == MVT::i32 || VT == MVT::i64) {
22818     // Check for BEXTR.
22819     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22820         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22821       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22822       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22823       if (MaskNode && ShiftNode) {
22824         uint64_t Mask = MaskNode->getZExtValue();
22825         uint64_t Shift = ShiftNode->getZExtValue();
22826         if (isMask_64(Mask)) {
22827           uint64_t MaskSize = countPopulation(Mask);
22828           if (Shift + MaskSize <= VT.getSizeInBits())
22829             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22830                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22831                                                VT));
22832         }
22833       }
22834     } // BEXTR
22835
22836     return SDValue();
22837   }
22838
22839   // Want to form ANDNP nodes:
22840   // 1) In the hopes of then easily combining them with OR and AND nodes
22841   //    to form PBLEND/PSIGN.
22842   // 2) To match ANDN packed intrinsics
22843   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22844     return SDValue();
22845
22846   // Check LHS for vnot
22847   if (N0.getOpcode() == ISD::XOR &&
22848       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22849       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22850     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22851
22852   // Check RHS for vnot
22853   if (N1.getOpcode() == ISD::XOR &&
22854       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22855       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22856     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22857
22858   return SDValue();
22859 }
22860
22861 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22862                                 TargetLowering::DAGCombinerInfo &DCI,
22863                                 const X86Subtarget *Subtarget) {
22864   if (DCI.isBeforeLegalizeOps())
22865     return SDValue();
22866
22867   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22868   if (R.getNode())
22869     return R;
22870
22871   SDValue N0 = N->getOperand(0);
22872   SDValue N1 = N->getOperand(1);
22873   EVT VT = N->getValueType(0);
22874
22875   // look for psign/blend
22876   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22877     if (!Subtarget->hasSSSE3() ||
22878         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22879       return SDValue();
22880
22881     // Canonicalize pandn to RHS
22882     if (N0.getOpcode() == X86ISD::ANDNP)
22883       std::swap(N0, N1);
22884     // or (and (m, y), (pandn m, x))
22885     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22886       SDValue Mask = N1.getOperand(0);
22887       SDValue X    = N1.getOperand(1);
22888       SDValue Y;
22889       if (N0.getOperand(0) == Mask)
22890         Y = N0.getOperand(1);
22891       if (N0.getOperand(1) == Mask)
22892         Y = N0.getOperand(0);
22893
22894       // Check to see if the mask appeared in both the AND and ANDNP and
22895       if (!Y.getNode())
22896         return SDValue();
22897
22898       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22899       // Look through mask bitcast.
22900       if (Mask.getOpcode() == ISD::BITCAST)
22901         Mask = Mask.getOperand(0);
22902       if (X.getOpcode() == ISD::BITCAST)
22903         X = X.getOperand(0);
22904       if (Y.getOpcode() == ISD::BITCAST)
22905         Y = Y.getOperand(0);
22906
22907       EVT MaskVT = Mask.getValueType();
22908
22909       // Validate that the Mask operand is a vector sra node.
22910       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22911       // there is no psrai.b
22912       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22913       unsigned SraAmt = ~0;
22914       if (Mask.getOpcode() == ISD::SRA) {
22915         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22916           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22917             SraAmt = AmtConst->getZExtValue();
22918       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22919         SDValue SraC = Mask.getOperand(1);
22920         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22921       }
22922       if ((SraAmt + 1) != EltBits)
22923         return SDValue();
22924
22925       SDLoc DL(N);
22926
22927       // Now we know we at least have a plendvb with the mask val.  See if
22928       // we can form a psignb/w/d.
22929       // psign = x.type == y.type == mask.type && y = sub(0, x);
22930       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22931           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22932           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22933         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22934                "Unsupported VT for PSIGN");
22935         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22936         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22937       }
22938       // PBLENDVB only available on SSE 4.1
22939       if (!Subtarget->hasSSE41())
22940         return SDValue();
22941
22942       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22943
22944       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22945       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22946       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22947       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22948       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22949     }
22950   }
22951
22952   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22953     return SDValue();
22954
22955   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22956   MachineFunction &MF = DAG.getMachineFunction();
22957   bool OptForSize =
22958       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22959
22960   // SHLD/SHRD instructions have lower register pressure, but on some
22961   // platforms they have higher latency than the equivalent
22962   // series of shifts/or that would otherwise be generated.
22963   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22964   // have higher latencies and we are not optimizing for size.
22965   if (!OptForSize && Subtarget->isSHLDSlow())
22966     return SDValue();
22967
22968   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22969     std::swap(N0, N1);
22970   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22971     return SDValue();
22972   if (!N0.hasOneUse() || !N1.hasOneUse())
22973     return SDValue();
22974
22975   SDValue ShAmt0 = N0.getOperand(1);
22976   if (ShAmt0.getValueType() != MVT::i8)
22977     return SDValue();
22978   SDValue ShAmt1 = N1.getOperand(1);
22979   if (ShAmt1.getValueType() != MVT::i8)
22980     return SDValue();
22981   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22982     ShAmt0 = ShAmt0.getOperand(0);
22983   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22984     ShAmt1 = ShAmt1.getOperand(0);
22985
22986   SDLoc DL(N);
22987   unsigned Opc = X86ISD::SHLD;
22988   SDValue Op0 = N0.getOperand(0);
22989   SDValue Op1 = N1.getOperand(0);
22990   if (ShAmt0.getOpcode() == ISD::SUB) {
22991     Opc = X86ISD::SHRD;
22992     std::swap(Op0, Op1);
22993     std::swap(ShAmt0, ShAmt1);
22994   }
22995
22996   unsigned Bits = VT.getSizeInBits();
22997   if (ShAmt1.getOpcode() == ISD::SUB) {
22998     SDValue Sum = ShAmt1.getOperand(0);
22999     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23000       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23001       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23002         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23003       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23004         return DAG.getNode(Opc, DL, VT,
23005                            Op0, Op1,
23006                            DAG.getNode(ISD::TRUNCATE, DL,
23007                                        MVT::i8, ShAmt0));
23008     }
23009   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23010     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23011     if (ShAmt0C &&
23012         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23013       return DAG.getNode(Opc, DL, VT,
23014                          N0.getOperand(0), N1.getOperand(0),
23015                          DAG.getNode(ISD::TRUNCATE, DL,
23016                                        MVT::i8, ShAmt0));
23017   }
23018
23019   return SDValue();
23020 }
23021
23022 // Generate NEG and CMOV for integer abs.
23023 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23024   EVT VT = N->getValueType(0);
23025
23026   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23027   // 8-bit integer abs to NEG and CMOV.
23028   if (VT.isInteger() && VT.getSizeInBits() == 8)
23029     return SDValue();
23030
23031   SDValue N0 = N->getOperand(0);
23032   SDValue N1 = N->getOperand(1);
23033   SDLoc DL(N);
23034
23035   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23036   // and change it to SUB and CMOV.
23037   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23038       N0.getOpcode() == ISD::ADD &&
23039       N0.getOperand(1) == N1 &&
23040       N1.getOpcode() == ISD::SRA &&
23041       N1.getOperand(0) == N0.getOperand(0))
23042     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23043       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23044         // Generate SUB & CMOV.
23045         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23046                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23047
23048         SDValue Ops[] = { N0.getOperand(0), Neg,
23049                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23050                           SDValue(Neg.getNode(), 1) };
23051         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23052       }
23053   return SDValue();
23054 }
23055
23056 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23057 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23058                                  TargetLowering::DAGCombinerInfo &DCI,
23059                                  const X86Subtarget *Subtarget) {
23060   if (DCI.isBeforeLegalizeOps())
23061     return SDValue();
23062
23063   if (Subtarget->hasCMov()) {
23064     SDValue RV = performIntegerAbsCombine(N, DAG);
23065     if (RV.getNode())
23066       return RV;
23067   }
23068
23069   return SDValue();
23070 }
23071
23072 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23073 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23074                                   TargetLowering::DAGCombinerInfo &DCI,
23075                                   const X86Subtarget *Subtarget) {
23076   LoadSDNode *Ld = cast<LoadSDNode>(N);
23077   EVT RegVT = Ld->getValueType(0);
23078   EVT MemVT = Ld->getMemoryVT();
23079   SDLoc dl(Ld);
23080   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23081
23082   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23083   // into two 16-byte operations.
23084   ISD::LoadExtType Ext = Ld->getExtensionType();
23085   unsigned Alignment = Ld->getAlignment();
23086   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23087   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23088       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23089     unsigned NumElems = RegVT.getVectorNumElements();
23090     if (NumElems < 2)
23091       return SDValue();
23092
23093     SDValue Ptr = Ld->getBasePtr();
23094     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23095
23096     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23097                                   NumElems/2);
23098     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23099                                 Ld->getPointerInfo(), Ld->isVolatile(),
23100                                 Ld->isNonTemporal(), Ld->isInvariant(),
23101                                 Alignment);
23102     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23103     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23104                                 Ld->getPointerInfo(), Ld->isVolatile(),
23105                                 Ld->isNonTemporal(), Ld->isInvariant(),
23106                                 std::min(16U, Alignment));
23107     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23108                              Load1.getValue(1),
23109                              Load2.getValue(1));
23110
23111     SDValue NewVec = DAG.getUNDEF(RegVT);
23112     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23113     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23114     return DCI.CombineTo(N, NewVec, TF, true);
23115   }
23116
23117   return SDValue();
23118 }
23119
23120 /// PerformMLOADCombine - Resolve extending loads
23121 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23122                                    TargetLowering::DAGCombinerInfo &DCI,
23123                                    const X86Subtarget *Subtarget) {
23124   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23125   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23126     return SDValue();
23127
23128   EVT VT = Mld->getValueType(0);
23129   unsigned NumElems = VT.getVectorNumElements();
23130   EVT LdVT = Mld->getMemoryVT();
23131   SDLoc dl(Mld);
23132
23133   assert(LdVT != VT && "Cannot extend to the same type");
23134   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23135   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23136   // From, To sizes and ElemCount must be pow of two
23137   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23138     "Unexpected size for extending masked load");
23139
23140   unsigned SizeRatio  = ToSz / FromSz;
23141   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23142
23143   // Create a type on which we perform the shuffle
23144   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23145           LdVT.getScalarType(), NumElems*SizeRatio);
23146   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23147
23148   // Convert Src0 value
23149   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
23150   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23151     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23152     for (unsigned i = 0; i != NumElems; ++i)
23153       ShuffleVec[i] = i * SizeRatio;
23154
23155     // Can't shuffle using an illegal type.
23156     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23157             && "WideVecVT should be legal");
23158     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23159                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23160   }
23161   // Prepare the new mask
23162   SDValue NewMask;
23163   SDValue Mask = Mld->getMask();
23164   if (Mask.getValueType() == VT) {
23165     // Mask and original value have the same type
23166     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23167     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23168     for (unsigned i = 0; i != NumElems; ++i)
23169       ShuffleVec[i] = i * SizeRatio;
23170     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23171       ShuffleVec[i] = NumElems*SizeRatio;
23172     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23173                                    DAG.getConstant(0, dl, WideVecVT),
23174                                    &ShuffleVec[0]);
23175   }
23176   else {
23177     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23178     unsigned WidenNumElts = NumElems*SizeRatio;
23179     unsigned MaskNumElts = VT.getVectorNumElements();
23180     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23181                                      WidenNumElts);
23182
23183     unsigned NumConcat = WidenNumElts / MaskNumElts;
23184     SmallVector<SDValue, 16> Ops(NumConcat);
23185     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23186     Ops[0] = Mask;
23187     for (unsigned i = 1; i != NumConcat; ++i)
23188       Ops[i] = ZeroVal;
23189
23190     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23191   }
23192
23193   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23194                                      Mld->getBasePtr(), NewMask, WideSrc0,
23195                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23196                                      ISD::NON_EXTLOAD);
23197   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23198   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23199
23200 }
23201 /// PerformMSTORECombine - Resolve truncating stores
23202 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23203                                     const X86Subtarget *Subtarget) {
23204   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23205   if (!Mst->isTruncatingStore())
23206     return SDValue();
23207
23208   EVT VT = Mst->getValue().getValueType();
23209   unsigned NumElems = VT.getVectorNumElements();
23210   EVT StVT = Mst->getMemoryVT();
23211   SDLoc dl(Mst);
23212
23213   assert(StVT != VT && "Cannot truncate to the same type");
23214   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23215   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23216
23217   // From, To sizes and ElemCount must be pow of two
23218   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23219     "Unexpected size for truncating masked store");
23220   // We are going to use the original vector elt for storing.
23221   // Accumulated smaller vector elements must be a multiple of the store size.
23222   assert (((NumElems * FromSz) % ToSz) == 0 &&
23223           "Unexpected ratio for truncating masked store");
23224
23225   unsigned SizeRatio  = FromSz / ToSz;
23226   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23227
23228   // Create a type on which we perform the shuffle
23229   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23230           StVT.getScalarType(), NumElems*SizeRatio);
23231
23232   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23233
23234   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23235   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23236   for (unsigned i = 0; i != NumElems; ++i)
23237     ShuffleVec[i] = i * SizeRatio;
23238
23239   // Can't shuffle using an illegal type.
23240   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23241           && "WideVecVT should be legal");
23242
23243   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23244                                         DAG.getUNDEF(WideVecVT),
23245                                         &ShuffleVec[0]);
23246
23247   SDValue NewMask;
23248   SDValue Mask = Mst->getMask();
23249   if (Mask.getValueType() == VT) {
23250     // Mask and original value have the same type
23251     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23252     for (unsigned i = 0; i != NumElems; ++i)
23253       ShuffleVec[i] = i * SizeRatio;
23254     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23255       ShuffleVec[i] = NumElems*SizeRatio;
23256     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23257                                    DAG.getConstant(0, dl, WideVecVT),
23258                                    &ShuffleVec[0]);
23259   }
23260   else {
23261     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23262     unsigned WidenNumElts = NumElems*SizeRatio;
23263     unsigned MaskNumElts = VT.getVectorNumElements();
23264     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23265                                      WidenNumElts);
23266
23267     unsigned NumConcat = WidenNumElts / MaskNumElts;
23268     SmallVector<SDValue, 16> Ops(NumConcat);
23269     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23270     Ops[0] = Mask;
23271     for (unsigned i = 1; i != NumConcat; ++i)
23272       Ops[i] = ZeroVal;
23273
23274     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23275   }
23276
23277   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23278                             NewMask, StVT, Mst->getMemOperand(), false);
23279 }
23280 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23281 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23282                                    const X86Subtarget *Subtarget) {
23283   StoreSDNode *St = cast<StoreSDNode>(N);
23284   EVT VT = St->getValue().getValueType();
23285   EVT StVT = St->getMemoryVT();
23286   SDLoc dl(St);
23287   SDValue StoredVal = St->getOperand(1);
23288   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23289
23290   // If we are saving a concatenation of two XMM registers and 32-byte stores
23291   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23292   unsigned Alignment = St->getAlignment();
23293   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23294   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23295       StVT == VT && !IsAligned) {
23296     unsigned NumElems = VT.getVectorNumElements();
23297     if (NumElems < 2)
23298       return SDValue();
23299
23300     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23301     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23302
23303     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23304     SDValue Ptr0 = St->getBasePtr();
23305     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23306
23307     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23308                                 St->getPointerInfo(), St->isVolatile(),
23309                                 St->isNonTemporal(), Alignment);
23310     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23311                                 St->getPointerInfo(), St->isVolatile(),
23312                                 St->isNonTemporal(),
23313                                 std::min(16U, Alignment));
23314     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23315   }
23316
23317   // Optimize trunc store (of multiple scalars) to shuffle and store.
23318   // First, pack all of the elements in one place. Next, store to memory
23319   // in fewer chunks.
23320   if (St->isTruncatingStore() && VT.isVector()) {
23321     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23322     unsigned NumElems = VT.getVectorNumElements();
23323     assert(StVT != VT && "Cannot truncate to the same type");
23324     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23325     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23326
23327     // From, To sizes and ElemCount must be pow of two
23328     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23329     // We are going to use the original vector elt for storing.
23330     // Accumulated smaller vector elements must be a multiple of the store size.
23331     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23332
23333     unsigned SizeRatio  = FromSz / ToSz;
23334
23335     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23336
23337     // Create a type on which we perform the shuffle
23338     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23339             StVT.getScalarType(), NumElems*SizeRatio);
23340
23341     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23342
23343     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23344     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23345     for (unsigned i = 0; i != NumElems; ++i)
23346       ShuffleVec[i] = i * SizeRatio;
23347
23348     // Can't shuffle using an illegal type.
23349     if (!TLI.isTypeLegal(WideVecVT))
23350       return SDValue();
23351
23352     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23353                                          DAG.getUNDEF(WideVecVT),
23354                                          &ShuffleVec[0]);
23355     // At this point all of the data is stored at the bottom of the
23356     // register. We now need to save it to mem.
23357
23358     // Find the largest store unit
23359     MVT StoreType = MVT::i8;
23360     for (MVT Tp : MVT::integer_valuetypes()) {
23361       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23362         StoreType = Tp;
23363     }
23364
23365     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23366     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23367         (64 <= NumElems * ToSz))
23368       StoreType = MVT::f64;
23369
23370     // Bitcast the original vector into a vector of store-size units
23371     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23372             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23373     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23374     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23375     SmallVector<SDValue, 8> Chains;
23376     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23377                                         TLI.getPointerTy());
23378     SDValue Ptr = St->getBasePtr();
23379
23380     // Perform one or more big stores into memory.
23381     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23382       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23383                                    StoreType, ShuffWide,
23384                                    DAG.getIntPtrConstant(i, dl));
23385       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23386                                 St->getPointerInfo(), St->isVolatile(),
23387                                 St->isNonTemporal(), St->getAlignment());
23388       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23389       Chains.push_back(Ch);
23390     }
23391
23392     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23393   }
23394
23395   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23396   // the FP state in cases where an emms may be missing.
23397   // A preferable solution to the general problem is to figure out the right
23398   // places to insert EMMS.  This qualifies as a quick hack.
23399
23400   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23401   if (VT.getSizeInBits() != 64)
23402     return SDValue();
23403
23404   const Function *F = DAG.getMachineFunction().getFunction();
23405   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23406   bool F64IsLegal =
23407       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23408   if ((VT.isVector() ||
23409        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23410       isa<LoadSDNode>(St->getValue()) &&
23411       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23412       St->getChain().hasOneUse() && !St->isVolatile()) {
23413     SDNode* LdVal = St->getValue().getNode();
23414     LoadSDNode *Ld = nullptr;
23415     int TokenFactorIndex = -1;
23416     SmallVector<SDValue, 8> Ops;
23417     SDNode* ChainVal = St->getChain().getNode();
23418     // Must be a store of a load.  We currently handle two cases:  the load
23419     // is a direct child, and it's under an intervening TokenFactor.  It is
23420     // possible to dig deeper under nested TokenFactors.
23421     if (ChainVal == LdVal)
23422       Ld = cast<LoadSDNode>(St->getChain());
23423     else if (St->getValue().hasOneUse() &&
23424              ChainVal->getOpcode() == ISD::TokenFactor) {
23425       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23426         if (ChainVal->getOperand(i).getNode() == LdVal) {
23427           TokenFactorIndex = i;
23428           Ld = cast<LoadSDNode>(St->getValue());
23429         } else
23430           Ops.push_back(ChainVal->getOperand(i));
23431       }
23432     }
23433
23434     if (!Ld || !ISD::isNormalLoad(Ld))
23435       return SDValue();
23436
23437     // If this is not the MMX case, i.e. we are just turning i64 load/store
23438     // into f64 load/store, avoid the transformation if there are multiple
23439     // uses of the loaded value.
23440     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23441       return SDValue();
23442
23443     SDLoc LdDL(Ld);
23444     SDLoc StDL(N);
23445     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23446     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23447     // pair instead.
23448     if (Subtarget->is64Bit() || F64IsLegal) {
23449       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23450       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23451                                   Ld->getPointerInfo(), Ld->isVolatile(),
23452                                   Ld->isNonTemporal(), Ld->isInvariant(),
23453                                   Ld->getAlignment());
23454       SDValue NewChain = NewLd.getValue(1);
23455       if (TokenFactorIndex != -1) {
23456         Ops.push_back(NewChain);
23457         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23458       }
23459       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23460                           St->getPointerInfo(),
23461                           St->isVolatile(), St->isNonTemporal(),
23462                           St->getAlignment());
23463     }
23464
23465     // Otherwise, lower to two pairs of 32-bit loads / stores.
23466     SDValue LoAddr = Ld->getBasePtr();
23467     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23468                                  DAG.getConstant(4, LdDL, MVT::i32));
23469
23470     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23471                                Ld->getPointerInfo(),
23472                                Ld->isVolatile(), Ld->isNonTemporal(),
23473                                Ld->isInvariant(), Ld->getAlignment());
23474     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23475                                Ld->getPointerInfo().getWithOffset(4),
23476                                Ld->isVolatile(), Ld->isNonTemporal(),
23477                                Ld->isInvariant(),
23478                                MinAlign(Ld->getAlignment(), 4));
23479
23480     SDValue NewChain = LoLd.getValue(1);
23481     if (TokenFactorIndex != -1) {
23482       Ops.push_back(LoLd);
23483       Ops.push_back(HiLd);
23484       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23485     }
23486
23487     LoAddr = St->getBasePtr();
23488     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23489                          DAG.getConstant(4, StDL, MVT::i32));
23490
23491     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23492                                 St->getPointerInfo(),
23493                                 St->isVolatile(), St->isNonTemporal(),
23494                                 St->getAlignment());
23495     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23496                                 St->getPointerInfo().getWithOffset(4),
23497                                 St->isVolatile(),
23498                                 St->isNonTemporal(),
23499                                 MinAlign(St->getAlignment(), 4));
23500     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23501   }
23502
23503   // This is similar to the above case, but here we handle a scalar 64-bit
23504   // integer store that is extracted from a vector on a 32-bit target.
23505   // If we have SSE2, then we can treat it like a floating-point double
23506   // to get past legalization. The execution dependencies fixup pass will
23507   // choose the optimal machine instruction for the store if this really is
23508   // an integer or v2f32 rather than an f64.
23509   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23510       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23511     SDValue OldExtract = St->getOperand(1);
23512     SDValue ExtOp0 = OldExtract.getOperand(0);
23513     unsigned VecSize = ExtOp0.getValueSizeInBits();
23514     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23515     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23516     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23517                                      BitCast, OldExtract.getOperand(1));
23518     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23519                         St->getPointerInfo(), St->isVolatile(),
23520                         St->isNonTemporal(), St->getAlignment());
23521   }
23522
23523   return SDValue();
23524 }
23525
23526 /// Return 'true' if this vector operation is "horizontal"
23527 /// and return the operands for the horizontal operation in LHS and RHS.  A
23528 /// horizontal operation performs the binary operation on successive elements
23529 /// of its first operand, then on successive elements of its second operand,
23530 /// returning the resulting values in a vector.  For example, if
23531 ///   A = < float a0, float a1, float a2, float a3 >
23532 /// and
23533 ///   B = < float b0, float b1, float b2, float b3 >
23534 /// then the result of doing a horizontal operation on A and B is
23535 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23536 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23537 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23538 /// set to A, RHS to B, and the routine returns 'true'.
23539 /// Note that the binary operation should have the property that if one of the
23540 /// operands is UNDEF then the result is UNDEF.
23541 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23542   // Look for the following pattern: if
23543   //   A = < float a0, float a1, float a2, float a3 >
23544   //   B = < float b0, float b1, float b2, float b3 >
23545   // and
23546   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23547   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23548   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23549   // which is A horizontal-op B.
23550
23551   // At least one of the operands should be a vector shuffle.
23552   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23553       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23554     return false;
23555
23556   MVT VT = LHS.getSimpleValueType();
23557
23558   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23559          "Unsupported vector type for horizontal add/sub");
23560
23561   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23562   // operate independently on 128-bit lanes.
23563   unsigned NumElts = VT.getVectorNumElements();
23564   unsigned NumLanes = VT.getSizeInBits()/128;
23565   unsigned NumLaneElts = NumElts / NumLanes;
23566   assert((NumLaneElts % 2 == 0) &&
23567          "Vector type should have an even number of elements in each lane");
23568   unsigned HalfLaneElts = NumLaneElts/2;
23569
23570   // View LHS in the form
23571   //   LHS = VECTOR_SHUFFLE A, B, LMask
23572   // If LHS is not a shuffle then pretend it is the shuffle
23573   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23574   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23575   // type VT.
23576   SDValue A, B;
23577   SmallVector<int, 16> LMask(NumElts);
23578   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23579     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23580       A = LHS.getOperand(0);
23581     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23582       B = LHS.getOperand(1);
23583     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23584     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23585   } else {
23586     if (LHS.getOpcode() != ISD::UNDEF)
23587       A = LHS;
23588     for (unsigned i = 0; i != NumElts; ++i)
23589       LMask[i] = i;
23590   }
23591
23592   // Likewise, view RHS in the form
23593   //   RHS = VECTOR_SHUFFLE C, D, RMask
23594   SDValue C, D;
23595   SmallVector<int, 16> RMask(NumElts);
23596   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23597     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23598       C = RHS.getOperand(0);
23599     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23600       D = RHS.getOperand(1);
23601     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23602     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23603   } else {
23604     if (RHS.getOpcode() != ISD::UNDEF)
23605       C = RHS;
23606     for (unsigned i = 0; i != NumElts; ++i)
23607       RMask[i] = i;
23608   }
23609
23610   // Check that the shuffles are both shuffling the same vectors.
23611   if (!(A == C && B == D) && !(A == D && B == C))
23612     return false;
23613
23614   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23615   if (!A.getNode() && !B.getNode())
23616     return false;
23617
23618   // If A and B occur in reverse order in RHS, then "swap" them (which means
23619   // rewriting the mask).
23620   if (A != C)
23621     ShuffleVectorSDNode::commuteMask(RMask);
23622
23623   // At this point LHS and RHS are equivalent to
23624   //   LHS = VECTOR_SHUFFLE A, B, LMask
23625   //   RHS = VECTOR_SHUFFLE A, B, RMask
23626   // Check that the masks correspond to performing a horizontal operation.
23627   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23628     for (unsigned i = 0; i != NumLaneElts; ++i) {
23629       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23630
23631       // Ignore any UNDEF components.
23632       if (LIdx < 0 || RIdx < 0 ||
23633           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23634           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23635         continue;
23636
23637       // Check that successive elements are being operated on.  If not, this is
23638       // not a horizontal operation.
23639       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23640       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23641       if (!(LIdx == Index && RIdx == Index + 1) &&
23642           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23643         return false;
23644     }
23645   }
23646
23647   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23648   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23649   return true;
23650 }
23651
23652 /// Do target-specific dag combines on floating point adds.
23653 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23654                                   const X86Subtarget *Subtarget) {
23655   EVT VT = N->getValueType(0);
23656   SDValue LHS = N->getOperand(0);
23657   SDValue RHS = N->getOperand(1);
23658
23659   // Try to synthesize horizontal adds from adds of shuffles.
23660   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23661        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23662       isHorizontalBinOp(LHS, RHS, true))
23663     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23664   return SDValue();
23665 }
23666
23667 /// Do target-specific dag combines on floating point subs.
23668 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23669                                   const X86Subtarget *Subtarget) {
23670   EVT VT = N->getValueType(0);
23671   SDValue LHS = N->getOperand(0);
23672   SDValue RHS = N->getOperand(1);
23673
23674   // Try to synthesize horizontal subs from subs of shuffles.
23675   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23676        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23677       isHorizontalBinOp(LHS, RHS, false))
23678     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23679   return SDValue();
23680 }
23681
23682 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23683 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23684   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23685
23686   // F[X]OR(0.0, x) -> x
23687   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23688     if (C->getValueAPF().isPosZero())
23689       return N->getOperand(1);
23690
23691   // F[X]OR(x, 0.0) -> x
23692   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23693     if (C->getValueAPF().isPosZero())
23694       return N->getOperand(0);
23695   return SDValue();
23696 }
23697
23698 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23699 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23700   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23701
23702   // Only perform optimizations if UnsafeMath is used.
23703   if (!DAG.getTarget().Options.UnsafeFPMath)
23704     return SDValue();
23705
23706   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23707   // into FMINC and FMAXC, which are Commutative operations.
23708   unsigned NewOp = 0;
23709   switch (N->getOpcode()) {
23710     default: llvm_unreachable("unknown opcode");
23711     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23712     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23713   }
23714
23715   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23716                      N->getOperand(0), N->getOperand(1));
23717 }
23718
23719 /// Do target-specific dag combines on X86ISD::FAND nodes.
23720 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23721   // FAND(0.0, x) -> 0.0
23722   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23723     if (C->getValueAPF().isPosZero())
23724       return N->getOperand(0);
23725
23726   // FAND(x, 0.0) -> 0.0
23727   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23728     if (C->getValueAPF().isPosZero())
23729       return N->getOperand(1);
23730
23731   return SDValue();
23732 }
23733
23734 /// Do target-specific dag combines on X86ISD::FANDN nodes
23735 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23736   // FANDN(0.0, x) -> x
23737   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23738     if (C->getValueAPF().isPosZero())
23739       return N->getOperand(1);
23740
23741   // FANDN(x, 0.0) -> 0.0
23742   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23743     if (C->getValueAPF().isPosZero())
23744       return N->getOperand(1);
23745
23746   return SDValue();
23747 }
23748
23749 static SDValue PerformBTCombine(SDNode *N,
23750                                 SelectionDAG &DAG,
23751                                 TargetLowering::DAGCombinerInfo &DCI) {
23752   // BT ignores high bits in the bit index operand.
23753   SDValue Op1 = N->getOperand(1);
23754   if (Op1.hasOneUse()) {
23755     unsigned BitWidth = Op1.getValueSizeInBits();
23756     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23757     APInt KnownZero, KnownOne;
23758     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23759                                           !DCI.isBeforeLegalizeOps());
23760     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23761     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23762         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23763       DCI.CommitTargetLoweringOpt(TLO);
23764   }
23765   return SDValue();
23766 }
23767
23768 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23769   SDValue Op = N->getOperand(0);
23770   if (Op.getOpcode() == ISD::BITCAST)
23771     Op = Op.getOperand(0);
23772   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23773   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23774       VT.getVectorElementType().getSizeInBits() ==
23775       OpVT.getVectorElementType().getSizeInBits()) {
23776     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23777   }
23778   return SDValue();
23779 }
23780
23781 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23782                                                const X86Subtarget *Subtarget) {
23783   EVT VT = N->getValueType(0);
23784   if (!VT.isVector())
23785     return SDValue();
23786
23787   SDValue N0 = N->getOperand(0);
23788   SDValue N1 = N->getOperand(1);
23789   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23790   SDLoc dl(N);
23791
23792   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23793   // both SSE and AVX2 since there is no sign-extended shift right
23794   // operation on a vector with 64-bit elements.
23795   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23796   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23797   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23798       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23799     SDValue N00 = N0.getOperand(0);
23800
23801     // EXTLOAD has a better solution on AVX2,
23802     // it may be replaced with X86ISD::VSEXT node.
23803     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23804       if (!ISD::isNormalLoad(N00.getNode()))
23805         return SDValue();
23806
23807     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23808         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23809                                   N00, N1);
23810       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23811     }
23812   }
23813   return SDValue();
23814 }
23815
23816 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23817                                   TargetLowering::DAGCombinerInfo &DCI,
23818                                   const X86Subtarget *Subtarget) {
23819   SDValue N0 = N->getOperand(0);
23820   EVT VT = N->getValueType(0);
23821   EVT SVT = VT.getScalarType();
23822   EVT InVT = N0->getValueType(0);
23823   EVT InSVT = InVT.getScalarType();
23824   SDLoc DL(N);
23825
23826   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23827   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23828   // This exposes the sext to the sdivrem lowering, so that it directly extends
23829   // from AH (which we otherwise need to do contortions to access).
23830   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23831       InVT == MVT::i8 && VT == MVT::i32) {
23832     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23833     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
23834                             N0.getOperand(0), N0.getOperand(1));
23835     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23836     return R.getValue(1);
23837   }
23838
23839   if (!DCI.isBeforeLegalizeOps()) {
23840     if (N0.getValueType() == MVT::i1) {
23841       SDValue Zero = DAG.getConstant(0, DL, VT);
23842       SDValue AllOnes =
23843         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
23844       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
23845     }
23846     return SDValue();
23847   }
23848
23849   if (VT.isVector()) {
23850     auto ExtendToVec128 = [&DAG](SDLoc DL, SDValue N) {
23851       EVT InVT = N->getValueType(0);
23852       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
23853                                    128 / InVT.getScalarSizeInBits());
23854       SmallVector<SDValue, 8> Opnds(128 / InVT.getSizeInBits(),
23855                                     DAG.getUNDEF(InVT));
23856       Opnds[0] = N;
23857       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
23858     };
23859
23860     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
23861     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
23862     if (VT.getSizeInBits() == 128 &&
23863         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23864         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23865       SDValue ExOp = ExtendToVec128(DL, N0);
23866       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
23867     }
23868
23869     // On pre-AVX2 targets, split into 128-bit nodes of
23870     // ISD::SIGN_EXTEND_VECTOR_INREG.
23871     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
23872         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23873         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23874       unsigned NumVecs = VT.getSizeInBits() / 128;
23875       unsigned NumSubElts = 128 / SVT.getSizeInBits();
23876       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
23877       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
23878
23879       SmallVector<SDValue, 8> Opnds;
23880       for (unsigned i = 0, Offset = 0; i != NumVecs;
23881            ++i, Offset += NumSubElts) {
23882         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
23883                                      DAG.getIntPtrConstant(Offset, DL));
23884         SrcVec = ExtendToVec128(DL, SrcVec);
23885         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
23886         Opnds.push_back(SrcVec);
23887       }
23888       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
23889     }
23890   }
23891
23892   if (!Subtarget->hasFp256())
23893     return SDValue();
23894
23895   if (VT.isVector() && VT.getSizeInBits() == 256) {
23896     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23897     if (R.getNode())
23898       return R;
23899   }
23900
23901   return SDValue();
23902 }
23903
23904 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23905                                  const X86Subtarget* Subtarget) {
23906   SDLoc dl(N);
23907   EVT VT = N->getValueType(0);
23908
23909   // Let legalize expand this if it isn't a legal type yet.
23910   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23911     return SDValue();
23912
23913   EVT ScalarVT = VT.getScalarType();
23914   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23915       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23916     return SDValue();
23917
23918   SDValue A = N->getOperand(0);
23919   SDValue B = N->getOperand(1);
23920   SDValue C = N->getOperand(2);
23921
23922   bool NegA = (A.getOpcode() == ISD::FNEG);
23923   bool NegB = (B.getOpcode() == ISD::FNEG);
23924   bool NegC = (C.getOpcode() == ISD::FNEG);
23925
23926   // Negative multiplication when NegA xor NegB
23927   bool NegMul = (NegA != NegB);
23928   if (NegA)
23929     A = A.getOperand(0);
23930   if (NegB)
23931     B = B.getOperand(0);
23932   if (NegC)
23933     C = C.getOperand(0);
23934
23935   unsigned Opcode;
23936   if (!NegMul)
23937     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23938   else
23939     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23940
23941   return DAG.getNode(Opcode, dl, VT, A, B, C);
23942 }
23943
23944 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23945                                   TargetLowering::DAGCombinerInfo &DCI,
23946                                   const X86Subtarget *Subtarget) {
23947   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23948   //           (and (i32 x86isd::setcc_carry), 1)
23949   // This eliminates the zext. This transformation is necessary because
23950   // ISD::SETCC is always legalized to i8.
23951   SDLoc dl(N);
23952   SDValue N0 = N->getOperand(0);
23953   EVT VT = N->getValueType(0);
23954
23955   if (N0.getOpcode() == ISD::AND &&
23956       N0.hasOneUse() &&
23957       N0.getOperand(0).hasOneUse()) {
23958     SDValue N00 = N0.getOperand(0);
23959     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23960       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23961       if (!C || C->getZExtValue() != 1)
23962         return SDValue();
23963       return DAG.getNode(ISD::AND, dl, VT,
23964                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23965                                      N00.getOperand(0), N00.getOperand(1)),
23966                          DAG.getConstant(1, dl, VT));
23967     }
23968   }
23969
23970   if (N0.getOpcode() == ISD::TRUNCATE &&
23971       N0.hasOneUse() &&
23972       N0.getOperand(0).hasOneUse()) {
23973     SDValue N00 = N0.getOperand(0);
23974     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23975       return DAG.getNode(ISD::AND, dl, VT,
23976                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23977                                      N00.getOperand(0), N00.getOperand(1)),
23978                          DAG.getConstant(1, dl, VT));
23979     }
23980   }
23981   if (VT.is256BitVector()) {
23982     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23983     if (R.getNode())
23984       return R;
23985   }
23986
23987   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23988   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23989   // This exposes the zext to the udivrem lowering, so that it directly extends
23990   // from AH (which we otherwise need to do contortions to access).
23991   if (N0.getOpcode() == ISD::UDIVREM &&
23992       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23993       (VT == MVT::i32 || VT == MVT::i64)) {
23994     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23995     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23996                             N0.getOperand(0), N0.getOperand(1));
23997     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23998     return R.getValue(1);
23999   }
24000
24001   return SDValue();
24002 }
24003
24004 // Optimize x == -y --> x+y == 0
24005 //          x != -y --> x+y != 0
24006 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24007                                       const X86Subtarget* Subtarget) {
24008   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24009   SDValue LHS = N->getOperand(0);
24010   SDValue RHS = N->getOperand(1);
24011   EVT VT = N->getValueType(0);
24012   SDLoc DL(N);
24013
24014   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24015     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24016       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24017         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24018                                    LHS.getOperand(1));
24019         return DAG.getSetCC(DL, N->getValueType(0), addV,
24020                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24021       }
24022   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24023     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24024       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24025         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24026                                    RHS.getOperand(1));
24027         return DAG.getSetCC(DL, N->getValueType(0), addV,
24028                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24029       }
24030
24031   if (VT.getScalarType() == MVT::i1 &&
24032       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24033     bool IsSEXT0 =
24034         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24035         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24036     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24037
24038     if (!IsSEXT0 || !IsVZero1) {
24039       // Swap the operands and update the condition code.
24040       std::swap(LHS, RHS);
24041       CC = ISD::getSetCCSwappedOperands(CC);
24042
24043       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24044                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24045       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24046     }
24047
24048     if (IsSEXT0 && IsVZero1) {
24049       assert(VT == LHS.getOperand(0).getValueType() &&
24050              "Uexpected operand type");
24051       if (CC == ISD::SETGT)
24052         return DAG.getConstant(0, DL, VT);
24053       if (CC == ISD::SETLE)
24054         return DAG.getConstant(1, DL, VT);
24055       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24056         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24057
24058       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24059              "Unexpected condition code!");
24060       return LHS.getOperand(0);
24061     }
24062   }
24063
24064   return SDValue();
24065 }
24066
24067 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24068                                          SelectionDAG &DAG) {
24069   SDLoc dl(Load);
24070   MVT VT = Load->getSimpleValueType(0);
24071   MVT EVT = VT.getVectorElementType();
24072   SDValue Addr = Load->getOperand(1);
24073   SDValue NewAddr = DAG.getNode(
24074       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24075       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24076                       Addr.getSimpleValueType()));
24077
24078   SDValue NewLoad =
24079       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24080                   DAG.getMachineFunction().getMachineMemOperand(
24081                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24082   return NewLoad;
24083 }
24084
24085 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24086                                       const X86Subtarget *Subtarget) {
24087   SDLoc dl(N);
24088   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24089   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24090          "X86insertps is only defined for v4x32");
24091
24092   SDValue Ld = N->getOperand(1);
24093   if (MayFoldLoad(Ld)) {
24094     // Extract the countS bits from the immediate so we can get the proper
24095     // address when narrowing the vector load to a specific element.
24096     // When the second source op is a memory address, insertps doesn't use
24097     // countS and just gets an f32 from that address.
24098     unsigned DestIndex =
24099         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24100
24101     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24102
24103     // Create this as a scalar to vector to match the instruction pattern.
24104     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24105     // countS bits are ignored when loading from memory on insertps, which
24106     // means we don't need to explicitly set them to 0.
24107     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24108                        LoadScalarToVector, N->getOperand(2));
24109   }
24110   return SDValue();
24111 }
24112
24113 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24114   SDValue V0 = N->getOperand(0);
24115   SDValue V1 = N->getOperand(1);
24116   SDLoc DL(N);
24117   EVT VT = N->getValueType(0);
24118
24119   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24120   // operands and changing the mask to 1. This saves us a bunch of
24121   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24122   // x86InstrInfo knows how to commute this back after instruction selection
24123   // if it would help register allocation.
24124
24125   // TODO: If optimizing for size or a processor that doesn't suffer from
24126   // partial register update stalls, this should be transformed into a MOVSD
24127   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24128
24129   if (VT == MVT::v2f64)
24130     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24131       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24132         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24133         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24134       }
24135
24136   return SDValue();
24137 }
24138
24139 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24140 // as "sbb reg,reg", since it can be extended without zext and produces
24141 // an all-ones bit which is more useful than 0/1 in some cases.
24142 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24143                                MVT VT) {
24144   if (VT == MVT::i8)
24145     return DAG.getNode(ISD::AND, DL, VT,
24146                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24147                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24148                                    EFLAGS),
24149                        DAG.getConstant(1, DL, VT));
24150   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24151   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24152                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24153                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24154                                  EFLAGS));
24155 }
24156
24157 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24158 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24159                                    TargetLowering::DAGCombinerInfo &DCI,
24160                                    const X86Subtarget *Subtarget) {
24161   SDLoc DL(N);
24162   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24163   SDValue EFLAGS = N->getOperand(1);
24164
24165   if (CC == X86::COND_A) {
24166     // Try to convert COND_A into COND_B in an attempt to facilitate
24167     // materializing "setb reg".
24168     //
24169     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24170     // cannot take an immediate as its first operand.
24171     //
24172     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24173         EFLAGS.getValueType().isInteger() &&
24174         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24175       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24176                                    EFLAGS.getNode()->getVTList(),
24177                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24178       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24179       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24180     }
24181   }
24182
24183   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24184   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24185   // cases.
24186   if (CC == X86::COND_B)
24187     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24188
24189   SDValue Flags;
24190
24191   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24192   if (Flags.getNode()) {
24193     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24194     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24195   }
24196
24197   return SDValue();
24198 }
24199
24200 // Optimize branch condition evaluation.
24201 //
24202 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24203                                     TargetLowering::DAGCombinerInfo &DCI,
24204                                     const X86Subtarget *Subtarget) {
24205   SDLoc DL(N);
24206   SDValue Chain = N->getOperand(0);
24207   SDValue Dest = N->getOperand(1);
24208   SDValue EFLAGS = N->getOperand(3);
24209   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24210
24211   SDValue Flags;
24212
24213   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24214   if (Flags.getNode()) {
24215     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24216     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24217                        Flags);
24218   }
24219
24220   return SDValue();
24221 }
24222
24223 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24224                                                          SelectionDAG &DAG) {
24225   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24226   // optimize away operation when it's from a constant.
24227   //
24228   // The general transformation is:
24229   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24230   //       AND(VECTOR_CMP(x,y), constant2)
24231   //    constant2 = UNARYOP(constant)
24232
24233   // Early exit if this isn't a vector operation, the operand of the
24234   // unary operation isn't a bitwise AND, or if the sizes of the operations
24235   // aren't the same.
24236   EVT VT = N->getValueType(0);
24237   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24238       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24239       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24240     return SDValue();
24241
24242   // Now check that the other operand of the AND is a constant. We could
24243   // make the transformation for non-constant splats as well, but it's unclear
24244   // that would be a benefit as it would not eliminate any operations, just
24245   // perform one more step in scalar code before moving to the vector unit.
24246   if (BuildVectorSDNode *BV =
24247           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24248     // Bail out if the vector isn't a constant.
24249     if (!BV->isConstant())
24250       return SDValue();
24251
24252     // Everything checks out. Build up the new and improved node.
24253     SDLoc DL(N);
24254     EVT IntVT = BV->getValueType(0);
24255     // Create a new constant of the appropriate type for the transformed
24256     // DAG.
24257     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24258     // The AND node needs bitcasts to/from an integer vector type around it.
24259     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24260     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24261                                  N->getOperand(0)->getOperand(0), MaskConst);
24262     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24263     return Res;
24264   }
24265
24266   return SDValue();
24267 }
24268
24269 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24270                                         const X86Subtarget *Subtarget) {
24271   // First try to optimize away the conversion entirely when it's
24272   // conditionally from a constant. Vectors only.
24273   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24274   if (Res != SDValue())
24275     return Res;
24276
24277   // Now move on to more general possibilities.
24278   SDValue Op0 = N->getOperand(0);
24279   EVT InVT = Op0->getValueType(0);
24280
24281   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24282   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24283     SDLoc dl(N);
24284     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24285     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24286     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24287   }
24288
24289   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24290   // a 32-bit target where SSE doesn't support i64->FP operations.
24291   if (Op0.getOpcode() == ISD::LOAD) {
24292     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24293     EVT VT = Ld->getValueType(0);
24294
24295     // This transformation is not supported if the result type is f16
24296     if (N->getValueType(0) == MVT::f16)
24297       return SDValue();
24298
24299     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24300         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24301         !Subtarget->is64Bit() && VT == MVT::i64) {
24302       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24303           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24304       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24305       return FILDChain;
24306     }
24307   }
24308   return SDValue();
24309 }
24310
24311 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24312 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24313                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24314   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24315   // the result is either zero or one (depending on the input carry bit).
24316   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24317   if (X86::isZeroNode(N->getOperand(0)) &&
24318       X86::isZeroNode(N->getOperand(1)) &&
24319       // We don't have a good way to replace an EFLAGS use, so only do this when
24320       // dead right now.
24321       SDValue(N, 1).use_empty()) {
24322     SDLoc DL(N);
24323     EVT VT = N->getValueType(0);
24324     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24325     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24326                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24327                                            DAG.getConstant(X86::COND_B, DL,
24328                                                            MVT::i8),
24329                                            N->getOperand(2)),
24330                                DAG.getConstant(1, DL, VT));
24331     return DCI.CombineTo(N, Res1, CarryOut);
24332   }
24333
24334   return SDValue();
24335 }
24336
24337 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24338 //      (add Y, (setne X, 0)) -> sbb -1, Y
24339 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24340 //      (sub (setne X, 0), Y) -> adc -1, Y
24341 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24342   SDLoc DL(N);
24343
24344   // Look through ZExts.
24345   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24346   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24347     return SDValue();
24348
24349   SDValue SetCC = Ext.getOperand(0);
24350   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24351     return SDValue();
24352
24353   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24354   if (CC != X86::COND_E && CC != X86::COND_NE)
24355     return SDValue();
24356
24357   SDValue Cmp = SetCC.getOperand(1);
24358   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24359       !X86::isZeroNode(Cmp.getOperand(1)) ||
24360       !Cmp.getOperand(0).getValueType().isInteger())
24361     return SDValue();
24362
24363   SDValue CmpOp0 = Cmp.getOperand(0);
24364   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24365                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24366
24367   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24368   if (CC == X86::COND_NE)
24369     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24370                        DL, OtherVal.getValueType(), OtherVal,
24371                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24372                        NewCmp);
24373   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24374                      DL, OtherVal.getValueType(), OtherVal,
24375                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24376 }
24377
24378 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24379 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24380                                  const X86Subtarget *Subtarget) {
24381   EVT VT = N->getValueType(0);
24382   SDValue Op0 = N->getOperand(0);
24383   SDValue Op1 = N->getOperand(1);
24384
24385   // Try to synthesize horizontal adds from adds of shuffles.
24386   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24387        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24388       isHorizontalBinOp(Op0, Op1, true))
24389     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24390
24391   return OptimizeConditionalInDecrement(N, DAG);
24392 }
24393
24394 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24395                                  const X86Subtarget *Subtarget) {
24396   SDValue Op0 = N->getOperand(0);
24397   SDValue Op1 = N->getOperand(1);
24398
24399   // X86 can't encode an immediate LHS of a sub. See if we can push the
24400   // negation into a preceding instruction.
24401   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24402     // If the RHS of the sub is a XOR with one use and a constant, invert the
24403     // immediate. Then add one to the LHS of the sub so we can turn
24404     // X-Y -> X+~Y+1, saving one register.
24405     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24406         isa<ConstantSDNode>(Op1.getOperand(1))) {
24407       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24408       EVT VT = Op0.getValueType();
24409       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24410                                    Op1.getOperand(0),
24411                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24412       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24413                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24414     }
24415   }
24416
24417   // Try to synthesize horizontal adds from adds of shuffles.
24418   EVT VT = N->getValueType(0);
24419   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24420        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24421       isHorizontalBinOp(Op0, Op1, true))
24422     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24423
24424   return OptimizeConditionalInDecrement(N, DAG);
24425 }
24426
24427 /// performVZEXTCombine - Performs build vector combines
24428 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24429                                    TargetLowering::DAGCombinerInfo &DCI,
24430                                    const X86Subtarget *Subtarget) {
24431   SDLoc DL(N);
24432   MVT VT = N->getSimpleValueType(0);
24433   SDValue Op = N->getOperand(0);
24434   MVT OpVT = Op.getSimpleValueType();
24435   MVT OpEltVT = OpVT.getVectorElementType();
24436   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24437
24438   // (vzext (bitcast (vzext (x)) -> (vzext x)
24439   SDValue V = Op;
24440   while (V.getOpcode() == ISD::BITCAST)
24441     V = V.getOperand(0);
24442
24443   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24444     MVT InnerVT = V.getSimpleValueType();
24445     MVT InnerEltVT = InnerVT.getVectorElementType();
24446
24447     // If the element sizes match exactly, we can just do one larger vzext. This
24448     // is always an exact type match as vzext operates on integer types.
24449     if (OpEltVT == InnerEltVT) {
24450       assert(OpVT == InnerVT && "Types must match for vzext!");
24451       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24452     }
24453
24454     // The only other way we can combine them is if only a single element of the
24455     // inner vzext is used in the input to the outer vzext.
24456     if (InnerEltVT.getSizeInBits() < InputBits)
24457       return SDValue();
24458
24459     // In this case, the inner vzext is completely dead because we're going to
24460     // only look at bits inside of the low element. Just do the outer vzext on
24461     // a bitcast of the input to the inner.
24462     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24463                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24464   }
24465
24466   // Check if we can bypass extracting and re-inserting an element of an input
24467   // vector. Essentialy:
24468   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24469   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24470       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24471       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24472     SDValue ExtractedV = V.getOperand(0);
24473     SDValue OrigV = ExtractedV.getOperand(0);
24474     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24475       if (ExtractIdx->getZExtValue() == 0) {
24476         MVT OrigVT = OrigV.getSimpleValueType();
24477         // Extract a subvector if necessary...
24478         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24479           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24480           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24481                                     OrigVT.getVectorNumElements() / Ratio);
24482           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24483                               DAG.getIntPtrConstant(0, DL));
24484         }
24485         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24486         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24487       }
24488   }
24489
24490   return SDValue();
24491 }
24492
24493 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24494                                              DAGCombinerInfo &DCI) const {
24495   SelectionDAG &DAG = DCI.DAG;
24496   switch (N->getOpcode()) {
24497   default: break;
24498   case ISD::EXTRACT_VECTOR_ELT:
24499     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24500   case ISD::VSELECT:
24501   case ISD::SELECT:
24502   case X86ISD::SHRUNKBLEND:
24503     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24504   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24505   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24506   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24507   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24508   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24509   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24510   case ISD::SHL:
24511   case ISD::SRA:
24512   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24513   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24514   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24515   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24516   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24517   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24518   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24519   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24520   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24521   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24522   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24523   case X86ISD::FXOR:
24524   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24525   case X86ISD::FMIN:
24526   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24527   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24528   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24529   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24530   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24531   case ISD::ANY_EXTEND:
24532   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24533   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24534   case ISD::SIGN_EXTEND_INREG:
24535     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24536   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24537   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24538   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24539   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24540   case X86ISD::SHUFP:       // Handle all target specific shuffles
24541   case X86ISD::PALIGNR:
24542   case X86ISD::UNPCKH:
24543   case X86ISD::UNPCKL:
24544   case X86ISD::MOVHLPS:
24545   case X86ISD::MOVLHPS:
24546   case X86ISD::PSHUFB:
24547   case X86ISD::PSHUFD:
24548   case X86ISD::PSHUFHW:
24549   case X86ISD::PSHUFLW:
24550   case X86ISD::MOVSS:
24551   case X86ISD::MOVSD:
24552   case X86ISD::VPERMILPI:
24553   case X86ISD::VPERM2X128:
24554   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24555   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24556   case ISD::INTRINSIC_WO_CHAIN:
24557     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24558   case X86ISD::INSERTPS: {
24559     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24560       return PerformINSERTPSCombine(N, DAG, Subtarget);
24561     break;
24562   }
24563   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24564   }
24565
24566   return SDValue();
24567 }
24568
24569 /// isTypeDesirableForOp - Return true if the target has native support for
24570 /// the specified value type and it is 'desirable' to use the type for the
24571 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24572 /// instruction encodings are longer and some i16 instructions are slow.
24573 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24574   if (!isTypeLegal(VT))
24575     return false;
24576   if (VT != MVT::i16)
24577     return true;
24578
24579   switch (Opc) {
24580   default:
24581     return true;
24582   case ISD::LOAD:
24583   case ISD::SIGN_EXTEND:
24584   case ISD::ZERO_EXTEND:
24585   case ISD::ANY_EXTEND:
24586   case ISD::SHL:
24587   case ISD::SRL:
24588   case ISD::SUB:
24589   case ISD::ADD:
24590   case ISD::MUL:
24591   case ISD::AND:
24592   case ISD::OR:
24593   case ISD::XOR:
24594     return false;
24595   }
24596 }
24597
24598 /// IsDesirableToPromoteOp - This method query the target whether it is
24599 /// beneficial for dag combiner to promote the specified node. If true, it
24600 /// should return the desired promotion type by reference.
24601 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24602   EVT VT = Op.getValueType();
24603   if (VT != MVT::i16)
24604     return false;
24605
24606   bool Promote = false;
24607   bool Commute = false;
24608   switch (Op.getOpcode()) {
24609   default: break;
24610   case ISD::LOAD: {
24611     LoadSDNode *LD = cast<LoadSDNode>(Op);
24612     // If the non-extending load has a single use and it's not live out, then it
24613     // might be folded.
24614     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24615                                                      Op.hasOneUse()*/) {
24616       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24617              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24618         // The only case where we'd want to promote LOAD (rather then it being
24619         // promoted as an operand is when it's only use is liveout.
24620         if (UI->getOpcode() != ISD::CopyToReg)
24621           return false;
24622       }
24623     }
24624     Promote = true;
24625     break;
24626   }
24627   case ISD::SIGN_EXTEND:
24628   case ISD::ZERO_EXTEND:
24629   case ISD::ANY_EXTEND:
24630     Promote = true;
24631     break;
24632   case ISD::SHL:
24633   case ISD::SRL: {
24634     SDValue N0 = Op.getOperand(0);
24635     // Look out for (store (shl (load), x)).
24636     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24637       return false;
24638     Promote = true;
24639     break;
24640   }
24641   case ISD::ADD:
24642   case ISD::MUL:
24643   case ISD::AND:
24644   case ISD::OR:
24645   case ISD::XOR:
24646     Commute = true;
24647     // fallthrough
24648   case ISD::SUB: {
24649     SDValue N0 = Op.getOperand(0);
24650     SDValue N1 = Op.getOperand(1);
24651     if (!Commute && MayFoldLoad(N1))
24652       return false;
24653     // Avoid disabling potential load folding opportunities.
24654     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24655       return false;
24656     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24657       return false;
24658     Promote = true;
24659   }
24660   }
24661
24662   PVT = MVT::i32;
24663   return Promote;
24664 }
24665
24666 //===----------------------------------------------------------------------===//
24667 //                           X86 Inline Assembly Support
24668 //===----------------------------------------------------------------------===//
24669
24670 // Helper to match a string separated by whitespace.
24671 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24672   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24673
24674   for (StringRef Piece : Pieces) {
24675     if (!S.startswith(Piece)) // Check if the piece matches.
24676       return false;
24677
24678     S = S.substr(Piece.size());
24679     StringRef::size_type Pos = S.find_first_not_of(" \t");
24680     if (Pos == 0) // We matched a prefix.
24681       return false;
24682
24683     S = S.substr(Pos);
24684   }
24685
24686   return S.empty();
24687 }
24688
24689 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24690
24691   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24692     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24693         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24694         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24695
24696       if (AsmPieces.size() == 3)
24697         return true;
24698       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24699         return true;
24700     }
24701   }
24702   return false;
24703 }
24704
24705 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24706   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24707
24708   std::string AsmStr = IA->getAsmString();
24709
24710   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24711   if (!Ty || Ty->getBitWidth() % 16 != 0)
24712     return false;
24713
24714   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24715   SmallVector<StringRef, 4> AsmPieces;
24716   SplitString(AsmStr, AsmPieces, ";\n");
24717
24718   switch (AsmPieces.size()) {
24719   default: return false;
24720   case 1:
24721     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24722     // we will turn this bswap into something that will be lowered to logical
24723     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24724     // lower so don't worry about this.
24725     // bswap $0
24726     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24727         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24728         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24729         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24730         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24731         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24732       // No need to check constraints, nothing other than the equivalent of
24733       // "=r,0" would be valid here.
24734       return IntrinsicLowering::LowerToByteSwap(CI);
24735     }
24736
24737     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24738     if (CI->getType()->isIntegerTy(16) &&
24739         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24740         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24741          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24742       AsmPieces.clear();
24743       const std::string &ConstraintsStr = IA->getConstraintString();
24744       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24745       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24746       if (clobbersFlagRegisters(AsmPieces))
24747         return IntrinsicLowering::LowerToByteSwap(CI);
24748     }
24749     break;
24750   case 3:
24751     if (CI->getType()->isIntegerTy(32) &&
24752         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24753         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24754         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24755         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24756       AsmPieces.clear();
24757       const std::string &ConstraintsStr = IA->getConstraintString();
24758       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24759       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24760       if (clobbersFlagRegisters(AsmPieces))
24761         return IntrinsicLowering::LowerToByteSwap(CI);
24762     }
24763
24764     if (CI->getType()->isIntegerTy(64)) {
24765       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24766       if (Constraints.size() >= 2 &&
24767           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24768           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24769         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24770         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24771             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24772             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24773           return IntrinsicLowering::LowerToByteSwap(CI);
24774       }
24775     }
24776     break;
24777   }
24778   return false;
24779 }
24780
24781 /// getConstraintType - Given a constraint letter, return the type of
24782 /// constraint it is for this target.
24783 X86TargetLowering::ConstraintType
24784 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24785   if (Constraint.size() == 1) {
24786     switch (Constraint[0]) {
24787     case 'R':
24788     case 'q':
24789     case 'Q':
24790     case 'f':
24791     case 't':
24792     case 'u':
24793     case 'y':
24794     case 'x':
24795     case 'Y':
24796     case 'l':
24797       return C_RegisterClass;
24798     case 'a':
24799     case 'b':
24800     case 'c':
24801     case 'd':
24802     case 'S':
24803     case 'D':
24804     case 'A':
24805       return C_Register;
24806     case 'I':
24807     case 'J':
24808     case 'K':
24809     case 'L':
24810     case 'M':
24811     case 'N':
24812     case 'G':
24813     case 'C':
24814     case 'e':
24815     case 'Z':
24816       return C_Other;
24817     default:
24818       break;
24819     }
24820   }
24821   return TargetLowering::getConstraintType(Constraint);
24822 }
24823
24824 /// Examine constraint type and operand type and determine a weight value.
24825 /// This object must already have been set up with the operand type
24826 /// and the current alternative constraint selected.
24827 TargetLowering::ConstraintWeight
24828   X86TargetLowering::getSingleConstraintMatchWeight(
24829     AsmOperandInfo &info, const char *constraint) const {
24830   ConstraintWeight weight = CW_Invalid;
24831   Value *CallOperandVal = info.CallOperandVal;
24832     // If we don't have a value, we can't do a match,
24833     // but allow it at the lowest weight.
24834   if (!CallOperandVal)
24835     return CW_Default;
24836   Type *type = CallOperandVal->getType();
24837   // Look at the constraint type.
24838   switch (*constraint) {
24839   default:
24840     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24841   case 'R':
24842   case 'q':
24843   case 'Q':
24844   case 'a':
24845   case 'b':
24846   case 'c':
24847   case 'd':
24848   case 'S':
24849   case 'D':
24850   case 'A':
24851     if (CallOperandVal->getType()->isIntegerTy())
24852       weight = CW_SpecificReg;
24853     break;
24854   case 'f':
24855   case 't':
24856   case 'u':
24857     if (type->isFloatingPointTy())
24858       weight = CW_SpecificReg;
24859     break;
24860   case 'y':
24861     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24862       weight = CW_SpecificReg;
24863     break;
24864   case 'x':
24865   case 'Y':
24866     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24867         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24868       weight = CW_Register;
24869     break;
24870   case 'I':
24871     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24872       if (C->getZExtValue() <= 31)
24873         weight = CW_Constant;
24874     }
24875     break;
24876   case 'J':
24877     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24878       if (C->getZExtValue() <= 63)
24879         weight = CW_Constant;
24880     }
24881     break;
24882   case 'K':
24883     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24884       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24885         weight = CW_Constant;
24886     }
24887     break;
24888   case 'L':
24889     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24890       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24891         weight = CW_Constant;
24892     }
24893     break;
24894   case 'M':
24895     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24896       if (C->getZExtValue() <= 3)
24897         weight = CW_Constant;
24898     }
24899     break;
24900   case 'N':
24901     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24902       if (C->getZExtValue() <= 0xff)
24903         weight = CW_Constant;
24904     }
24905     break;
24906   case 'G':
24907   case 'C':
24908     if (isa<ConstantFP>(CallOperandVal)) {
24909       weight = CW_Constant;
24910     }
24911     break;
24912   case 'e':
24913     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24914       if ((C->getSExtValue() >= -0x80000000LL) &&
24915           (C->getSExtValue() <= 0x7fffffffLL))
24916         weight = CW_Constant;
24917     }
24918     break;
24919   case 'Z':
24920     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24921       if (C->getZExtValue() <= 0xffffffff)
24922         weight = CW_Constant;
24923     }
24924     break;
24925   }
24926   return weight;
24927 }
24928
24929 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24930 /// with another that has more specific requirements based on the type of the
24931 /// corresponding operand.
24932 const char *X86TargetLowering::
24933 LowerXConstraint(EVT ConstraintVT) const {
24934   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24935   // 'f' like normal targets.
24936   if (ConstraintVT.isFloatingPoint()) {
24937     if (Subtarget->hasSSE2())
24938       return "Y";
24939     if (Subtarget->hasSSE1())
24940       return "x";
24941   }
24942
24943   return TargetLowering::LowerXConstraint(ConstraintVT);
24944 }
24945
24946 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24947 /// vector.  If it is invalid, don't add anything to Ops.
24948 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24949                                                      std::string &Constraint,
24950                                                      std::vector<SDValue>&Ops,
24951                                                      SelectionDAG &DAG) const {
24952   SDValue Result;
24953
24954   // Only support length 1 constraints for now.
24955   if (Constraint.length() > 1) return;
24956
24957   char ConstraintLetter = Constraint[0];
24958   switch (ConstraintLetter) {
24959   default: break;
24960   case 'I':
24961     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24962       if (C->getZExtValue() <= 31) {
24963         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24964                                        Op.getValueType());
24965         break;
24966       }
24967     }
24968     return;
24969   case 'J':
24970     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24971       if (C->getZExtValue() <= 63) {
24972         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24973                                        Op.getValueType());
24974         break;
24975       }
24976     }
24977     return;
24978   case 'K':
24979     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24980       if (isInt<8>(C->getSExtValue())) {
24981         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24982                                        Op.getValueType());
24983         break;
24984       }
24985     }
24986     return;
24987   case 'L':
24988     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24989       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24990           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24991         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24992                                        Op.getValueType());
24993         break;
24994       }
24995     }
24996     return;
24997   case 'M':
24998     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24999       if (C->getZExtValue() <= 3) {
25000         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25001                                        Op.getValueType());
25002         break;
25003       }
25004     }
25005     return;
25006   case 'N':
25007     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25008       if (C->getZExtValue() <= 255) {
25009         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25010                                        Op.getValueType());
25011         break;
25012       }
25013     }
25014     return;
25015   case 'O':
25016     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25017       if (C->getZExtValue() <= 127) {
25018         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25019                                        Op.getValueType());
25020         break;
25021       }
25022     }
25023     return;
25024   case 'e': {
25025     // 32-bit signed value
25026     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25027       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25028                                            C->getSExtValue())) {
25029         // Widen to 64 bits here to get it sign extended.
25030         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25031         break;
25032       }
25033     // FIXME gcc accepts some relocatable values here too, but only in certain
25034     // memory models; it's complicated.
25035     }
25036     return;
25037   }
25038   case 'Z': {
25039     // 32-bit unsigned value
25040     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25041       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25042                                            C->getZExtValue())) {
25043         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25044                                        Op.getValueType());
25045         break;
25046       }
25047     }
25048     // FIXME gcc accepts some relocatable values here too, but only in certain
25049     // memory models; it's complicated.
25050     return;
25051   }
25052   case 'i': {
25053     // Literal immediates are always ok.
25054     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25055       // Widen to 64 bits here to get it sign extended.
25056       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25057       break;
25058     }
25059
25060     // In any sort of PIC mode addresses need to be computed at runtime by
25061     // adding in a register or some sort of table lookup.  These can't
25062     // be used as immediates.
25063     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25064       return;
25065
25066     // If we are in non-pic codegen mode, we allow the address of a global (with
25067     // an optional displacement) to be used with 'i'.
25068     GlobalAddressSDNode *GA = nullptr;
25069     int64_t Offset = 0;
25070
25071     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25072     while (1) {
25073       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25074         Offset += GA->getOffset();
25075         break;
25076       } else if (Op.getOpcode() == ISD::ADD) {
25077         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25078           Offset += C->getZExtValue();
25079           Op = Op.getOperand(0);
25080           continue;
25081         }
25082       } else if (Op.getOpcode() == ISD::SUB) {
25083         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25084           Offset += -C->getZExtValue();
25085           Op = Op.getOperand(0);
25086           continue;
25087         }
25088       }
25089
25090       // Otherwise, this isn't something we can handle, reject it.
25091       return;
25092     }
25093
25094     const GlobalValue *GV = GA->getGlobal();
25095     // If we require an extra load to get this address, as in PIC mode, we
25096     // can't accept it.
25097     if (isGlobalStubReference(
25098             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25099       return;
25100
25101     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25102                                         GA->getValueType(0), Offset);
25103     break;
25104   }
25105   }
25106
25107   if (Result.getNode()) {
25108     Ops.push_back(Result);
25109     return;
25110   }
25111   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25112 }
25113
25114 std::pair<unsigned, const TargetRegisterClass *>
25115 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25116                                                 const std::string &Constraint,
25117                                                 MVT VT) const {
25118   // First, see if this is a constraint that directly corresponds to an LLVM
25119   // register class.
25120   if (Constraint.size() == 1) {
25121     // GCC Constraint Letters
25122     switch (Constraint[0]) {
25123     default: break;
25124       // TODO: Slight differences here in allocation order and leaving
25125       // RIP in the class. Do they matter any more here than they do
25126       // in the normal allocation?
25127     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25128       if (Subtarget->is64Bit()) {
25129         if (VT == MVT::i32 || VT == MVT::f32)
25130           return std::make_pair(0U, &X86::GR32RegClass);
25131         if (VT == MVT::i16)
25132           return std::make_pair(0U, &X86::GR16RegClass);
25133         if (VT == MVT::i8 || VT == MVT::i1)
25134           return std::make_pair(0U, &X86::GR8RegClass);
25135         if (VT == MVT::i64 || VT == MVT::f64)
25136           return std::make_pair(0U, &X86::GR64RegClass);
25137         break;
25138       }
25139       // 32-bit fallthrough
25140     case 'Q':   // Q_REGS
25141       if (VT == MVT::i32 || VT == MVT::f32)
25142         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25143       if (VT == MVT::i16)
25144         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25145       if (VT == MVT::i8 || VT == MVT::i1)
25146         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25147       if (VT == MVT::i64)
25148         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25149       break;
25150     case 'r':   // GENERAL_REGS
25151     case 'l':   // INDEX_REGS
25152       if (VT == MVT::i8 || VT == MVT::i1)
25153         return std::make_pair(0U, &X86::GR8RegClass);
25154       if (VT == MVT::i16)
25155         return std::make_pair(0U, &X86::GR16RegClass);
25156       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25157         return std::make_pair(0U, &X86::GR32RegClass);
25158       return std::make_pair(0U, &X86::GR64RegClass);
25159     case 'R':   // LEGACY_REGS
25160       if (VT == MVT::i8 || VT == MVT::i1)
25161         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25162       if (VT == MVT::i16)
25163         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25164       if (VT == MVT::i32 || !Subtarget->is64Bit())
25165         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25166       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25167     case 'f':  // FP Stack registers.
25168       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25169       // value to the correct fpstack register class.
25170       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25171         return std::make_pair(0U, &X86::RFP32RegClass);
25172       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25173         return std::make_pair(0U, &X86::RFP64RegClass);
25174       return std::make_pair(0U, &X86::RFP80RegClass);
25175     case 'y':   // MMX_REGS if MMX allowed.
25176       if (!Subtarget->hasMMX()) break;
25177       return std::make_pair(0U, &X86::VR64RegClass);
25178     case 'Y':   // SSE_REGS if SSE2 allowed
25179       if (!Subtarget->hasSSE2()) break;
25180       // FALL THROUGH.
25181     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25182       if (!Subtarget->hasSSE1()) break;
25183
25184       switch (VT.SimpleTy) {
25185       default: break;
25186       // Scalar SSE types.
25187       case MVT::f32:
25188       case MVT::i32:
25189         return std::make_pair(0U, &X86::FR32RegClass);
25190       case MVT::f64:
25191       case MVT::i64:
25192         return std::make_pair(0U, &X86::FR64RegClass);
25193       // Vector types.
25194       case MVT::v16i8:
25195       case MVT::v8i16:
25196       case MVT::v4i32:
25197       case MVT::v2i64:
25198       case MVT::v4f32:
25199       case MVT::v2f64:
25200         return std::make_pair(0U, &X86::VR128RegClass);
25201       // AVX types.
25202       case MVT::v32i8:
25203       case MVT::v16i16:
25204       case MVT::v8i32:
25205       case MVT::v4i64:
25206       case MVT::v8f32:
25207       case MVT::v4f64:
25208         return std::make_pair(0U, &X86::VR256RegClass);
25209       case MVT::v8f64:
25210       case MVT::v16f32:
25211       case MVT::v16i32:
25212       case MVT::v8i64:
25213         return std::make_pair(0U, &X86::VR512RegClass);
25214       }
25215       break;
25216     }
25217   }
25218
25219   // Use the default implementation in TargetLowering to convert the register
25220   // constraint into a member of a register class.
25221   std::pair<unsigned, const TargetRegisterClass*> Res;
25222   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25223
25224   // Not found as a standard register?
25225   if (!Res.second) {
25226     // Map st(0) -> st(7) -> ST0
25227     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25228         tolower(Constraint[1]) == 's' &&
25229         tolower(Constraint[2]) == 't' &&
25230         Constraint[3] == '(' &&
25231         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25232         Constraint[5] == ')' &&
25233         Constraint[6] == '}') {
25234
25235       Res.first = X86::FP0+Constraint[4]-'0';
25236       Res.second = &X86::RFP80RegClass;
25237       return Res;
25238     }
25239
25240     // GCC allows "st(0)" to be called just plain "st".
25241     if (StringRef("{st}").equals_lower(Constraint)) {
25242       Res.first = X86::FP0;
25243       Res.second = &X86::RFP80RegClass;
25244       return Res;
25245     }
25246
25247     // flags -> EFLAGS
25248     if (StringRef("{flags}").equals_lower(Constraint)) {
25249       Res.first = X86::EFLAGS;
25250       Res.second = &X86::CCRRegClass;
25251       return Res;
25252     }
25253
25254     // 'A' means EAX + EDX.
25255     if (Constraint == "A") {
25256       Res.first = X86::EAX;
25257       Res.second = &X86::GR32_ADRegClass;
25258       return Res;
25259     }
25260     return Res;
25261   }
25262
25263   // Otherwise, check to see if this is a register class of the wrong value
25264   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25265   // turn into {ax},{dx}.
25266   if (Res.second->hasType(VT))
25267     return Res;   // Correct type already, nothing to do.
25268
25269   // All of the single-register GCC register classes map their values onto
25270   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25271   // really want an 8-bit or 32-bit register, map to the appropriate register
25272   // class and return the appropriate register.
25273   if (Res.second == &X86::GR16RegClass) {
25274     if (VT == MVT::i8 || VT == MVT::i1) {
25275       unsigned DestReg = 0;
25276       switch (Res.first) {
25277       default: break;
25278       case X86::AX: DestReg = X86::AL; break;
25279       case X86::DX: DestReg = X86::DL; break;
25280       case X86::CX: DestReg = X86::CL; break;
25281       case X86::BX: DestReg = X86::BL; break;
25282       }
25283       if (DestReg) {
25284         Res.first = DestReg;
25285         Res.second = &X86::GR8RegClass;
25286       }
25287     } else if (VT == MVT::i32 || VT == MVT::f32) {
25288       unsigned DestReg = 0;
25289       switch (Res.first) {
25290       default: break;
25291       case X86::AX: DestReg = X86::EAX; break;
25292       case X86::DX: DestReg = X86::EDX; break;
25293       case X86::CX: DestReg = X86::ECX; break;
25294       case X86::BX: DestReg = X86::EBX; break;
25295       case X86::SI: DestReg = X86::ESI; break;
25296       case X86::DI: DestReg = X86::EDI; break;
25297       case X86::BP: DestReg = X86::EBP; break;
25298       case X86::SP: DestReg = X86::ESP; break;
25299       }
25300       if (DestReg) {
25301         Res.first = DestReg;
25302         Res.second = &X86::GR32RegClass;
25303       }
25304     } else if (VT == MVT::i64 || VT == MVT::f64) {
25305       unsigned DestReg = 0;
25306       switch (Res.first) {
25307       default: break;
25308       case X86::AX: DestReg = X86::RAX; break;
25309       case X86::DX: DestReg = X86::RDX; break;
25310       case X86::CX: DestReg = X86::RCX; break;
25311       case X86::BX: DestReg = X86::RBX; break;
25312       case X86::SI: DestReg = X86::RSI; break;
25313       case X86::DI: DestReg = X86::RDI; break;
25314       case X86::BP: DestReg = X86::RBP; break;
25315       case X86::SP: DestReg = X86::RSP; break;
25316       }
25317       if (DestReg) {
25318         Res.first = DestReg;
25319         Res.second = &X86::GR64RegClass;
25320       }
25321     }
25322   } else if (Res.second == &X86::FR32RegClass ||
25323              Res.second == &X86::FR64RegClass ||
25324              Res.second == &X86::VR128RegClass ||
25325              Res.second == &X86::VR256RegClass ||
25326              Res.second == &X86::FR32XRegClass ||
25327              Res.second == &X86::FR64XRegClass ||
25328              Res.second == &X86::VR128XRegClass ||
25329              Res.second == &X86::VR256XRegClass ||
25330              Res.second == &X86::VR512RegClass) {
25331     // Handle references to XMM physical registers that got mapped into the
25332     // wrong class.  This can happen with constraints like {xmm0} where the
25333     // target independent register mapper will just pick the first match it can
25334     // find, ignoring the required type.
25335
25336     if (VT == MVT::f32 || VT == MVT::i32)
25337       Res.second = &X86::FR32RegClass;
25338     else if (VT == MVT::f64 || VT == MVT::i64)
25339       Res.second = &X86::FR64RegClass;
25340     else if (X86::VR128RegClass.hasType(VT))
25341       Res.second = &X86::VR128RegClass;
25342     else if (X86::VR256RegClass.hasType(VT))
25343       Res.second = &X86::VR256RegClass;
25344     else if (X86::VR512RegClass.hasType(VT))
25345       Res.second = &X86::VR512RegClass;
25346   }
25347
25348   return Res;
25349 }
25350
25351 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25352                                             Type *Ty) const {
25353   // Scaling factors are not free at all.
25354   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25355   // will take 2 allocations in the out of order engine instead of 1
25356   // for plain addressing mode, i.e. inst (reg1).
25357   // E.g.,
25358   // vaddps (%rsi,%drx), %ymm0, %ymm1
25359   // Requires two allocations (one for the load, one for the computation)
25360   // whereas:
25361   // vaddps (%rsi), %ymm0, %ymm1
25362   // Requires just 1 allocation, i.e., freeing allocations for other operations
25363   // and having less micro operations to execute.
25364   //
25365   // For some X86 architectures, this is even worse because for instance for
25366   // stores, the complex addressing mode forces the instruction to use the
25367   // "load" ports instead of the dedicated "store" port.
25368   // E.g., on Haswell:
25369   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25370   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25371   if (isLegalAddressingMode(AM, Ty))
25372     // Scale represents reg2 * scale, thus account for 1
25373     // as soon as we use a second register.
25374     return AM.Scale != 0;
25375   return -1;
25376 }
25377
25378 bool X86TargetLowering::isTargetFTOL() const {
25379   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25380 }