AVX-512: select operation for i1 vectors
[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::SRL,               MVT::v8i16, Custom);
1008     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1009
1010     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1015
1016     // In the customized shift lowering, the legal cases in AVX2 will be
1017     // recognized.
1018     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1025   }
1026
1027   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1028     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1029     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1030     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1031     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1032     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1034
1035     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1036     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1038
1039     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1041     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1042     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1043     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1044     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1045     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1046     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1047     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1049     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1050     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1051
1052     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1055     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1056     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1062     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1063     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1064
1065     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1066     // even though v8i16 is a legal type.
1067     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1068     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1070
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1073     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1074
1075     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1076     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1077
1078     for (MVT VT : MVT::fp_vector_valuetypes())
1079       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1080
1081     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1082     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1083
1084     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1085     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1086
1087     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1088     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1089
1090     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1091     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1092     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1093     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1094
1095     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1096     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1097     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1098
1099     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1100     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1101     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1102     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1103     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1104     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1105     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1106     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1107     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1108     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1109     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1110     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1111
1112     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1113       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1114       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1115       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1116       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1117       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1118       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1119     }
1120
1121     if (Subtarget->hasInt256()) {
1122       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1123       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1125       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1126
1127       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1128       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1129       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1130       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1131
1132       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1133       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1134       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1135       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1136
1137       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1138       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1139       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1140       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1141
1142       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1143       // when we have a 256bit-wide blend with immediate.
1144       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1145
1146       // Only provide customized ctpop vector bit twiddling for vector types we
1147       // know to perform better than using the popcnt instructions on each
1148       // vector element. If popcnt isn't supported, always provide the custom
1149       // version.
1150       if (!Subtarget->hasPOPCNT())
1151         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1152
1153       // Custom CTPOP always performs better on natively supported v8i32
1154       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1155
1156       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1157       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1158       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1159       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1160       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1161       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1162       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1163
1164       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1165       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1166       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1167       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1168       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1169       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1170     } else {
1171       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1173       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1174       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1175
1176       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1178       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1179       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1180
1181       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1182       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1183       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1184       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1185     }
1186
1187     // In the customized shift lowering, the legal cases in AVX2 will be
1188     // recognized.
1189     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1190     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1191
1192     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1193     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1194
1195     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1196
1197     // Custom lower several nodes for 256-bit types.
1198     for (MVT VT : MVT::vector_valuetypes()) {
1199       if (VT.getScalarSizeInBits() >= 32) {
1200         setOperationAction(ISD::MLOAD,  VT, Legal);
1201         setOperationAction(ISD::MSTORE, VT, Legal);
1202       }
1203       // Extract subvector is special because the value type
1204       // (result) is 128-bit but the source is 256-bit wide.
1205       if (VT.is128BitVector()) {
1206         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1207       }
1208       // Do not attempt to custom lower other non-256-bit vectors
1209       if (!VT.is256BitVector())
1210         continue;
1211
1212       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1213       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1214       setOperationAction(ISD::VSELECT,            VT, Custom);
1215       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1216       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1217       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1218       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1219       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1220     }
1221
1222     if (Subtarget->hasInt256())
1223       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1224
1225
1226     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1227     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1228       MVT VT = (MVT::SimpleValueType)i;
1229
1230       // Do not attempt to promote non-256-bit vectors
1231       if (!VT.is256BitVector())
1232         continue;
1233
1234       setOperationAction(ISD::AND,    VT, Promote);
1235       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1236       setOperationAction(ISD::OR,     VT, Promote);
1237       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1238       setOperationAction(ISD::XOR,    VT, Promote);
1239       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1240       setOperationAction(ISD::LOAD,   VT, Promote);
1241       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1242       setOperationAction(ISD::SELECT, VT, Promote);
1243       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1244     }
1245   }
1246
1247   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1248     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1249     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1250     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1251     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1252
1253     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1254     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1255     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1256
1257     for (MVT VT : MVT::fp_vector_valuetypes())
1258       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1259
1260     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1261     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1262     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1263     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1264     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1265     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1266     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1267     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1268     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1269     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1270
1271     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1272     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1273     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1274     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1275     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1276     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1277
1278     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1279     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1280     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1281     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1282     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1283     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1284     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1285     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1286
1287     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1288     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1289     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1290     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1291     if (Subtarget->is64Bit()) {
1292       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1293       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1294       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1295       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1296     }
1297     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1298     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1299     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1300     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1301     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1302     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1303     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1304     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1305     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1306     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1307     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1308     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1309     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1310     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1311     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1312     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1313
1314     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1315     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1316     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1317     if (Subtarget->hasDQI()) {
1318       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1319       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1320     }
1321     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1322     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1323     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1324     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1325     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1326     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1327     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1328     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1329     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1330     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1331     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1332     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1333     if (Subtarget->hasDQI()) {
1334       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1335       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1336     }
1337     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1338     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1339     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1340     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1341     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1342     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1343     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1344     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1346     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1347
1348     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1349     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1350     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1351     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1352     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1353
1354     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1355     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1356
1357     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1358
1359     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1360     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1361     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1362     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1363     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1364     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1365     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1366     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1367     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1368     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1370
1371     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1372     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1373
1374     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1375     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1376
1377     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1380     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1381
1382     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1383     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1384
1385     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1386     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1387
1388     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1389     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1390     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1392     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1393     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1394
1395     if (Subtarget->hasCDI()) {
1396       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1397       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1398     }
1399     if (Subtarget->hasDQI()) {
1400       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1401       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1402       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1403     }
1404     // Custom lower several nodes.
1405     for (MVT VT : MVT::vector_valuetypes()) {
1406       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1407       if (EltSize == 1) {
1408         setOperationAction(ISD::AND, VT, Legal);
1409         setOperationAction(ISD::OR,  VT, Legal);
1410         setOperationAction(ISD::XOR,  VT, Legal);
1411       }
1412       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1413         setOperationAction(ISD::MGATHER,  VT, Custom);
1414         setOperationAction(ISD::MSCATTER, VT, Custom);
1415       }
1416       // Extract subvector is special because the value type
1417       // (result) is 256/128-bit but the source is 512-bit wide.
1418       if (VT.is128BitVector() || VT.is256BitVector()) {
1419         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1420       }
1421       if (VT.getVectorElementType() == MVT::i1)
1422         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1423
1424       // Do not attempt to custom lower other non-512-bit vectors
1425       if (!VT.is512BitVector())
1426         continue;
1427
1428       if (EltSize >= 32) {
1429         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1430         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1431         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1432         setOperationAction(ISD::VSELECT,             VT, Legal);
1433         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1434         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1435         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1436         setOperationAction(ISD::MLOAD,               VT, Legal);
1437         setOperationAction(ISD::MSTORE,              VT, Legal);
1438       }
1439     }
1440     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1441       MVT VT = (MVT::SimpleValueType)i;
1442
1443       // Do not attempt to promote non-512-bit vectors.
1444       if (!VT.is512BitVector())
1445         continue;
1446
1447       setOperationAction(ISD::SELECT, VT, Promote);
1448       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1449     }
1450   }// has  AVX-512
1451
1452   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1453     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1454     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1455
1456     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1457     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1458
1459     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1460     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1461     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1462     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1463     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1464     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1466     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1467     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1468     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1470     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1471     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1472     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1474
1475     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1476       const MVT VT = (MVT::SimpleValueType)i;
1477
1478       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1479
1480       // Do not attempt to promote non-512-bit vectors.
1481       if (!VT.is512BitVector())
1482         continue;
1483
1484       if (EltSize < 32) {
1485         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1486         setOperationAction(ISD::VSELECT,             VT, Legal);
1487       }
1488     }
1489   }
1490
1491   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1492     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1493     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1494
1495     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1496     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1497     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1498     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1499     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1500     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1501     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1502     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1503
1504     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1505     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1506     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1507     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1508     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1509     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1510   }
1511
1512   // We want to custom lower some of our intrinsics.
1513   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1514   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1515   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1516   if (!Subtarget->is64Bit())
1517     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1518
1519   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1520   // handle type legalization for these operations here.
1521   //
1522   // FIXME: We really should do custom legalization for addition and
1523   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1524   // than generic legalization for 64-bit multiplication-with-overflow, though.
1525   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1526     // Add/Sub/Mul with overflow operations are custom lowered.
1527     MVT VT = IntVTs[i];
1528     setOperationAction(ISD::SADDO, VT, Custom);
1529     setOperationAction(ISD::UADDO, VT, Custom);
1530     setOperationAction(ISD::SSUBO, VT, Custom);
1531     setOperationAction(ISD::USUBO, VT, Custom);
1532     setOperationAction(ISD::SMULO, VT, Custom);
1533     setOperationAction(ISD::UMULO, VT, Custom);
1534   }
1535
1536
1537   if (!Subtarget->is64Bit()) {
1538     // These libcalls are not available in 32-bit.
1539     setLibcallName(RTLIB::SHL_I128, nullptr);
1540     setLibcallName(RTLIB::SRL_I128, nullptr);
1541     setLibcallName(RTLIB::SRA_I128, nullptr);
1542   }
1543
1544   // Combine sin / cos into one node or libcall if possible.
1545   if (Subtarget->hasSinCos()) {
1546     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1547     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1548     if (Subtarget->isTargetDarwin()) {
1549       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1550       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1551       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1552       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1553     }
1554   }
1555
1556   if (Subtarget->isTargetWin64()) {
1557     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1558     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1559     setOperationAction(ISD::SREM, MVT::i128, Custom);
1560     setOperationAction(ISD::UREM, MVT::i128, Custom);
1561     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1562     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1563   }
1564
1565   // We have target-specific dag combine patterns for the following nodes:
1566   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1567   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1568   setTargetDAGCombine(ISD::BITCAST);
1569   setTargetDAGCombine(ISD::VSELECT);
1570   setTargetDAGCombine(ISD::SELECT);
1571   setTargetDAGCombine(ISD::SHL);
1572   setTargetDAGCombine(ISD::SRA);
1573   setTargetDAGCombine(ISD::SRL);
1574   setTargetDAGCombine(ISD::OR);
1575   setTargetDAGCombine(ISD::AND);
1576   setTargetDAGCombine(ISD::ADD);
1577   setTargetDAGCombine(ISD::FADD);
1578   setTargetDAGCombine(ISD::FSUB);
1579   setTargetDAGCombine(ISD::FMA);
1580   setTargetDAGCombine(ISD::SUB);
1581   setTargetDAGCombine(ISD::LOAD);
1582   setTargetDAGCombine(ISD::MLOAD);
1583   setTargetDAGCombine(ISD::STORE);
1584   setTargetDAGCombine(ISD::MSTORE);
1585   setTargetDAGCombine(ISD::ZERO_EXTEND);
1586   setTargetDAGCombine(ISD::ANY_EXTEND);
1587   setTargetDAGCombine(ISD::SIGN_EXTEND);
1588   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1589   setTargetDAGCombine(ISD::TRUNCATE);
1590   setTargetDAGCombine(ISD::SINT_TO_FP);
1591   setTargetDAGCombine(ISD::SETCC);
1592   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1593   setTargetDAGCombine(ISD::BUILD_VECTOR);
1594   setTargetDAGCombine(ISD::MUL);
1595   setTargetDAGCombine(ISD::XOR);
1596
1597   computeRegisterProperties(Subtarget->getRegisterInfo());
1598
1599   // On Darwin, -Os means optimize for size without hurting performance,
1600   // do not reduce the limit.
1601   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1602   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1603   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1604   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1605   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1606   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1607   setPrefLoopAlignment(4); // 2^4 bytes.
1608
1609   // Predictable cmov don't hurt on atom because it's in-order.
1610   PredictableSelectIsExpensive = !Subtarget->isAtom();
1611   EnableExtLdPromotion = true;
1612   setPrefFunctionAlignment(4); // 2^4 bytes.
1613
1614   verifyIntrinsicTables();
1615 }
1616
1617 // This has so far only been implemented for 64-bit MachO.
1618 bool X86TargetLowering::useLoadStackGuardNode() const {
1619   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1620 }
1621
1622 TargetLoweringBase::LegalizeTypeAction
1623 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1624   if (ExperimentalVectorWideningLegalization &&
1625       VT.getVectorNumElements() != 1 &&
1626       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1627     return TypeWidenVector;
1628
1629   return TargetLoweringBase::getPreferredVectorAction(VT);
1630 }
1631
1632 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1633   if (!VT.isVector())
1634     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1635
1636   const unsigned NumElts = VT.getVectorNumElements();
1637   const EVT EltVT = VT.getVectorElementType();
1638   if (VT.is512BitVector()) {
1639     if (Subtarget->hasAVX512())
1640       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1641           EltVT == MVT::f32 || EltVT == MVT::f64)
1642         switch(NumElts) {
1643         case  8: return MVT::v8i1;
1644         case 16: return MVT::v16i1;
1645       }
1646     if (Subtarget->hasBWI())
1647       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1648         switch(NumElts) {
1649         case 32: return MVT::v32i1;
1650         case 64: return MVT::v64i1;
1651       }
1652   }
1653
1654   if (VT.is256BitVector() || VT.is128BitVector()) {
1655     if (Subtarget->hasVLX())
1656       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1657           EltVT == MVT::f32 || EltVT == MVT::f64)
1658         switch(NumElts) {
1659         case 2: return MVT::v2i1;
1660         case 4: return MVT::v4i1;
1661         case 8: return MVT::v8i1;
1662       }
1663     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1664       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1665         switch(NumElts) {
1666         case  8: return MVT::v8i1;
1667         case 16: return MVT::v16i1;
1668         case 32: return MVT::v32i1;
1669       }
1670   }
1671
1672   return VT.changeVectorElementTypeToInteger();
1673 }
1674
1675 /// Helper for getByValTypeAlignment to determine
1676 /// the desired ByVal argument alignment.
1677 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1678   if (MaxAlign == 16)
1679     return;
1680   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1681     if (VTy->getBitWidth() == 128)
1682       MaxAlign = 16;
1683   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1684     unsigned EltAlign = 0;
1685     getMaxByValAlign(ATy->getElementType(), EltAlign);
1686     if (EltAlign > MaxAlign)
1687       MaxAlign = EltAlign;
1688   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1689     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1690       unsigned EltAlign = 0;
1691       getMaxByValAlign(STy->getElementType(i), EltAlign);
1692       if (EltAlign > MaxAlign)
1693         MaxAlign = EltAlign;
1694       if (MaxAlign == 16)
1695         break;
1696     }
1697   }
1698 }
1699
1700 /// Return the desired alignment for ByVal aggregate
1701 /// function arguments in the caller parameter area. For X86, aggregates
1702 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1703 /// are at 4-byte boundaries.
1704 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1705   if (Subtarget->is64Bit()) {
1706     // Max of 8 and alignment of type.
1707     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1708     if (TyAlign > 8)
1709       return TyAlign;
1710     return 8;
1711   }
1712
1713   unsigned Align = 4;
1714   if (Subtarget->hasSSE1())
1715     getMaxByValAlign(Ty, Align);
1716   return Align;
1717 }
1718
1719 /// Returns the target specific optimal type for load
1720 /// and store operations as a result of memset, memcpy, and memmove
1721 /// lowering. If DstAlign is zero that means it's safe to destination
1722 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1723 /// means there isn't a need to check it against alignment requirement,
1724 /// probably because the source does not need to be loaded. If 'IsMemset' is
1725 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1726 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1727 /// source is constant so it does not need to be loaded.
1728 /// It returns EVT::Other if the type should be determined using generic
1729 /// target-independent logic.
1730 EVT
1731 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1732                                        unsigned DstAlign, unsigned SrcAlign,
1733                                        bool IsMemset, bool ZeroMemset,
1734                                        bool MemcpyStrSrc,
1735                                        MachineFunction &MF) const {
1736   const Function *F = MF.getFunction();
1737   if ((!IsMemset || ZeroMemset) &&
1738       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1739     if (Size >= 16 &&
1740         (Subtarget->isUnalignedMemAccessFast() ||
1741          ((DstAlign == 0 || DstAlign >= 16) &&
1742           (SrcAlign == 0 || SrcAlign >= 16)))) {
1743       if (Size >= 32) {
1744         if (Subtarget->hasInt256())
1745           return MVT::v8i32;
1746         if (Subtarget->hasFp256())
1747           return MVT::v8f32;
1748       }
1749       if (Subtarget->hasSSE2())
1750         return MVT::v4i32;
1751       if (Subtarget->hasSSE1())
1752         return MVT::v4f32;
1753     } else if (!MemcpyStrSrc && Size >= 8 &&
1754                !Subtarget->is64Bit() &&
1755                Subtarget->hasSSE2()) {
1756       // Do not use f64 to lower memcpy if source is string constant. It's
1757       // better to use i32 to avoid the loads.
1758       return MVT::f64;
1759     }
1760   }
1761   if (Subtarget->is64Bit() && Size >= 8)
1762     return MVT::i64;
1763   return MVT::i32;
1764 }
1765
1766 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1767   if (VT == MVT::f32)
1768     return X86ScalarSSEf32;
1769   else if (VT == MVT::f64)
1770     return X86ScalarSSEf64;
1771   return true;
1772 }
1773
1774 bool
1775 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1776                                                   unsigned,
1777                                                   unsigned,
1778                                                   bool *Fast) const {
1779   if (Fast)
1780     *Fast = Subtarget->isUnalignedMemAccessFast();
1781   return true;
1782 }
1783
1784 /// Return the entry encoding for a jump table in the
1785 /// current function.  The returned value is a member of the
1786 /// MachineJumpTableInfo::JTEntryKind enum.
1787 unsigned X86TargetLowering::getJumpTableEncoding() const {
1788   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1789   // symbol.
1790   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1791       Subtarget->isPICStyleGOT())
1792     return MachineJumpTableInfo::EK_Custom32;
1793
1794   // Otherwise, use the normal jump table encoding heuristics.
1795   return TargetLowering::getJumpTableEncoding();
1796 }
1797
1798 bool X86TargetLowering::useSoftFloat() const {
1799   return Subtarget->useSoftFloat();
1800 }
1801
1802 const MCExpr *
1803 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1804                                              const MachineBasicBlock *MBB,
1805                                              unsigned uid,MCContext &Ctx) const{
1806   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1807          Subtarget->isPICStyleGOT());
1808   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1809   // entries.
1810   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1811                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1812 }
1813
1814 /// Returns relocation base for the given PIC jumptable.
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816                                                     SelectionDAG &DAG) const {
1817   if (!Subtarget->is64Bit())
1818     // This doesn't have SDLoc associated with it, but is not really the
1819     // same as a Register.
1820     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1821   return Table;
1822 }
1823
1824 /// This returns the relocation base for the given PIC jumptable,
1825 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1826 const MCExpr *X86TargetLowering::
1827 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1828                              MCContext &Ctx) const {
1829   // X86-64 uses RIP relative addressing based on the jump table label.
1830   if (Subtarget->isPICStyleRIPRel())
1831     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1832
1833   // Otherwise, the reference is relative to the PIC base.
1834   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1835 }
1836
1837 std::pair<const TargetRegisterClass *, uint8_t>
1838 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1839                                            MVT VT) const {
1840   const TargetRegisterClass *RRC = nullptr;
1841   uint8_t Cost = 1;
1842   switch (VT.SimpleTy) {
1843   default:
1844     return TargetLowering::findRepresentativeClass(TRI, VT);
1845   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1846     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1847     break;
1848   case MVT::x86mmx:
1849     RRC = &X86::VR64RegClass;
1850     break;
1851   case MVT::f32: case MVT::f64:
1852   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1853   case MVT::v4f32: case MVT::v2f64:
1854   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1855   case MVT::v4f64:
1856     RRC = &X86::VR128RegClass;
1857     break;
1858   }
1859   return std::make_pair(RRC, Cost);
1860 }
1861
1862 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1863                                                unsigned &Offset) const {
1864   if (!Subtarget->isTargetLinux())
1865     return false;
1866
1867   if (Subtarget->is64Bit()) {
1868     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1869     Offset = 0x28;
1870     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1871       AddressSpace = 256;
1872     else
1873       AddressSpace = 257;
1874   } else {
1875     // %gs:0x14 on i386
1876     Offset = 0x14;
1877     AddressSpace = 256;
1878   }
1879   return true;
1880 }
1881
1882 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1883                                             unsigned DestAS) const {
1884   assert(SrcAS != DestAS && "Expected different address spaces!");
1885
1886   return SrcAS < 256 && DestAS < 256;
1887 }
1888
1889 //===----------------------------------------------------------------------===//
1890 //               Return Value Calling Convention Implementation
1891 //===----------------------------------------------------------------------===//
1892
1893 #include "X86GenCallingConv.inc"
1894
1895 bool
1896 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1897                                   MachineFunction &MF, bool isVarArg,
1898                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1899                         LLVMContext &Context) const {
1900   SmallVector<CCValAssign, 16> RVLocs;
1901   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1902   return CCInfo.CheckReturn(Outs, RetCC_X86);
1903 }
1904
1905 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1906   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1907   return ScratchRegs;
1908 }
1909
1910 SDValue
1911 X86TargetLowering::LowerReturn(SDValue Chain,
1912                                CallingConv::ID CallConv, bool isVarArg,
1913                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1914                                const SmallVectorImpl<SDValue> &OutVals,
1915                                SDLoc dl, SelectionDAG &DAG) const {
1916   MachineFunction &MF = DAG.getMachineFunction();
1917   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1918
1919   SmallVector<CCValAssign, 16> RVLocs;
1920   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1921   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1922
1923   SDValue Flag;
1924   SmallVector<SDValue, 6> RetOps;
1925   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1926   // Operand #1 = Bytes To Pop
1927   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1928                    MVT::i16));
1929
1930   // Copy the result values into the output registers.
1931   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1932     CCValAssign &VA = RVLocs[i];
1933     assert(VA.isRegLoc() && "Can only return in registers!");
1934     SDValue ValToCopy = OutVals[i];
1935     EVT ValVT = ValToCopy.getValueType();
1936
1937     // Promote values to the appropriate types.
1938     if (VA.getLocInfo() == CCValAssign::SExt)
1939       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1940     else if (VA.getLocInfo() == CCValAssign::ZExt)
1941       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1942     else if (VA.getLocInfo() == CCValAssign::AExt) {
1943       if (ValVT.getScalarType() == MVT::i1)
1944         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945       else
1946         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     }   
1948     else if (VA.getLocInfo() == CCValAssign::BCvt)
1949       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1950
1951     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1952            "Unexpected FP-extend for return value.");
1953
1954     // If this is x86-64, and we disabled SSE, we can't return FP values,
1955     // or SSE or MMX vectors.
1956     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1957          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1958           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1959       report_fatal_error("SSE register return with SSE disabled");
1960     }
1961     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1962     // llvm-gcc has never done it right and no one has noticed, so this
1963     // should be OK for now.
1964     if (ValVT == MVT::f64 &&
1965         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1966       report_fatal_error("SSE2 register return with SSE2 disabled");
1967
1968     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1969     // the RET instruction and handled by the FP Stackifier.
1970     if (VA.getLocReg() == X86::FP0 ||
1971         VA.getLocReg() == X86::FP1) {
1972       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1973       // change the value to the FP stack register class.
1974       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1975         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1976       RetOps.push_back(ValToCopy);
1977       // Don't emit a copytoreg.
1978       continue;
1979     }
1980
1981     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1982     // which is returned in RAX / RDX.
1983     if (Subtarget->is64Bit()) {
1984       if (ValVT == MVT::x86mmx) {
1985         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1986           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1987           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1988                                   ValToCopy);
1989           // If we don't have SSE2 available, convert to v4f32 so the generated
1990           // register is legal.
1991           if (!Subtarget->hasSSE2())
1992             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1993         }
1994       }
1995     }
1996
1997     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1998     Flag = Chain.getValue(1);
1999     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2000   }
2001
2002   // The x86-64 ABIs require that for returning structs by value we copy
2003   // the sret argument into %rax/%eax (depending on ABI) for the return.
2004   // Win32 requires us to put the sret argument to %eax as well.
2005   // We saved the argument into a virtual register in the entry block,
2006   // so now we copy the value out and into %rax/%eax.
2007   //
2008   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2009   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2010   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2011   // either case FuncInfo->setSRetReturnReg() will have been called.
2012   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2013     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2014            "No need for an sret register");
2015     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2016
2017     unsigned RetValReg
2018         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019           X86::RAX : X86::EAX;
2020     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021     Flag = Chain.getValue(1);
2022
2023     // RAX/EAX now acts like a return value.
2024     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2025   }
2026
2027   RetOps[0] = Chain;  // Update chain.
2028
2029   // Add the flag if we have it.
2030   if (Flag.getNode())
2031     RetOps.push_back(Flag);
2032
2033   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2034 }
2035
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037   if (N->getNumValues() != 1)
2038     return false;
2039   if (!N->hasNUsesOfValue(1, 0))
2040     return false;
2041
2042   SDValue TCChain = Chain;
2043   SDNode *Copy = *N->use_begin();
2044   if (Copy->getOpcode() == ISD::CopyToReg) {
2045     // If the copy has a glue operand, we conservatively assume it isn't safe to
2046     // perform a tail call.
2047     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2048       return false;
2049     TCChain = Copy->getOperand(0);
2050   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2051     return false;
2052
2053   bool HasRet = false;
2054   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2055        UI != UE; ++UI) {
2056     if (UI->getOpcode() != X86ISD::RET_FLAG)
2057       return false;
2058     // If we are returning more than one value, we can definitely
2059     // not make a tail call see PR19530
2060     if (UI->getNumOperands() > 4)
2061       return false;
2062     if (UI->getNumOperands() == 4 &&
2063         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2064       return false;
2065     HasRet = true;
2066   }
2067
2068   if (!HasRet)
2069     return false;
2070
2071   Chain = TCChain;
2072   return true;
2073 }
2074
2075 EVT
2076 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2077                                             ISD::NodeType ExtendKind) const {
2078   MVT ReturnMVT;
2079   // TODO: Is this also valid on 32-bit?
2080   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2081     ReturnMVT = MVT::i8;
2082   else
2083     ReturnMVT = MVT::i32;
2084
2085   EVT MinVT = getRegisterType(Context, ReturnMVT);
2086   return VT.bitsLT(MinVT) ? MinVT : VT;
2087 }
2088
2089 /// Lower the result values of a call into the
2090 /// appropriate copies out of appropriate physical registers.
2091 ///
2092 SDValue
2093 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2094                                    CallingConv::ID CallConv, bool isVarArg,
2095                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2096                                    SDLoc dl, SelectionDAG &DAG,
2097                                    SmallVectorImpl<SDValue> &InVals) const {
2098
2099   // Assign locations to each value returned by this call.
2100   SmallVector<CCValAssign, 16> RVLocs;
2101   bool Is64Bit = Subtarget->is64Bit();
2102   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2103                  *DAG.getContext());
2104   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2105
2106   // Copy all of the result registers out of their specified physreg.
2107   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2108     CCValAssign &VA = RVLocs[i];
2109     EVT CopyVT = VA.getLocVT();
2110
2111     // If this is x86-64, and we disabled SSE, we can't return FP values
2112     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2113         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2114       report_fatal_error("SSE register return with SSE disabled");
2115     }
2116
2117     // If we prefer to use the value in xmm registers, copy it out as f80 and
2118     // use a truncate to move it from fp stack reg to xmm reg.
2119     bool RoundAfterCopy = false;
2120     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2121         isScalarFPTypeInSSEReg(VA.getValVT())) {
2122       CopyVT = MVT::f80;
2123       RoundAfterCopy = (CopyVT != VA.getLocVT());
2124     }
2125
2126     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2127                                CopyVT, InFlag).getValue(1);
2128     SDValue Val = Chain.getValue(0);
2129
2130     if (RoundAfterCopy)
2131       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2132                         // This truncation won't change the value.
2133                         DAG.getIntPtrConstant(1, dl));
2134
2135     InFlag = Chain.getValue(2);
2136     InVals.push_back(Val);
2137   }
2138
2139   return Chain;
2140 }
2141
2142 //===----------------------------------------------------------------------===//
2143 //                C & StdCall & Fast Calling Convention implementation
2144 //===----------------------------------------------------------------------===//
2145 //  StdCall calling convention seems to be standard for many Windows' API
2146 //  routines and around. It differs from C calling convention just a little:
2147 //  callee should clean up the stack, not caller. Symbols should be also
2148 //  decorated in some fancy way :) It doesn't support any vector arguments.
2149 //  For info on fast calling convention see Fast Calling Convention (tail call)
2150 //  implementation LowerX86_32FastCCCallTo.
2151
2152 /// CallIsStructReturn - Determines whether a call uses struct return
2153 /// semantics.
2154 enum StructReturnType {
2155   NotStructReturn,
2156   RegStructReturn,
2157   StackStructReturn
2158 };
2159 static StructReturnType
2160 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2161   if (Outs.empty())
2162     return NotStructReturn;
2163
2164   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2165   if (!Flags.isSRet())
2166     return NotStructReturn;
2167   if (Flags.isInReg())
2168     return RegStructReturn;
2169   return StackStructReturn;
2170 }
2171
2172 /// Determines whether a function uses struct return semantics.
2173 static StructReturnType
2174 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2175   if (Ins.empty())
2176     return NotStructReturn;
2177
2178   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2179   if (!Flags.isSRet())
2180     return NotStructReturn;
2181   if (Flags.isInReg())
2182     return RegStructReturn;
2183   return StackStructReturn;
2184 }
2185
2186 /// Make a copy of an aggregate at address specified by "Src" to address
2187 /// "Dst" with size and alignment information specified by the specific
2188 /// parameter attribute. The copy will be passed as a byval function parameter.
2189 static SDValue
2190 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2191                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2192                           SDLoc dl) {
2193   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2194
2195   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2196                        /*isVolatile*/false, /*AlwaysInline=*/true,
2197                        /*isTailCall*/false,
2198                        MachinePointerInfo(), MachinePointerInfo());
2199 }
2200
2201 /// Return true if the calling convention is one that
2202 /// supports tail call optimization.
2203 static bool IsTailCallConvention(CallingConv::ID CC) {
2204   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2205           CC == CallingConv::HiPE);
2206 }
2207
2208 /// \brief Return true if the calling convention is a C calling convention.
2209 static bool IsCCallConvention(CallingConv::ID CC) {
2210   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2211           CC == CallingConv::X86_64_SysV);
2212 }
2213
2214 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2215   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2216     return false;
2217
2218   CallSite CS(CI);
2219   CallingConv::ID CalleeCC = CS.getCallingConv();
2220   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2221     return false;
2222
2223   return true;
2224 }
2225
2226 /// Return true if the function is being made into
2227 /// a tailcall target by changing its ABI.
2228 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2229                                    bool GuaranteedTailCallOpt) {
2230   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2231 }
2232
2233 SDValue
2234 X86TargetLowering::LowerMemArgument(SDValue Chain,
2235                                     CallingConv::ID CallConv,
2236                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2237                                     SDLoc dl, SelectionDAG &DAG,
2238                                     const CCValAssign &VA,
2239                                     MachineFrameInfo *MFI,
2240                                     unsigned i) const {
2241   // Create the nodes corresponding to a load from this parameter slot.
2242   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2243   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2244       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2245   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2246   EVT ValVT;
2247
2248   // If value is passed by pointer we have address passed instead of the value
2249   // itself.
2250   if (VA.getLocInfo() == CCValAssign::Indirect)
2251     ValVT = VA.getLocVT();
2252   else
2253     ValVT = VA.getValVT();
2254
2255   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2256   // changed with more analysis.
2257   // In case of tail call optimization mark all arguments mutable. Since they
2258   // could be overwritten by lowering of arguments in case of a tail call.
2259   if (Flags.isByVal()) {
2260     unsigned Bytes = Flags.getByValSize();
2261     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2262     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2263     return DAG.getFrameIndex(FI, getPointerTy());
2264   } else {
2265     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2266                                     VA.getLocMemOffset(), isImmutable);
2267     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2268     return DAG.getLoad(ValVT, dl, Chain, FIN,
2269                        MachinePointerInfo::getFixedStack(FI),
2270                        false, false, false, 0);
2271   }
2272 }
2273
2274 // FIXME: Get this from tablegen.
2275 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2276                                                 const X86Subtarget *Subtarget) {
2277   assert(Subtarget->is64Bit());
2278
2279   if (Subtarget->isCallingConvWin64(CallConv)) {
2280     static const MCPhysReg GPR64ArgRegsWin64[] = {
2281       X86::RCX, X86::RDX, X86::R8,  X86::R9
2282     };
2283     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2284   }
2285
2286   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2287     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2288   };
2289   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2290 }
2291
2292 // FIXME: Get this from tablegen.
2293 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2294                                                 CallingConv::ID CallConv,
2295                                                 const X86Subtarget *Subtarget) {
2296   assert(Subtarget->is64Bit());
2297   if (Subtarget->isCallingConvWin64(CallConv)) {
2298     // The XMM registers which might contain var arg parameters are shadowed
2299     // in their paired GPR.  So we only need to save the GPR to their home
2300     // slots.
2301     // TODO: __vectorcall will change this.
2302     return None;
2303   }
2304
2305   const Function *Fn = MF.getFunction();
2306   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2307   bool isSoftFloat = Subtarget->useSoftFloat();
2308   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2309          "SSE register cannot be used when SSE is disabled!");
2310   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2311     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2312     // registers.
2313     return None;
2314
2315   static const MCPhysReg XMMArgRegs64Bit[] = {
2316     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2317     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2318   };
2319   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2320 }
2321
2322 SDValue
2323 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2324                                         CallingConv::ID CallConv,
2325                                         bool isVarArg,
2326                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2327                                         SDLoc dl,
2328                                         SelectionDAG &DAG,
2329                                         SmallVectorImpl<SDValue> &InVals)
2330                                           const {
2331   MachineFunction &MF = DAG.getMachineFunction();
2332   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2333   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2334
2335   const Function* Fn = MF.getFunction();
2336   if (Fn->hasExternalLinkage() &&
2337       Subtarget->isTargetCygMing() &&
2338       Fn->getName() == "main")
2339     FuncInfo->setForceFramePointer(true);
2340
2341   MachineFrameInfo *MFI = MF.getFrameInfo();
2342   bool Is64Bit = Subtarget->is64Bit();
2343   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2344
2345   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2346          "Var args not supported with calling convention fastcc, ghc or hipe");
2347
2348   // Assign locations to all of the incoming arguments.
2349   SmallVector<CCValAssign, 16> ArgLocs;
2350   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2351
2352   // Allocate shadow area for Win64
2353   if (IsWin64)
2354     CCInfo.AllocateStack(32, 8);
2355
2356   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2357
2358   unsigned LastVal = ~0U;
2359   SDValue ArgValue;
2360   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2361     CCValAssign &VA = ArgLocs[i];
2362     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2363     // places.
2364     assert(VA.getValNo() != LastVal &&
2365            "Don't support value assigned to multiple locs yet");
2366     (void)LastVal;
2367     LastVal = VA.getValNo();
2368
2369     if (VA.isRegLoc()) {
2370       EVT RegVT = VA.getLocVT();
2371       const TargetRegisterClass *RC;
2372       if (RegVT == MVT::i32)
2373         RC = &X86::GR32RegClass;
2374       else if (Is64Bit && RegVT == MVT::i64)
2375         RC = &X86::GR64RegClass;
2376       else if (RegVT == MVT::f32)
2377         RC = &X86::FR32RegClass;
2378       else if (RegVT == MVT::f64)
2379         RC = &X86::FR64RegClass;
2380       else if (RegVT.is512BitVector())
2381         RC = &X86::VR512RegClass;
2382       else if (RegVT.is256BitVector())
2383         RC = &X86::VR256RegClass;
2384       else if (RegVT.is128BitVector())
2385         RC = &X86::VR128RegClass;
2386       else if (RegVT == MVT::x86mmx)
2387         RC = &X86::VR64RegClass;
2388       else if (RegVT == MVT::i1)
2389         RC = &X86::VK1RegClass;
2390       else if (RegVT == MVT::v8i1)
2391         RC = &X86::VK8RegClass;
2392       else if (RegVT == MVT::v16i1)
2393         RC = &X86::VK16RegClass;
2394       else if (RegVT == MVT::v32i1)
2395         RC = &X86::VK32RegClass;
2396       else if (RegVT == MVT::v64i1)
2397         RC = &X86::VK64RegClass;
2398       else
2399         llvm_unreachable("Unknown argument type!");
2400
2401       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2402       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2403
2404       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2405       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2406       // right size.
2407       if (VA.getLocInfo() == CCValAssign::SExt)
2408         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2409                                DAG.getValueType(VA.getValVT()));
2410       else if (VA.getLocInfo() == CCValAssign::ZExt)
2411         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2412                                DAG.getValueType(VA.getValVT()));
2413       else if (VA.getLocInfo() == CCValAssign::BCvt)
2414         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2415
2416       if (VA.isExtInLoc()) {
2417         // Handle MMX values passed in XMM regs.
2418         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2419           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2420         else
2421           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2422       }
2423     } else {
2424       assert(VA.isMemLoc());
2425       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2426     }
2427
2428     // If value is passed via pointer - do a load.
2429     if (VA.getLocInfo() == CCValAssign::Indirect)
2430       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2431                              MachinePointerInfo(), false, false, false, 0);
2432
2433     InVals.push_back(ArgValue);
2434   }
2435
2436   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2437     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2438       // The x86-64 ABIs require that for returning structs by value we copy
2439       // the sret argument into %rax/%eax (depending on ABI) for the return.
2440       // Win32 requires us to put the sret argument to %eax as well.
2441       // Save the argument into a virtual register so that we can access it
2442       // from the return points.
2443       if (Ins[i].Flags.isSRet()) {
2444         unsigned Reg = FuncInfo->getSRetReturnReg();
2445         if (!Reg) {
2446           MVT PtrTy = getPointerTy();
2447           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2448           FuncInfo->setSRetReturnReg(Reg);
2449         }
2450         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2451         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2452         break;
2453       }
2454     }
2455   }
2456
2457   unsigned StackSize = CCInfo.getNextStackOffset();
2458   // Align stack specially for tail calls.
2459   if (FuncIsMadeTailCallSafe(CallConv,
2460                              MF.getTarget().Options.GuaranteedTailCallOpt))
2461     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2462
2463   // If the function takes variable number of arguments, make a frame index for
2464   // the start of the first vararg value... for expansion of llvm.va_start. We
2465   // can skip this if there are no va_start calls.
2466   if (MFI->hasVAStart() &&
2467       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2468                    CallConv != CallingConv::X86_ThisCall))) {
2469     FuncInfo->setVarArgsFrameIndex(
2470         MFI->CreateFixedObject(1, StackSize, true));
2471   }
2472
2473   MachineModuleInfo &MMI = MF.getMMI();
2474   const Function *WinEHParent = nullptr;
2475   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2476     WinEHParent = MMI.getWinEHParent(Fn);
2477   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2478   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2479
2480   // Figure out if XMM registers are in use.
2481   assert(!(Subtarget->useSoftFloat() &&
2482            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2483          "SSE register cannot be used when SSE is disabled!");
2484
2485   // 64-bit calling conventions support varargs and register parameters, so we
2486   // have to do extra work to spill them in the prologue.
2487   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2488     // Find the first unallocated argument registers.
2489     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2490     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2491     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2492     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2493     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2494            "SSE register cannot be used when SSE is disabled!");
2495
2496     // Gather all the live in physical registers.
2497     SmallVector<SDValue, 6> LiveGPRs;
2498     SmallVector<SDValue, 8> LiveXMMRegs;
2499     SDValue ALVal;
2500     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2501       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2502       LiveGPRs.push_back(
2503           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2504     }
2505     if (!ArgXMMs.empty()) {
2506       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2507       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2508       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2509         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2510         LiveXMMRegs.push_back(
2511             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2512       }
2513     }
2514
2515     if (IsWin64) {
2516       // Get to the caller-allocated home save location.  Add 8 to account
2517       // for the return address.
2518       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2519       FuncInfo->setRegSaveFrameIndex(
2520           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2521       // Fixup to set vararg frame on shadow area (4 x i64).
2522       if (NumIntRegs < 4)
2523         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2524     } else {
2525       // For X86-64, if there are vararg parameters that are passed via
2526       // registers, then we must store them to their spots on the stack so
2527       // they may be loaded by deferencing the result of va_next.
2528       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2529       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2530       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2531           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2532     }
2533
2534     // Store the integer parameter registers.
2535     SmallVector<SDValue, 8> MemOps;
2536     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2537                                       getPointerTy());
2538     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2539     for (SDValue Val : LiveGPRs) {
2540       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2541                                 DAG.getIntPtrConstant(Offset, dl));
2542       SDValue Store =
2543         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2544                      MachinePointerInfo::getFixedStack(
2545                        FuncInfo->getRegSaveFrameIndex(), Offset),
2546                      false, false, 0);
2547       MemOps.push_back(Store);
2548       Offset += 8;
2549     }
2550
2551     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2552       // Now store the XMM (fp + vector) parameter registers.
2553       SmallVector<SDValue, 12> SaveXMMOps;
2554       SaveXMMOps.push_back(Chain);
2555       SaveXMMOps.push_back(ALVal);
2556       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2557                              FuncInfo->getRegSaveFrameIndex(), dl));
2558       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2559                              FuncInfo->getVarArgsFPOffset(), dl));
2560       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2561                         LiveXMMRegs.end());
2562       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2563                                    MVT::Other, SaveXMMOps));
2564     }
2565
2566     if (!MemOps.empty())
2567       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2568   } else if (IsWinEHOutlined) {
2569     // Get to the caller-allocated home save location.  Add 8 to account
2570     // for the return address.
2571     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2572     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2573         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2574
2575     MMI.getWinEHFuncInfo(Fn)
2576         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2577         FuncInfo->getRegSaveFrameIndex();
2578
2579     // Store the second integer parameter (rdx) into rsp+16 relative to the
2580     // stack pointer at the entry of the function.
2581     SDValue RSFIN =
2582         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2583     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2584     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2585     Chain = DAG.getStore(
2586         Val.getValue(1), dl, Val, RSFIN,
2587         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2588         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2589   }
2590
2591   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2592     // Find the largest legal vector type.
2593     MVT VecVT = MVT::Other;
2594     // FIXME: Only some x86_32 calling conventions support AVX512.
2595     if (Subtarget->hasAVX512() &&
2596         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2597                      CallConv == CallingConv::Intel_OCL_BI)))
2598       VecVT = MVT::v16f32;
2599     else if (Subtarget->hasAVX())
2600       VecVT = MVT::v8f32;
2601     else if (Subtarget->hasSSE2())
2602       VecVT = MVT::v4f32;
2603
2604     // We forward some GPRs and some vector types.
2605     SmallVector<MVT, 2> RegParmTypes;
2606     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2607     RegParmTypes.push_back(IntVT);
2608     if (VecVT != MVT::Other)
2609       RegParmTypes.push_back(VecVT);
2610
2611     // Compute the set of forwarded registers. The rest are scratch.
2612     SmallVectorImpl<ForwardedRegister> &Forwards =
2613         FuncInfo->getForwardedMustTailRegParms();
2614     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2615
2616     // Conservatively forward AL on x86_64, since it might be used for varargs.
2617     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2618       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2619       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2620     }
2621
2622     // Copy all forwards from physical to virtual registers.
2623     for (ForwardedRegister &F : Forwards) {
2624       // FIXME: Can we use a less constrained schedule?
2625       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2626       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2627       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2628     }
2629   }
2630
2631   // Some CCs need callee pop.
2632   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2633                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2634     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2635   } else {
2636     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2637     // If this is an sret function, the return should pop the hidden pointer.
2638     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2639         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2640         argsAreStructReturn(Ins) == StackStructReturn)
2641       FuncInfo->setBytesToPopOnReturn(4);
2642   }
2643
2644   if (!Is64Bit) {
2645     // RegSaveFrameIndex is X86-64 only.
2646     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2647     if (CallConv == CallingConv::X86_FastCall ||
2648         CallConv == CallingConv::X86_ThisCall)
2649       // fastcc functions can't have varargs.
2650       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2651   }
2652
2653   FuncInfo->setArgumentStackSize(StackSize);
2654
2655   if (IsWinEHParent) {
2656     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2657     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2658     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2659     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2660     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2661                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2662                          /*isVolatile=*/true,
2663                          /*isNonTemporal=*/false, /*Alignment=*/0);
2664   }
2665
2666   return Chain;
2667 }
2668
2669 SDValue
2670 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2671                                     SDValue StackPtr, SDValue Arg,
2672                                     SDLoc dl, SelectionDAG &DAG,
2673                                     const CCValAssign &VA,
2674                                     ISD::ArgFlagsTy Flags) const {
2675   unsigned LocMemOffset = VA.getLocMemOffset();
2676   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2677   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2678   if (Flags.isByVal())
2679     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2680
2681   return DAG.getStore(Chain, dl, Arg, PtrOff,
2682                       MachinePointerInfo::getStack(LocMemOffset),
2683                       false, false, 0);
2684 }
2685
2686 /// Emit a load of return address if tail call
2687 /// optimization is performed and it is required.
2688 SDValue
2689 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2690                                            SDValue &OutRetAddr, SDValue Chain,
2691                                            bool IsTailCall, bool Is64Bit,
2692                                            int FPDiff, SDLoc dl) const {
2693   // Adjust the Return address stack slot.
2694   EVT VT = getPointerTy();
2695   OutRetAddr = getReturnAddressFrameIndex(DAG);
2696
2697   // Load the "old" Return address.
2698   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2699                            false, false, false, 0);
2700   return SDValue(OutRetAddr.getNode(), 1);
2701 }
2702
2703 /// Emit a store of the return address if tail call
2704 /// optimization is performed and it is required (FPDiff!=0).
2705 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2706                                         SDValue Chain, SDValue RetAddrFrIdx,
2707                                         EVT PtrVT, unsigned SlotSize,
2708                                         int FPDiff, SDLoc dl) {
2709   // Store the return address to the appropriate stack slot.
2710   if (!FPDiff) return Chain;
2711   // Calculate the new stack slot for the return address.
2712   int NewReturnAddrFI =
2713     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2714                                          false);
2715   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2716   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2717                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2718                        false, false, 0);
2719   return Chain;
2720 }
2721
2722 SDValue
2723 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2724                              SmallVectorImpl<SDValue> &InVals) const {
2725   SelectionDAG &DAG                     = CLI.DAG;
2726   SDLoc &dl                             = CLI.DL;
2727   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2728   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2729   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2730   SDValue Chain                         = CLI.Chain;
2731   SDValue Callee                        = CLI.Callee;
2732   CallingConv::ID CallConv              = CLI.CallConv;
2733   bool &isTailCall                      = CLI.IsTailCall;
2734   bool isVarArg                         = CLI.IsVarArg;
2735
2736   MachineFunction &MF = DAG.getMachineFunction();
2737   bool Is64Bit        = Subtarget->is64Bit();
2738   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2739   StructReturnType SR = callIsStructReturn(Outs);
2740   bool IsSibcall      = false;
2741   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2742
2743   if (MF.getTarget().Options.DisableTailCalls)
2744     isTailCall = false;
2745
2746   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2747   if (IsMustTail) {
2748     // Force this to be a tail call.  The verifier rules are enough to ensure
2749     // that we can lower this successfully without moving the return address
2750     // around.
2751     isTailCall = true;
2752   } else if (isTailCall) {
2753     // Check if it's really possible to do a tail call.
2754     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2755                     isVarArg, SR != NotStructReturn,
2756                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2757                     Outs, OutVals, Ins, DAG);
2758
2759     // Sibcalls are automatically detected tailcalls which do not require
2760     // ABI changes.
2761     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2762       IsSibcall = true;
2763
2764     if (isTailCall)
2765       ++NumTailCalls;
2766   }
2767
2768   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2769          "Var args not supported with calling convention fastcc, ghc or hipe");
2770
2771   // Analyze operands of the call, assigning locations to each operand.
2772   SmallVector<CCValAssign, 16> ArgLocs;
2773   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2774
2775   // Allocate shadow area for Win64
2776   if (IsWin64)
2777     CCInfo.AllocateStack(32, 8);
2778
2779   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2780
2781   // Get a count of how many bytes are to be pushed on the stack.
2782   unsigned NumBytes = CCInfo.getNextStackOffset();
2783   if (IsSibcall)
2784     // This is a sibcall. The memory operands are available in caller's
2785     // own caller's stack.
2786     NumBytes = 0;
2787   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2788            IsTailCallConvention(CallConv))
2789     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2790
2791   int FPDiff = 0;
2792   if (isTailCall && !IsSibcall && !IsMustTail) {
2793     // Lower arguments at fp - stackoffset + fpdiff.
2794     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2795
2796     FPDiff = NumBytesCallerPushed - NumBytes;
2797
2798     // Set the delta of movement of the returnaddr stackslot.
2799     // But only set if delta is greater than previous delta.
2800     if (FPDiff < X86Info->getTCReturnAddrDelta())
2801       X86Info->setTCReturnAddrDelta(FPDiff);
2802   }
2803
2804   unsigned NumBytesToPush = NumBytes;
2805   unsigned NumBytesToPop = NumBytes;
2806
2807   // If we have an inalloca argument, all stack space has already been allocated
2808   // for us and be right at the top of the stack.  We don't support multiple
2809   // arguments passed in memory when using inalloca.
2810   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2811     NumBytesToPush = 0;
2812     if (!ArgLocs.back().isMemLoc())
2813       report_fatal_error("cannot use inalloca attribute on a register "
2814                          "parameter");
2815     if (ArgLocs.back().getLocMemOffset() != 0)
2816       report_fatal_error("any parameter with the inalloca attribute must be "
2817                          "the only memory argument");
2818   }
2819
2820   if (!IsSibcall)
2821     Chain = DAG.getCALLSEQ_START(
2822         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2823
2824   SDValue RetAddrFrIdx;
2825   // Load return address for tail calls.
2826   if (isTailCall && FPDiff)
2827     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2828                                     Is64Bit, FPDiff, dl);
2829
2830   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2831   SmallVector<SDValue, 8> MemOpChains;
2832   SDValue StackPtr;
2833
2834   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2835   // of tail call optimization arguments are handle later.
2836   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2837   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2838     // Skip inalloca arguments, they have already been written.
2839     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2840     if (Flags.isInAlloca())
2841       continue;
2842
2843     CCValAssign &VA = ArgLocs[i];
2844     EVT RegVT = VA.getLocVT();
2845     SDValue Arg = OutVals[i];
2846     bool isByVal = Flags.isByVal();
2847
2848     // Promote the value if needed.
2849     switch (VA.getLocInfo()) {
2850     default: llvm_unreachable("Unknown loc info!");
2851     case CCValAssign::Full: break;
2852     case CCValAssign::SExt:
2853       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2854       break;
2855     case CCValAssign::ZExt:
2856       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2857       break;
2858     case CCValAssign::AExt:
2859       if (Arg.getValueType().getScalarType() == MVT::i1)
2860         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2861       else if (RegVT.is128BitVector()) {
2862         // Special case: passing MMX values in XMM registers.
2863         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2864         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2865         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2866       } else
2867         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2868       break;
2869     case CCValAssign::BCvt:
2870       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2871       break;
2872     case CCValAssign::Indirect: {
2873       // Store the argument.
2874       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2875       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2876       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2877                            MachinePointerInfo::getFixedStack(FI),
2878                            false, false, 0);
2879       Arg = SpillSlot;
2880       break;
2881     }
2882     }
2883
2884     if (VA.isRegLoc()) {
2885       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2886       if (isVarArg && IsWin64) {
2887         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2888         // shadow reg if callee is a varargs function.
2889         unsigned ShadowReg = 0;
2890         switch (VA.getLocReg()) {
2891         case X86::XMM0: ShadowReg = X86::RCX; break;
2892         case X86::XMM1: ShadowReg = X86::RDX; break;
2893         case X86::XMM2: ShadowReg = X86::R8; break;
2894         case X86::XMM3: ShadowReg = X86::R9; break;
2895         }
2896         if (ShadowReg)
2897           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2898       }
2899     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2900       assert(VA.isMemLoc());
2901       if (!StackPtr.getNode())
2902         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2903                                       getPointerTy());
2904       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2905                                              dl, DAG, VA, Flags));
2906     }
2907   }
2908
2909   if (!MemOpChains.empty())
2910     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2911
2912   if (Subtarget->isPICStyleGOT()) {
2913     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2914     // GOT pointer.
2915     if (!isTailCall) {
2916       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2917                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2918     } else {
2919       // If we are tail calling and generating PIC/GOT style code load the
2920       // address of the callee into ECX. The value in ecx is used as target of
2921       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2922       // for tail calls on PIC/GOT architectures. Normally we would just put the
2923       // address of GOT into ebx and then call target@PLT. But for tail calls
2924       // ebx would be restored (since ebx is callee saved) before jumping to the
2925       // target@PLT.
2926
2927       // Note: The actual moving to ECX is done further down.
2928       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2929       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2930           !G->getGlobal()->hasProtectedVisibility())
2931         Callee = LowerGlobalAddress(Callee, DAG);
2932       else if (isa<ExternalSymbolSDNode>(Callee))
2933         Callee = LowerExternalSymbol(Callee, DAG);
2934     }
2935   }
2936
2937   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2938     // From AMD64 ABI document:
2939     // For calls that may call functions that use varargs or stdargs
2940     // (prototype-less calls or calls to functions containing ellipsis (...) in
2941     // the declaration) %al is used as hidden argument to specify the number
2942     // of SSE registers used. The contents of %al do not need to match exactly
2943     // the number of registers, but must be an ubound on the number of SSE
2944     // registers used and is in the range 0 - 8 inclusive.
2945
2946     // Count the number of XMM registers allocated.
2947     static const MCPhysReg XMMArgRegs[] = {
2948       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2949       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2950     };
2951     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2952     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2953            && "SSE registers cannot be used when SSE is disabled");
2954
2955     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2956                                         DAG.getConstant(NumXMMRegs, dl,
2957                                                         MVT::i8)));
2958   }
2959
2960   if (isVarArg && IsMustTail) {
2961     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2962     for (const auto &F : Forwards) {
2963       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2964       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2965     }
2966   }
2967
2968   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2969   // don't need this because the eligibility check rejects calls that require
2970   // shuffling arguments passed in memory.
2971   if (!IsSibcall && isTailCall) {
2972     // Force all the incoming stack arguments to be loaded from the stack
2973     // before any new outgoing arguments are stored to the stack, because the
2974     // outgoing stack slots may alias the incoming argument stack slots, and
2975     // the alias isn't otherwise explicit. This is slightly more conservative
2976     // than necessary, because it means that each store effectively depends
2977     // on every argument instead of just those arguments it would clobber.
2978     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2979
2980     SmallVector<SDValue, 8> MemOpChains2;
2981     SDValue FIN;
2982     int FI = 0;
2983     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2984       CCValAssign &VA = ArgLocs[i];
2985       if (VA.isRegLoc())
2986         continue;
2987       assert(VA.isMemLoc());
2988       SDValue Arg = OutVals[i];
2989       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2990       // Skip inalloca arguments.  They don't require any work.
2991       if (Flags.isInAlloca())
2992         continue;
2993       // Create frame index.
2994       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2995       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2996       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2997       FIN = DAG.getFrameIndex(FI, getPointerTy());
2998
2999       if (Flags.isByVal()) {
3000         // Copy relative to framepointer.
3001         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3002         if (!StackPtr.getNode())
3003           StackPtr = DAG.getCopyFromReg(Chain, dl,
3004                                         RegInfo->getStackRegister(),
3005                                         getPointerTy());
3006         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3007
3008         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3009                                                          ArgChain,
3010                                                          Flags, DAG, dl));
3011       } else {
3012         // Store relative to framepointer.
3013         MemOpChains2.push_back(
3014           DAG.getStore(ArgChain, dl, Arg, FIN,
3015                        MachinePointerInfo::getFixedStack(FI),
3016                        false, false, 0));
3017       }
3018     }
3019
3020     if (!MemOpChains2.empty())
3021       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3022
3023     // Store the return address to the appropriate stack slot.
3024     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3025                                      getPointerTy(), RegInfo->getSlotSize(),
3026                                      FPDiff, dl);
3027   }
3028
3029   // Build a sequence of copy-to-reg nodes chained together with token chain
3030   // and flag operands which copy the outgoing args into registers.
3031   SDValue InFlag;
3032   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3033     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3034                              RegsToPass[i].second, InFlag);
3035     InFlag = Chain.getValue(1);
3036   }
3037
3038   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3039     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3040     // In the 64-bit large code model, we have to make all calls
3041     // through a register, since the call instruction's 32-bit
3042     // pc-relative offset may not be large enough to hold the whole
3043     // address.
3044   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3045     // If the callee is a GlobalAddress node (quite common, every direct call
3046     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3047     // it.
3048     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3049
3050     // We should use extra load for direct calls to dllimported functions in
3051     // non-JIT mode.
3052     const GlobalValue *GV = G->getGlobal();
3053     if (!GV->hasDLLImportStorageClass()) {
3054       unsigned char OpFlags = 0;
3055       bool ExtraLoad = false;
3056       unsigned WrapperKind = ISD::DELETED_NODE;
3057
3058       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3059       // external symbols most go through the PLT in PIC mode.  If the symbol
3060       // has hidden or protected visibility, or if it is static or local, then
3061       // we don't need to use the PLT - we can directly call it.
3062       if (Subtarget->isTargetELF() &&
3063           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3064           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3065         OpFlags = X86II::MO_PLT;
3066       } else if (Subtarget->isPICStyleStubAny() &&
3067                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3068                  (!Subtarget->getTargetTriple().isMacOSX() ||
3069                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3070         // PC-relative references to external symbols should go through $stub,
3071         // unless we're building with the leopard linker or later, which
3072         // automatically synthesizes these stubs.
3073         OpFlags = X86II::MO_DARWIN_STUB;
3074       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3075                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3076         // If the function is marked as non-lazy, generate an indirect call
3077         // which loads from the GOT directly. This avoids runtime overhead
3078         // at the cost of eager binding (and one extra byte of encoding).
3079         OpFlags = X86II::MO_GOTPCREL;
3080         WrapperKind = X86ISD::WrapperRIP;
3081         ExtraLoad = true;
3082       }
3083
3084       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3085                                           G->getOffset(), OpFlags);
3086
3087       // Add a wrapper if needed.
3088       if (WrapperKind != ISD::DELETED_NODE)
3089         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3090       // Add extra indirection if needed.
3091       if (ExtraLoad)
3092         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3093                              MachinePointerInfo::getGOT(),
3094                              false, false, false, 0);
3095     }
3096   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3097     unsigned char OpFlags = 0;
3098
3099     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3100     // external symbols should go through the PLT.
3101     if (Subtarget->isTargetELF() &&
3102         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3103       OpFlags = X86II::MO_PLT;
3104     } else if (Subtarget->isPICStyleStubAny() &&
3105                (!Subtarget->getTargetTriple().isMacOSX() ||
3106                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3107       // PC-relative references to external symbols should go through $stub,
3108       // unless we're building with the leopard linker or later, which
3109       // automatically synthesizes these stubs.
3110       OpFlags = X86II::MO_DARWIN_STUB;
3111     }
3112
3113     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3114                                          OpFlags);
3115   } else if (Subtarget->isTarget64BitILP32() &&
3116              Callee->getValueType(0) == MVT::i32) {
3117     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3118     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3119   }
3120
3121   // Returns a chain & a flag for retval copy to use.
3122   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3123   SmallVector<SDValue, 8> Ops;
3124
3125   if (!IsSibcall && isTailCall) {
3126     Chain = DAG.getCALLSEQ_END(Chain,
3127                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3128                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3129     InFlag = Chain.getValue(1);
3130   }
3131
3132   Ops.push_back(Chain);
3133   Ops.push_back(Callee);
3134
3135   if (isTailCall)
3136     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3137
3138   // Add argument registers to the end of the list so that they are known live
3139   // into the call.
3140   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3141     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3142                                   RegsToPass[i].second.getValueType()));
3143
3144   // Add a register mask operand representing the call-preserved registers.
3145   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3146   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3147   assert(Mask && "Missing call preserved mask for calling convention");
3148   Ops.push_back(DAG.getRegisterMask(Mask));
3149
3150   if (InFlag.getNode())
3151     Ops.push_back(InFlag);
3152
3153   if (isTailCall) {
3154     // We used to do:
3155     //// If this is the first return lowered for this function, add the regs
3156     //// to the liveout set for the function.
3157     // This isn't right, although it's probably harmless on x86; liveouts
3158     // should be computed from returns not tail calls.  Consider a void
3159     // function making a tail call to a function returning int.
3160     MF.getFrameInfo()->setHasTailCall();
3161     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3162   }
3163
3164   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3165   InFlag = Chain.getValue(1);
3166
3167   // Create the CALLSEQ_END node.
3168   unsigned NumBytesForCalleeToPop;
3169   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3170                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3171     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3172   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3173            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3174            SR == StackStructReturn)
3175     // If this is a call to a struct-return function, the callee
3176     // pops the hidden struct pointer, so we have to push it back.
3177     // This is common for Darwin/X86, Linux & Mingw32 targets.
3178     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3179     NumBytesForCalleeToPop = 4;
3180   else
3181     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3182
3183   // Returns a flag for retval copy to use.
3184   if (!IsSibcall) {
3185     Chain = DAG.getCALLSEQ_END(Chain,
3186                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3187                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3188                                                      true),
3189                                InFlag, dl);
3190     InFlag = Chain.getValue(1);
3191   }
3192
3193   // Handle result values, copying them out of physregs into vregs that we
3194   // return.
3195   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3196                          Ins, dl, DAG, InVals);
3197 }
3198
3199 //===----------------------------------------------------------------------===//
3200 //                Fast Calling Convention (tail call) implementation
3201 //===----------------------------------------------------------------------===//
3202
3203 //  Like std call, callee cleans arguments, convention except that ECX is
3204 //  reserved for storing the tail called function address. Only 2 registers are
3205 //  free for argument passing (inreg). Tail call optimization is performed
3206 //  provided:
3207 //                * tailcallopt is enabled
3208 //                * caller/callee are fastcc
3209 //  On X86_64 architecture with GOT-style position independent code only local
3210 //  (within module) calls are supported at the moment.
3211 //  To keep the stack aligned according to platform abi the function
3212 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3213 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3214 //  If a tail called function callee has more arguments than the caller the
3215 //  caller needs to make sure that there is room to move the RETADDR to. This is
3216 //  achieved by reserving an area the size of the argument delta right after the
3217 //  original RETADDR, but before the saved framepointer or the spilled registers
3218 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3219 //  stack layout:
3220 //    arg1
3221 //    arg2
3222 //    RETADDR
3223 //    [ new RETADDR
3224 //      move area ]
3225 //    (possible EBP)
3226 //    ESI
3227 //    EDI
3228 //    local1 ..
3229
3230 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3231 /// for a 16 byte align requirement.
3232 unsigned
3233 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3234                                                SelectionDAG& DAG) const {
3235   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3236   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3237   unsigned StackAlignment = TFI.getStackAlignment();
3238   uint64_t AlignMask = StackAlignment - 1;
3239   int64_t Offset = StackSize;
3240   unsigned SlotSize = RegInfo->getSlotSize();
3241   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3242     // Number smaller than 12 so just add the difference.
3243     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3244   } else {
3245     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3246     Offset = ((~AlignMask) & Offset) + StackAlignment +
3247       (StackAlignment-SlotSize);
3248   }
3249   return Offset;
3250 }
3251
3252 /// MatchingStackOffset - Return true if the given stack call argument is
3253 /// already available in the same position (relatively) of the caller's
3254 /// incoming argument stack.
3255 static
3256 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3257                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3258                          const X86InstrInfo *TII) {
3259   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3260   int FI = INT_MAX;
3261   if (Arg.getOpcode() == ISD::CopyFromReg) {
3262     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3263     if (!TargetRegisterInfo::isVirtualRegister(VR))
3264       return false;
3265     MachineInstr *Def = MRI->getVRegDef(VR);
3266     if (!Def)
3267       return false;
3268     if (!Flags.isByVal()) {
3269       if (!TII->isLoadFromStackSlot(Def, FI))
3270         return false;
3271     } else {
3272       unsigned Opcode = Def->getOpcode();
3273       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3274            Opcode == X86::LEA64_32r) &&
3275           Def->getOperand(1).isFI()) {
3276         FI = Def->getOperand(1).getIndex();
3277         Bytes = Flags.getByValSize();
3278       } else
3279         return false;
3280     }
3281   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3282     if (Flags.isByVal())
3283       // ByVal argument is passed in as a pointer but it's now being
3284       // dereferenced. e.g.
3285       // define @foo(%struct.X* %A) {
3286       //   tail call @bar(%struct.X* byval %A)
3287       // }
3288       return false;
3289     SDValue Ptr = Ld->getBasePtr();
3290     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3291     if (!FINode)
3292       return false;
3293     FI = FINode->getIndex();
3294   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3295     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3296     FI = FINode->getIndex();
3297     Bytes = Flags.getByValSize();
3298   } else
3299     return false;
3300
3301   assert(FI != INT_MAX);
3302   if (!MFI->isFixedObjectIndex(FI))
3303     return false;
3304   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3305 }
3306
3307 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3308 /// for tail call optimization. Targets which want to do tail call
3309 /// optimization should implement this function.
3310 bool
3311 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3312                                                      CallingConv::ID CalleeCC,
3313                                                      bool isVarArg,
3314                                                      bool isCalleeStructRet,
3315                                                      bool isCallerStructRet,
3316                                                      Type *RetTy,
3317                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3318                                     const SmallVectorImpl<SDValue> &OutVals,
3319                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3320                                                      SelectionDAG &DAG) const {
3321   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3322     return false;
3323
3324   // If -tailcallopt is specified, make fastcc functions tail-callable.
3325   const MachineFunction &MF = DAG.getMachineFunction();
3326   const Function *CallerF = MF.getFunction();
3327
3328   // If the function return type is x86_fp80 and the callee return type is not,
3329   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3330   // perform a tailcall optimization here.
3331   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3332     return false;
3333
3334   CallingConv::ID CallerCC = CallerF->getCallingConv();
3335   bool CCMatch = CallerCC == CalleeCC;
3336   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3337   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3338
3339   // Win64 functions have extra shadow space for argument homing. Don't do the
3340   // sibcall if the caller and callee have mismatched expectations for this
3341   // space.
3342   if (IsCalleeWin64 != IsCallerWin64)
3343     return false;
3344
3345   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3346     if (IsTailCallConvention(CalleeCC) && CCMatch)
3347       return true;
3348     return false;
3349   }
3350
3351   // Look for obvious safe cases to perform tail call optimization that do not
3352   // require ABI changes. This is what gcc calls sibcall.
3353
3354   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3355   // emit a special epilogue.
3356   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3357   if (RegInfo->needsStackRealignment(MF))
3358     return false;
3359
3360   // Also avoid sibcall optimization if either caller or callee uses struct
3361   // return semantics.
3362   if (isCalleeStructRet || isCallerStructRet)
3363     return false;
3364
3365   // An stdcall/thiscall caller is expected to clean up its arguments; the
3366   // callee isn't going to do that.
3367   // FIXME: this is more restrictive than needed. We could produce a tailcall
3368   // when the stack adjustment matches. For example, with a thiscall that takes
3369   // only one argument.
3370   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3371                    CallerCC == CallingConv::X86_ThisCall))
3372     return false;
3373
3374   // Do not sibcall optimize vararg calls unless all arguments are passed via
3375   // registers.
3376   if (isVarArg && !Outs.empty()) {
3377
3378     // Optimizing for varargs on Win64 is unlikely to be safe without
3379     // additional testing.
3380     if (IsCalleeWin64 || IsCallerWin64)
3381       return false;
3382
3383     SmallVector<CCValAssign, 16> ArgLocs;
3384     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3385                    *DAG.getContext());
3386
3387     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3388     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3389       if (!ArgLocs[i].isRegLoc())
3390         return false;
3391   }
3392
3393   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3394   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3395   // this into a sibcall.
3396   bool Unused = false;
3397   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3398     if (!Ins[i].Used) {
3399       Unused = true;
3400       break;
3401     }
3402   }
3403   if (Unused) {
3404     SmallVector<CCValAssign, 16> RVLocs;
3405     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3406                    *DAG.getContext());
3407     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3408     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3409       CCValAssign &VA = RVLocs[i];
3410       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3411         return false;
3412     }
3413   }
3414
3415   // If the calling conventions do not match, then we'd better make sure the
3416   // results are returned in the same way as what the caller expects.
3417   if (!CCMatch) {
3418     SmallVector<CCValAssign, 16> RVLocs1;
3419     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3420                     *DAG.getContext());
3421     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3422
3423     SmallVector<CCValAssign, 16> RVLocs2;
3424     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3425                     *DAG.getContext());
3426     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3427
3428     if (RVLocs1.size() != RVLocs2.size())
3429       return false;
3430     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3431       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3432         return false;
3433       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3434         return false;
3435       if (RVLocs1[i].isRegLoc()) {
3436         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3437           return false;
3438       } else {
3439         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3440           return false;
3441       }
3442     }
3443   }
3444
3445   // If the callee takes no arguments then go on to check the results of the
3446   // call.
3447   if (!Outs.empty()) {
3448     // Check if stack adjustment is needed. For now, do not do this if any
3449     // argument is passed on the stack.
3450     SmallVector<CCValAssign, 16> ArgLocs;
3451     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3452                    *DAG.getContext());
3453
3454     // Allocate shadow area for Win64
3455     if (IsCalleeWin64)
3456       CCInfo.AllocateStack(32, 8);
3457
3458     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3459     if (CCInfo.getNextStackOffset()) {
3460       MachineFunction &MF = DAG.getMachineFunction();
3461       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3462         return false;
3463
3464       // Check if the arguments are already laid out in the right way as
3465       // the caller's fixed stack objects.
3466       MachineFrameInfo *MFI = MF.getFrameInfo();
3467       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3468       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3469       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3470         CCValAssign &VA = ArgLocs[i];
3471         SDValue Arg = OutVals[i];
3472         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3473         if (VA.getLocInfo() == CCValAssign::Indirect)
3474           return false;
3475         if (!VA.isRegLoc()) {
3476           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3477                                    MFI, MRI, TII))
3478             return false;
3479         }
3480       }
3481     }
3482
3483     // If the tailcall address may be in a register, then make sure it's
3484     // possible to register allocate for it. In 32-bit, the call address can
3485     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3486     // callee-saved registers are restored. These happen to be the same
3487     // registers used to pass 'inreg' arguments so watch out for those.
3488     if (!Subtarget->is64Bit() &&
3489         ((!isa<GlobalAddressSDNode>(Callee) &&
3490           !isa<ExternalSymbolSDNode>(Callee)) ||
3491          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3492       unsigned NumInRegs = 0;
3493       // In PIC we need an extra register to formulate the address computation
3494       // for the callee.
3495       unsigned MaxInRegs =
3496         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3497
3498       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3499         CCValAssign &VA = ArgLocs[i];
3500         if (!VA.isRegLoc())
3501           continue;
3502         unsigned Reg = VA.getLocReg();
3503         switch (Reg) {
3504         default: break;
3505         case X86::EAX: case X86::EDX: case X86::ECX:
3506           if (++NumInRegs == MaxInRegs)
3507             return false;
3508           break;
3509         }
3510       }
3511     }
3512   }
3513
3514   return true;
3515 }
3516
3517 FastISel *
3518 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3519                                   const TargetLibraryInfo *libInfo) const {
3520   return X86::createFastISel(funcInfo, libInfo);
3521 }
3522
3523 //===----------------------------------------------------------------------===//
3524 //                           Other Lowering Hooks
3525 //===----------------------------------------------------------------------===//
3526
3527 static bool MayFoldLoad(SDValue Op) {
3528   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3529 }
3530
3531 static bool MayFoldIntoStore(SDValue Op) {
3532   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3533 }
3534
3535 static bool isTargetShuffle(unsigned Opcode) {
3536   switch(Opcode) {
3537   default: return false;
3538   case X86ISD::BLENDI:
3539   case X86ISD::PSHUFB:
3540   case X86ISD::PSHUFD:
3541   case X86ISD::PSHUFHW:
3542   case X86ISD::PSHUFLW:
3543   case X86ISD::SHUFP:
3544   case X86ISD::PALIGNR:
3545   case X86ISD::MOVLHPS:
3546   case X86ISD::MOVLHPD:
3547   case X86ISD::MOVHLPS:
3548   case X86ISD::MOVLPS:
3549   case X86ISD::MOVLPD:
3550   case X86ISD::MOVSHDUP:
3551   case X86ISD::MOVSLDUP:
3552   case X86ISD::MOVDDUP:
3553   case X86ISD::MOVSS:
3554   case X86ISD::MOVSD:
3555   case X86ISD::UNPCKL:
3556   case X86ISD::UNPCKH:
3557   case X86ISD::VPERMILPI:
3558   case X86ISD::VPERM2X128:
3559   case X86ISD::VPERMI:
3560     return true;
3561   }
3562 }
3563
3564 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3565                                     SDValue V1, unsigned TargetMask,
3566                                     SelectionDAG &DAG) {
3567   switch(Opc) {
3568   default: llvm_unreachable("Unknown x86 shuffle node");
3569   case X86ISD::PSHUFD:
3570   case X86ISD::PSHUFHW:
3571   case X86ISD::PSHUFLW:
3572   case X86ISD::VPERMILPI:
3573   case X86ISD::VPERMI:
3574     return DAG.getNode(Opc, dl, VT, V1,
3575                        DAG.getConstant(TargetMask, dl, MVT::i8));
3576   }
3577 }
3578
3579 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3580                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3581   switch(Opc) {
3582   default: llvm_unreachable("Unknown x86 shuffle node");
3583   case X86ISD::MOVLHPS:
3584   case X86ISD::MOVLHPD:
3585   case X86ISD::MOVHLPS:
3586   case X86ISD::MOVLPS:
3587   case X86ISD::MOVLPD:
3588   case X86ISD::MOVSS:
3589   case X86ISD::MOVSD:
3590   case X86ISD::UNPCKL:
3591   case X86ISD::UNPCKH:
3592     return DAG.getNode(Opc, dl, VT, V1, V2);
3593   }
3594 }
3595
3596 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3597   MachineFunction &MF = DAG.getMachineFunction();
3598   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3599   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3600   int ReturnAddrIndex = FuncInfo->getRAIndex();
3601
3602   if (ReturnAddrIndex == 0) {
3603     // Set up a frame object for the return address.
3604     unsigned SlotSize = RegInfo->getSlotSize();
3605     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3606                                                            -(int64_t)SlotSize,
3607                                                            false);
3608     FuncInfo->setRAIndex(ReturnAddrIndex);
3609   }
3610
3611   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3612 }
3613
3614 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3615                                        bool hasSymbolicDisplacement) {
3616   // Offset should fit into 32 bit immediate field.
3617   if (!isInt<32>(Offset))
3618     return false;
3619
3620   // If we don't have a symbolic displacement - we don't have any extra
3621   // restrictions.
3622   if (!hasSymbolicDisplacement)
3623     return true;
3624
3625   // FIXME: Some tweaks might be needed for medium code model.
3626   if (M != CodeModel::Small && M != CodeModel::Kernel)
3627     return false;
3628
3629   // For small code model we assume that latest object is 16MB before end of 31
3630   // bits boundary. We may also accept pretty large negative constants knowing
3631   // that all objects are in the positive half of address space.
3632   if (M == CodeModel::Small && Offset < 16*1024*1024)
3633     return true;
3634
3635   // For kernel code model we know that all object resist in the negative half
3636   // of 32bits address space. We may not accept negative offsets, since they may
3637   // be just off and we may accept pretty large positive ones.
3638   if (M == CodeModel::Kernel && Offset >= 0)
3639     return true;
3640
3641   return false;
3642 }
3643
3644 /// isCalleePop - Determines whether the callee is required to pop its
3645 /// own arguments. Callee pop is necessary to support tail calls.
3646 bool X86::isCalleePop(CallingConv::ID CallingConv,
3647                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3648   switch (CallingConv) {
3649   default:
3650     return false;
3651   case CallingConv::X86_StdCall:
3652   case CallingConv::X86_FastCall:
3653   case CallingConv::X86_ThisCall:
3654     return !is64Bit;
3655   case CallingConv::Fast:
3656   case CallingConv::GHC:
3657   case CallingConv::HiPE:
3658     if (IsVarArg)
3659       return false;
3660     return TailCallOpt;
3661   }
3662 }
3663
3664 /// \brief Return true if the condition is an unsigned comparison operation.
3665 static bool isX86CCUnsigned(unsigned X86CC) {
3666   switch (X86CC) {
3667   default: llvm_unreachable("Invalid integer condition!");
3668   case X86::COND_E:     return true;
3669   case X86::COND_G:     return false;
3670   case X86::COND_GE:    return false;
3671   case X86::COND_L:     return false;
3672   case X86::COND_LE:    return false;
3673   case X86::COND_NE:    return true;
3674   case X86::COND_B:     return true;
3675   case X86::COND_A:     return true;
3676   case X86::COND_BE:    return true;
3677   case X86::COND_AE:    return true;
3678   }
3679   llvm_unreachable("covered switch fell through?!");
3680 }
3681
3682 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3683 /// specific condition code, returning the condition code and the LHS/RHS of the
3684 /// comparison to make.
3685 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3686                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3687   if (!isFP) {
3688     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3689       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3690         // X > -1   -> X == 0, jump !sign.
3691         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3692         return X86::COND_NS;
3693       }
3694       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3695         // X < 0   -> X == 0, jump on sign.
3696         return X86::COND_S;
3697       }
3698       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3699         // X < 1   -> X <= 0
3700         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3701         return X86::COND_LE;
3702       }
3703     }
3704
3705     switch (SetCCOpcode) {
3706     default: llvm_unreachable("Invalid integer condition!");
3707     case ISD::SETEQ:  return X86::COND_E;
3708     case ISD::SETGT:  return X86::COND_G;
3709     case ISD::SETGE:  return X86::COND_GE;
3710     case ISD::SETLT:  return X86::COND_L;
3711     case ISD::SETLE:  return X86::COND_LE;
3712     case ISD::SETNE:  return X86::COND_NE;
3713     case ISD::SETULT: return X86::COND_B;
3714     case ISD::SETUGT: return X86::COND_A;
3715     case ISD::SETULE: return X86::COND_BE;
3716     case ISD::SETUGE: return X86::COND_AE;
3717     }
3718   }
3719
3720   // First determine if it is required or is profitable to flip the operands.
3721
3722   // If LHS is a foldable load, but RHS is not, flip the condition.
3723   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3724       !ISD::isNON_EXTLoad(RHS.getNode())) {
3725     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3726     std::swap(LHS, RHS);
3727   }
3728
3729   switch (SetCCOpcode) {
3730   default: break;
3731   case ISD::SETOLT:
3732   case ISD::SETOLE:
3733   case ISD::SETUGT:
3734   case ISD::SETUGE:
3735     std::swap(LHS, RHS);
3736     break;
3737   }
3738
3739   // On a floating point condition, the flags are set as follows:
3740   // ZF  PF  CF   op
3741   //  0 | 0 | 0 | X > Y
3742   //  0 | 0 | 1 | X < Y
3743   //  1 | 0 | 0 | X == Y
3744   //  1 | 1 | 1 | unordered
3745   switch (SetCCOpcode) {
3746   default: llvm_unreachable("Condcode should be pre-legalized away");
3747   case ISD::SETUEQ:
3748   case ISD::SETEQ:   return X86::COND_E;
3749   case ISD::SETOLT:              // flipped
3750   case ISD::SETOGT:
3751   case ISD::SETGT:   return X86::COND_A;
3752   case ISD::SETOLE:              // flipped
3753   case ISD::SETOGE:
3754   case ISD::SETGE:   return X86::COND_AE;
3755   case ISD::SETUGT:              // flipped
3756   case ISD::SETULT:
3757   case ISD::SETLT:   return X86::COND_B;
3758   case ISD::SETUGE:              // flipped
3759   case ISD::SETULE:
3760   case ISD::SETLE:   return X86::COND_BE;
3761   case ISD::SETONE:
3762   case ISD::SETNE:   return X86::COND_NE;
3763   case ISD::SETUO:   return X86::COND_P;
3764   case ISD::SETO:    return X86::COND_NP;
3765   case ISD::SETOEQ:
3766   case ISD::SETUNE:  return X86::COND_INVALID;
3767   }
3768 }
3769
3770 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3771 /// code. Current x86 isa includes the following FP cmov instructions:
3772 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3773 static bool hasFPCMov(unsigned X86CC) {
3774   switch (X86CC) {
3775   default:
3776     return false;
3777   case X86::COND_B:
3778   case X86::COND_BE:
3779   case X86::COND_E:
3780   case X86::COND_P:
3781   case X86::COND_A:
3782   case X86::COND_AE:
3783   case X86::COND_NE:
3784   case X86::COND_NP:
3785     return true;
3786   }
3787 }
3788
3789 /// isFPImmLegal - Returns true if the target can instruction select the
3790 /// specified FP immediate natively. If false, the legalizer will
3791 /// materialize the FP immediate as a load from a constant pool.
3792 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3793   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3794     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3795       return true;
3796   }
3797   return false;
3798 }
3799
3800 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3801                                               ISD::LoadExtType ExtTy,
3802                                               EVT NewVT) const {
3803   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3804   // relocation target a movq or addq instruction: don't let the load shrink.
3805   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3806   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3807     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3808       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3809   return true;
3810 }
3811
3812 /// \brief Returns true if it is beneficial to convert a load of a constant
3813 /// to just the constant itself.
3814 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3815                                                           Type *Ty) const {
3816   assert(Ty->isIntegerTy());
3817
3818   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3819   if (BitSize == 0 || BitSize > 64)
3820     return false;
3821   return true;
3822 }
3823
3824 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3825                                                 unsigned Index) const {
3826   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3827     return false;
3828
3829   return (Index == 0 || Index == ResVT.getVectorNumElements());
3830 }
3831
3832 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3833   // Speculate cttz only if we can directly use TZCNT.
3834   return Subtarget->hasBMI();
3835 }
3836
3837 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3838   // Speculate ctlz only if we can directly use LZCNT.
3839   return Subtarget->hasLZCNT();
3840 }
3841
3842 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3843 /// the specified range (L, H].
3844 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3845   return (Val < 0) || (Val >= Low && Val < Hi);
3846 }
3847
3848 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3849 /// specified value.
3850 static bool isUndefOrEqual(int Val, int CmpVal) {
3851   return (Val < 0 || Val == CmpVal);
3852 }
3853
3854 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3855 /// from position Pos and ending in Pos+Size, falls within the specified
3856 /// sequential range (Low, Low+Size]. or is undef.
3857 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3858                                        unsigned Pos, unsigned Size, int Low) {
3859   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3860     if (!isUndefOrEqual(Mask[i], Low))
3861       return false;
3862   return true;
3863 }
3864
3865 /// isVEXTRACTIndex - Return true if the specified
3866 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3867 /// suitable for instruction that extract 128 or 256 bit vectors
3868 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3869   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3870   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3871     return false;
3872
3873   // The index should be aligned on a vecWidth-bit boundary.
3874   uint64_t Index =
3875     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3876
3877   MVT VT = N->getSimpleValueType(0);
3878   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3879   bool Result = (Index * ElSize) % vecWidth == 0;
3880
3881   return Result;
3882 }
3883
3884 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3885 /// operand specifies a subvector insert that is suitable for input to
3886 /// insertion of 128 or 256-bit subvectors
3887 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3888   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3889   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3890     return false;
3891   // The index should be aligned on a vecWidth-bit boundary.
3892   uint64_t Index =
3893     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3894
3895   MVT VT = N->getSimpleValueType(0);
3896   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3897   bool Result = (Index * ElSize) % vecWidth == 0;
3898
3899   return Result;
3900 }
3901
3902 bool X86::isVINSERT128Index(SDNode *N) {
3903   return isVINSERTIndex(N, 128);
3904 }
3905
3906 bool X86::isVINSERT256Index(SDNode *N) {
3907   return isVINSERTIndex(N, 256);
3908 }
3909
3910 bool X86::isVEXTRACT128Index(SDNode *N) {
3911   return isVEXTRACTIndex(N, 128);
3912 }
3913
3914 bool X86::isVEXTRACT256Index(SDNode *N) {
3915   return isVEXTRACTIndex(N, 256);
3916 }
3917
3918 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3919   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3920   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3921     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3922
3923   uint64_t Index =
3924     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3925
3926   MVT VecVT = N->getOperand(0).getSimpleValueType();
3927   MVT ElVT = VecVT.getVectorElementType();
3928
3929   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3930   return Index / NumElemsPerChunk;
3931 }
3932
3933 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3934   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3935   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3936     llvm_unreachable("Illegal insert subvector for VINSERT");
3937
3938   uint64_t Index =
3939     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3940
3941   MVT VecVT = N->getSimpleValueType(0);
3942   MVT ElVT = VecVT.getVectorElementType();
3943
3944   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3945   return Index / NumElemsPerChunk;
3946 }
3947
3948 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3949 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3950 /// and VINSERTI128 instructions.
3951 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3952   return getExtractVEXTRACTImmediate(N, 128);
3953 }
3954
3955 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3956 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3957 /// and VINSERTI64x4 instructions.
3958 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3959   return getExtractVEXTRACTImmediate(N, 256);
3960 }
3961
3962 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3963 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3964 /// and VINSERTI128 instructions.
3965 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3966   return getInsertVINSERTImmediate(N, 128);
3967 }
3968
3969 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3970 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3971 /// and VINSERTI64x4 instructions.
3972 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3973   return getInsertVINSERTImmediate(N, 256);
3974 }
3975
3976 /// isZero - Returns true if Elt is a constant integer zero
3977 static bool isZero(SDValue V) {
3978   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3979   return C && C->isNullValue();
3980 }
3981
3982 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3983 /// constant +0.0.
3984 bool X86::isZeroNode(SDValue Elt) {
3985   if (isZero(Elt))
3986     return true;
3987   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3988     return CFP->getValueAPF().isPosZero();
3989   return false;
3990 }
3991
3992 /// getZeroVector - Returns a vector of specified type with all zero elements.
3993 ///
3994 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3995                              SelectionDAG &DAG, SDLoc dl) {
3996   assert(VT.isVector() && "Expected a vector type");
3997
3998   // Always build SSE zero vectors as <4 x i32> bitcasted
3999   // to their dest type. This ensures they get CSE'd.
4000   SDValue Vec;
4001   if (VT.is128BitVector()) {  // SSE
4002     if (Subtarget->hasSSE2()) {  // SSE2
4003       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4004       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4005     } else { // SSE1
4006       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4007       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4008     }
4009   } else if (VT.is256BitVector()) { // AVX
4010     if (Subtarget->hasInt256()) { // AVX2
4011       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4012       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4013       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4014     } else {
4015       // 256-bit logic and arithmetic instructions in AVX are all
4016       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4017       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4018       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4019       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4020     }
4021   } else if (VT.is512BitVector()) { // AVX-512
4022       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4023       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4024                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4025       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4026   } else if (VT.getScalarType() == MVT::i1) {
4027
4028     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4029             && "Unexpected vector type");
4030     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4031             && "Unexpected vector type");
4032     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4033     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4034     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4035   } else
4036     llvm_unreachable("Unexpected vector type");
4037
4038   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4039 }
4040
4041 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4042                                 SelectionDAG &DAG, SDLoc dl,
4043                                 unsigned vectorWidth) {
4044   assert((vectorWidth == 128 || vectorWidth == 256) &&
4045          "Unsupported vector width");
4046   EVT VT = Vec.getValueType();
4047   EVT ElVT = VT.getVectorElementType();
4048   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4049   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4050                                   VT.getVectorNumElements()/Factor);
4051
4052   // Extract from UNDEF is UNDEF.
4053   if (Vec.getOpcode() == ISD::UNDEF)
4054     return DAG.getUNDEF(ResultVT);
4055
4056   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4057   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4058
4059   // This is the index of the first element of the vectorWidth-bit chunk
4060   // we want.
4061   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4062                                * ElemsPerChunk);
4063
4064   // If the input is a buildvector just emit a smaller one.
4065   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4066     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4067                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4068                                     ElemsPerChunk));
4069
4070   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4071   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4072 }
4073
4074 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4075 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4076 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4077 /// instructions or a simple subregister reference. Idx is an index in the
4078 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4079 /// lowering EXTRACT_VECTOR_ELT operations easier.
4080 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4081                                    SelectionDAG &DAG, SDLoc dl) {
4082   assert((Vec.getValueType().is256BitVector() ||
4083           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4084   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4085 }
4086
4087 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4088 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4089                                    SelectionDAG &DAG, SDLoc dl) {
4090   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4091   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4092 }
4093
4094 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4095                                unsigned IdxVal, SelectionDAG &DAG,
4096                                SDLoc dl, unsigned vectorWidth) {
4097   assert((vectorWidth == 128 || vectorWidth == 256) &&
4098          "Unsupported vector width");
4099   // Inserting UNDEF is Result
4100   if (Vec.getOpcode() == ISD::UNDEF)
4101     return Result;
4102   EVT VT = Vec.getValueType();
4103   EVT ElVT = VT.getVectorElementType();
4104   EVT ResultVT = Result.getValueType();
4105
4106   // Insert the relevant vectorWidth bits.
4107   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4108
4109   // This is the index of the first element of the vectorWidth-bit chunk
4110   // we want.
4111   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4112                                * ElemsPerChunk);
4113
4114   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4115   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4116 }
4117
4118 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4119 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4120 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4121 /// simple superregister reference.  Idx is an index in the 128 bits
4122 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4123 /// lowering INSERT_VECTOR_ELT operations easier.
4124 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4125                                   SelectionDAG &DAG, SDLoc dl) {
4126   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4127
4128   // For insertion into the zero index (low half) of a 256-bit vector, it is
4129   // more efficient to generate a blend with immediate instead of an insert*128.
4130   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4131   // extend the subvector to the size of the result vector. Make sure that
4132   // we are not recursing on that node by checking for undef here.
4133   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4134       Result.getOpcode() != ISD::UNDEF) {
4135     EVT ResultVT = Result.getValueType();
4136     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4137     SDValue Undef = DAG.getUNDEF(ResultVT);
4138     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4139                                  Vec, ZeroIndex);
4140
4141     // The blend instruction, and therefore its mask, depend on the data type.
4142     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4143     if (ScalarType.isFloatingPoint()) {
4144       // Choose either vblendps (float) or vblendpd (double).
4145       unsigned ScalarSize = ScalarType.getSizeInBits();
4146       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4147       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4148       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4149       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4150     }
4151
4152     const X86Subtarget &Subtarget =
4153     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4154
4155     // AVX2 is needed for 256-bit integer blend support.
4156     // Integers must be cast to 32-bit because there is only vpblendd;
4157     // vpblendw can't be used for this because it has a handicapped mask.
4158
4159     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4160     // is still more efficient than using the wrong domain vinsertf128 that
4161     // will be created by InsertSubVector().
4162     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4163
4164     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4165     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4166     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4167     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4168   }
4169
4170   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4171 }
4172
4173 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4174                                   SelectionDAG &DAG, SDLoc dl) {
4175   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4176   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4177 }
4178
4179 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4180 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4181 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4182 /// large BUILD_VECTORS.
4183 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4184                                    unsigned NumElems, SelectionDAG &DAG,
4185                                    SDLoc dl) {
4186   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4187   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4188 }
4189
4190 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4191                                    unsigned NumElems, SelectionDAG &DAG,
4192                                    SDLoc dl) {
4193   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4194   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4195 }
4196
4197 /// getOnesVector - Returns a vector of specified type with all bits set.
4198 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4199 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4200 /// Then bitcast to their original type, ensuring they get CSE'd.
4201 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4202                              SDLoc dl) {
4203   assert(VT.isVector() && "Expected a vector type");
4204
4205   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4206   SDValue Vec;
4207   if (VT.is256BitVector()) {
4208     if (HasInt256) { // AVX2
4209       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4210       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4211     } else { // AVX
4212       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4213       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4214     }
4215   } else if (VT.is128BitVector()) {
4216     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4217   } else
4218     llvm_unreachable("Unexpected vector type");
4219
4220   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4221 }
4222
4223 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4224 /// operation of specified width.
4225 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4226                        SDValue V2) {
4227   unsigned NumElems = VT.getVectorNumElements();
4228   SmallVector<int, 8> Mask;
4229   Mask.push_back(NumElems);
4230   for (unsigned i = 1; i != NumElems; ++i)
4231     Mask.push_back(i);
4232   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4233 }
4234
4235 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4236 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4237                           SDValue V2) {
4238   unsigned NumElems = VT.getVectorNumElements();
4239   SmallVector<int, 8> Mask;
4240   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4241     Mask.push_back(i);
4242     Mask.push_back(i + NumElems);
4243   }
4244   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4245 }
4246
4247 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4248 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4249                           SDValue V2) {
4250   unsigned NumElems = VT.getVectorNumElements();
4251   SmallVector<int, 8> Mask;
4252   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4253     Mask.push_back(i + Half);
4254     Mask.push_back(i + NumElems + Half);
4255   }
4256   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4257 }
4258
4259 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4260 /// vector of zero or undef vector.  This produces a shuffle where the low
4261 /// element of V2 is swizzled into the zero/undef vector, landing at element
4262 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4263 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4264                                            bool IsZero,
4265                                            const X86Subtarget *Subtarget,
4266                                            SelectionDAG &DAG) {
4267   MVT VT = V2.getSimpleValueType();
4268   SDValue V1 = IsZero
4269     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4270   unsigned NumElems = VT.getVectorNumElements();
4271   SmallVector<int, 16> MaskVec;
4272   for (unsigned i = 0; i != NumElems; ++i)
4273     // If this is the insertion idx, put the low elt of V2 here.
4274     MaskVec.push_back(i == Idx ? NumElems : i);
4275   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4276 }
4277
4278 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4279 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4280 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4281 /// shuffles which use a single input multiple times, and in those cases it will
4282 /// adjust the mask to only have indices within that single input.
4283 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4284                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4285   unsigned NumElems = VT.getVectorNumElements();
4286   SDValue ImmN;
4287
4288   IsUnary = false;
4289   bool IsFakeUnary = false;
4290   switch(N->getOpcode()) {
4291   case X86ISD::BLENDI:
4292     ImmN = N->getOperand(N->getNumOperands()-1);
4293     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4294     break;
4295   case X86ISD::SHUFP:
4296     ImmN = N->getOperand(N->getNumOperands()-1);
4297     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4298     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4299     break;
4300   case X86ISD::UNPCKH:
4301     DecodeUNPCKHMask(VT, Mask);
4302     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4303     break;
4304   case X86ISD::UNPCKL:
4305     DecodeUNPCKLMask(VT, Mask);
4306     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4307     break;
4308   case X86ISD::MOVHLPS:
4309     DecodeMOVHLPSMask(NumElems, Mask);
4310     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4311     break;
4312   case X86ISD::MOVLHPS:
4313     DecodeMOVLHPSMask(NumElems, Mask);
4314     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4315     break;
4316   case X86ISD::PALIGNR:
4317     ImmN = N->getOperand(N->getNumOperands()-1);
4318     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4319     break;
4320   case X86ISD::PSHUFD:
4321   case X86ISD::VPERMILPI:
4322     ImmN = N->getOperand(N->getNumOperands()-1);
4323     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4324     IsUnary = true;
4325     break;
4326   case X86ISD::PSHUFHW:
4327     ImmN = N->getOperand(N->getNumOperands()-1);
4328     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4329     IsUnary = true;
4330     break;
4331   case X86ISD::PSHUFLW:
4332     ImmN = N->getOperand(N->getNumOperands()-1);
4333     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4334     IsUnary = true;
4335     break;
4336   case X86ISD::PSHUFB: {
4337     IsUnary = true;
4338     SDValue MaskNode = N->getOperand(1);
4339     while (MaskNode->getOpcode() == ISD::BITCAST)
4340       MaskNode = MaskNode->getOperand(0);
4341
4342     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4343       // If we have a build-vector, then things are easy.
4344       EVT VT = MaskNode.getValueType();
4345       assert(VT.isVector() &&
4346              "Can't produce a non-vector with a build_vector!");
4347       if (!VT.isInteger())
4348         return false;
4349
4350       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4351
4352       SmallVector<uint64_t, 32> RawMask;
4353       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4354         SDValue Op = MaskNode->getOperand(i);
4355         if (Op->getOpcode() == ISD::UNDEF) {
4356           RawMask.push_back((uint64_t)SM_SentinelUndef);
4357           continue;
4358         }
4359         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4360         if (!CN)
4361           return false;
4362         APInt MaskElement = CN->getAPIntValue();
4363
4364         // We now have to decode the element which could be any integer size and
4365         // extract each byte of it.
4366         for (int j = 0; j < NumBytesPerElement; ++j) {
4367           // Note that this is x86 and so always little endian: the low byte is
4368           // the first byte of the mask.
4369           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4370           MaskElement = MaskElement.lshr(8);
4371         }
4372       }
4373       DecodePSHUFBMask(RawMask, Mask);
4374       break;
4375     }
4376
4377     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4378     if (!MaskLoad)
4379       return false;
4380
4381     SDValue Ptr = MaskLoad->getBasePtr();
4382     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4383         Ptr->getOpcode() == X86ISD::WrapperRIP)
4384       Ptr = Ptr->getOperand(0);
4385
4386     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4387     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4388       return false;
4389
4390     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4391       DecodePSHUFBMask(C, Mask);
4392       if (Mask.empty())
4393         return false;
4394       break;
4395     }
4396
4397     return false;
4398   }
4399   case X86ISD::VPERMI:
4400     ImmN = N->getOperand(N->getNumOperands()-1);
4401     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4402     IsUnary = true;
4403     break;
4404   case X86ISD::MOVSS:
4405   case X86ISD::MOVSD:
4406     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4407     break;
4408   case X86ISD::VPERM2X128:
4409     ImmN = N->getOperand(N->getNumOperands()-1);
4410     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4411     if (Mask.empty()) return false;
4412     break;
4413   case X86ISD::MOVSLDUP:
4414     DecodeMOVSLDUPMask(VT, Mask);
4415     IsUnary = true;
4416     break;
4417   case X86ISD::MOVSHDUP:
4418     DecodeMOVSHDUPMask(VT, Mask);
4419     IsUnary = true;
4420     break;
4421   case X86ISD::MOVDDUP:
4422     DecodeMOVDDUPMask(VT, Mask);
4423     IsUnary = true;
4424     break;
4425   case X86ISD::MOVLHPD:
4426   case X86ISD::MOVLPD:
4427   case X86ISD::MOVLPS:
4428     // Not yet implemented
4429     return false;
4430   default: llvm_unreachable("unknown target shuffle node");
4431   }
4432
4433   // If we have a fake unary shuffle, the shuffle mask is spread across two
4434   // inputs that are actually the same node. Re-map the mask to always point
4435   // into the first input.
4436   if (IsFakeUnary)
4437     for (int &M : Mask)
4438       if (M >= (int)Mask.size())
4439         M -= Mask.size();
4440
4441   return true;
4442 }
4443
4444 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4445 /// element of the result of the vector shuffle.
4446 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4447                                    unsigned Depth) {
4448   if (Depth == 6)
4449     return SDValue();  // Limit search depth.
4450
4451   SDValue V = SDValue(N, 0);
4452   EVT VT = V.getValueType();
4453   unsigned Opcode = V.getOpcode();
4454
4455   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4456   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4457     int Elt = SV->getMaskElt(Index);
4458
4459     if (Elt < 0)
4460       return DAG.getUNDEF(VT.getVectorElementType());
4461
4462     unsigned NumElems = VT.getVectorNumElements();
4463     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4464                                          : SV->getOperand(1);
4465     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4466   }
4467
4468   // Recurse into target specific vector shuffles to find scalars.
4469   if (isTargetShuffle(Opcode)) {
4470     MVT ShufVT = V.getSimpleValueType();
4471     unsigned NumElems = ShufVT.getVectorNumElements();
4472     SmallVector<int, 16> ShuffleMask;
4473     bool IsUnary;
4474
4475     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4476       return SDValue();
4477
4478     int Elt = ShuffleMask[Index];
4479     if (Elt < 0)
4480       return DAG.getUNDEF(ShufVT.getVectorElementType());
4481
4482     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4483                                          : N->getOperand(1);
4484     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4485                                Depth+1);
4486   }
4487
4488   // Actual nodes that may contain scalar elements
4489   if (Opcode == ISD::BITCAST) {
4490     V = V.getOperand(0);
4491     EVT SrcVT = V.getValueType();
4492     unsigned NumElems = VT.getVectorNumElements();
4493
4494     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4495       return SDValue();
4496   }
4497
4498   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4499     return (Index == 0) ? V.getOperand(0)
4500                         : DAG.getUNDEF(VT.getVectorElementType());
4501
4502   if (V.getOpcode() == ISD::BUILD_VECTOR)
4503     return V.getOperand(Index);
4504
4505   return SDValue();
4506 }
4507
4508 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4509 ///
4510 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4511                                        unsigned NumNonZero, unsigned NumZero,
4512                                        SelectionDAG &DAG,
4513                                        const X86Subtarget* Subtarget,
4514                                        const TargetLowering &TLI) {
4515   if (NumNonZero > 8)
4516     return SDValue();
4517
4518   SDLoc dl(Op);
4519   SDValue V;
4520   bool First = true;
4521
4522   // SSE4.1 - use PINSRB to insert each byte directly.
4523   if (Subtarget->hasSSE41()) {
4524     for (unsigned i = 0; i < 16; ++i) {
4525       bool isNonZero = (NonZeros & (1 << i)) != 0;
4526       if (isNonZero) {
4527         if (First) {
4528           if (NumZero)
4529             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4530           else
4531             V = DAG.getUNDEF(MVT::v16i8);
4532           First = false;
4533         }
4534         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4535                         MVT::v16i8, V, Op.getOperand(i),
4536                         DAG.getIntPtrConstant(i, dl));
4537       }
4538     }
4539
4540     return V;
4541   }
4542
4543   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4544   for (unsigned i = 0; i < 16; ++i) {
4545     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4546     if (ThisIsNonZero && First) {
4547       if (NumZero)
4548         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4549       else
4550         V = DAG.getUNDEF(MVT::v8i16);
4551       First = false;
4552     }
4553
4554     if ((i & 1) != 0) {
4555       SDValue ThisElt, LastElt;
4556       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4557       if (LastIsNonZero) {
4558         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4559                               MVT::i16, Op.getOperand(i-1));
4560       }
4561       if (ThisIsNonZero) {
4562         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4563         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4564                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4565         if (LastIsNonZero)
4566           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4567       } else
4568         ThisElt = LastElt;
4569
4570       if (ThisElt.getNode())
4571         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4572                         DAG.getIntPtrConstant(i/2, dl));
4573     }
4574   }
4575
4576   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4577 }
4578
4579 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4580 ///
4581 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4582                                      unsigned NumNonZero, unsigned NumZero,
4583                                      SelectionDAG &DAG,
4584                                      const X86Subtarget* Subtarget,
4585                                      const TargetLowering &TLI) {
4586   if (NumNonZero > 4)
4587     return SDValue();
4588
4589   SDLoc dl(Op);
4590   SDValue V;
4591   bool First = true;
4592   for (unsigned i = 0; i < 8; ++i) {
4593     bool isNonZero = (NonZeros & (1 << i)) != 0;
4594     if (isNonZero) {
4595       if (First) {
4596         if (NumZero)
4597           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4598         else
4599           V = DAG.getUNDEF(MVT::v8i16);
4600         First = false;
4601       }
4602       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4603                       MVT::v8i16, V, Op.getOperand(i),
4604                       DAG.getIntPtrConstant(i, dl));
4605     }
4606   }
4607
4608   return V;
4609 }
4610
4611 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4612 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4613                                      const X86Subtarget *Subtarget,
4614                                      const TargetLowering &TLI) {
4615   // Find all zeroable elements.
4616   std::bitset<4> Zeroable;
4617   for (int i=0; i < 4; ++i) {
4618     SDValue Elt = Op->getOperand(i);
4619     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4620   }
4621   assert(Zeroable.size() - Zeroable.count() > 1 &&
4622          "We expect at least two non-zero elements!");
4623
4624   // We only know how to deal with build_vector nodes where elements are either
4625   // zeroable or extract_vector_elt with constant index.
4626   SDValue FirstNonZero;
4627   unsigned FirstNonZeroIdx;
4628   for (unsigned i=0; i < 4; ++i) {
4629     if (Zeroable[i])
4630       continue;
4631     SDValue Elt = Op->getOperand(i);
4632     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4633         !isa<ConstantSDNode>(Elt.getOperand(1)))
4634       return SDValue();
4635     // Make sure that this node is extracting from a 128-bit vector.
4636     MVT VT = Elt.getOperand(0).getSimpleValueType();
4637     if (!VT.is128BitVector())
4638       return SDValue();
4639     if (!FirstNonZero.getNode()) {
4640       FirstNonZero = Elt;
4641       FirstNonZeroIdx = i;
4642     }
4643   }
4644
4645   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4646   SDValue V1 = FirstNonZero.getOperand(0);
4647   MVT VT = V1.getSimpleValueType();
4648
4649   // See if this build_vector can be lowered as a blend with zero.
4650   SDValue Elt;
4651   unsigned EltMaskIdx, EltIdx;
4652   int Mask[4];
4653   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4654     if (Zeroable[EltIdx]) {
4655       // The zero vector will be on the right hand side.
4656       Mask[EltIdx] = EltIdx+4;
4657       continue;
4658     }
4659
4660     Elt = Op->getOperand(EltIdx);
4661     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4662     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4663     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4664       break;
4665     Mask[EltIdx] = EltIdx;
4666   }
4667
4668   if (EltIdx == 4) {
4669     // Let the shuffle legalizer deal with blend operations.
4670     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4671     if (V1.getSimpleValueType() != VT)
4672       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4673     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4674   }
4675
4676   // See if we can lower this build_vector to a INSERTPS.
4677   if (!Subtarget->hasSSE41())
4678     return SDValue();
4679
4680   SDValue V2 = Elt.getOperand(0);
4681   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4682     V1 = SDValue();
4683
4684   bool CanFold = true;
4685   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4686     if (Zeroable[i])
4687       continue;
4688
4689     SDValue Current = Op->getOperand(i);
4690     SDValue SrcVector = Current->getOperand(0);
4691     if (!V1.getNode())
4692       V1 = SrcVector;
4693     CanFold = SrcVector == V1 &&
4694       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4695   }
4696
4697   if (!CanFold)
4698     return SDValue();
4699
4700   assert(V1.getNode() && "Expected at least two non-zero elements!");
4701   if (V1.getSimpleValueType() != MVT::v4f32)
4702     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4703   if (V2.getSimpleValueType() != MVT::v4f32)
4704     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4705
4706   // Ok, we can emit an INSERTPS instruction.
4707   unsigned ZMask = Zeroable.to_ulong();
4708
4709   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4710   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4711   SDLoc DL(Op);
4712   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4713                                DAG.getIntPtrConstant(InsertPSMask, DL));
4714   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4715 }
4716
4717 /// Return a vector logical shift node.
4718 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4719                          unsigned NumBits, SelectionDAG &DAG,
4720                          const TargetLowering &TLI, SDLoc dl) {
4721   assert(VT.is128BitVector() && "Unknown type for VShift");
4722   MVT ShVT = MVT::v2i64;
4723   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4724   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4725   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4726   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4727   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4728   return DAG.getNode(ISD::BITCAST, dl, VT,
4729                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4730 }
4731
4732 static SDValue
4733 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4734
4735   // Check if the scalar load can be widened into a vector load. And if
4736   // the address is "base + cst" see if the cst can be "absorbed" into
4737   // the shuffle mask.
4738   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4739     SDValue Ptr = LD->getBasePtr();
4740     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4741       return SDValue();
4742     EVT PVT = LD->getValueType(0);
4743     if (PVT != MVT::i32 && PVT != MVT::f32)
4744       return SDValue();
4745
4746     int FI = -1;
4747     int64_t Offset = 0;
4748     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4749       FI = FINode->getIndex();
4750       Offset = 0;
4751     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4752                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4753       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4754       Offset = Ptr.getConstantOperandVal(1);
4755       Ptr = Ptr.getOperand(0);
4756     } else {
4757       return SDValue();
4758     }
4759
4760     // FIXME: 256-bit vector instructions don't require a strict alignment,
4761     // improve this code to support it better.
4762     unsigned RequiredAlign = VT.getSizeInBits()/8;
4763     SDValue Chain = LD->getChain();
4764     // Make sure the stack object alignment is at least 16 or 32.
4765     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4766     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4767       if (MFI->isFixedObjectIndex(FI)) {
4768         // Can't change the alignment. FIXME: It's possible to compute
4769         // the exact stack offset and reference FI + adjust offset instead.
4770         // If someone *really* cares about this. That's the way to implement it.
4771         return SDValue();
4772       } else {
4773         MFI->setObjectAlignment(FI, RequiredAlign);
4774       }
4775     }
4776
4777     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4778     // Ptr + (Offset & ~15).
4779     if (Offset < 0)
4780       return SDValue();
4781     if ((Offset % RequiredAlign) & 3)
4782       return SDValue();
4783     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4784     if (StartOffset) {
4785       SDLoc DL(Ptr);
4786       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4787                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4788     }
4789
4790     int EltNo = (Offset - StartOffset) >> 2;
4791     unsigned NumElems = VT.getVectorNumElements();
4792
4793     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4794     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4795                              LD->getPointerInfo().getWithOffset(StartOffset),
4796                              false, false, false, 0);
4797
4798     SmallVector<int, 8> Mask(NumElems, EltNo);
4799
4800     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4801   }
4802
4803   return SDValue();
4804 }
4805
4806 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4807 /// elements can be replaced by a single large load which has the same value as
4808 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4809 ///
4810 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4811 ///
4812 /// FIXME: we'd also like to handle the case where the last elements are zero
4813 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4814 /// There's even a handy isZeroNode for that purpose.
4815 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4816                                         SDLoc &DL, SelectionDAG &DAG,
4817                                         bool isAfterLegalize) {
4818   unsigned NumElems = Elts.size();
4819
4820   LoadSDNode *LDBase = nullptr;
4821   unsigned LastLoadedElt = -1U;
4822
4823   // For each element in the initializer, see if we've found a load or an undef.
4824   // If we don't find an initial load element, or later load elements are
4825   // non-consecutive, bail out.
4826   for (unsigned i = 0; i < NumElems; ++i) {
4827     SDValue Elt = Elts[i];
4828     // Look through a bitcast.
4829     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4830       Elt = Elt.getOperand(0);
4831     if (!Elt.getNode() ||
4832         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4833       return SDValue();
4834     if (!LDBase) {
4835       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4836         return SDValue();
4837       LDBase = cast<LoadSDNode>(Elt.getNode());
4838       LastLoadedElt = i;
4839       continue;
4840     }
4841     if (Elt.getOpcode() == ISD::UNDEF)
4842       continue;
4843
4844     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4845     EVT LdVT = Elt.getValueType();
4846     // Each loaded element must be the correct fractional portion of the
4847     // requested vector load.
4848     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4849       return SDValue();
4850     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4851       return SDValue();
4852     LastLoadedElt = i;
4853   }
4854
4855   // If we have found an entire vector of loads and undefs, then return a large
4856   // load of the entire vector width starting at the base pointer.  If we found
4857   // consecutive loads for the low half, generate a vzext_load node.
4858   if (LastLoadedElt == NumElems - 1) {
4859     assert(LDBase && "Did not find base load for merging consecutive loads");
4860     EVT EltVT = LDBase->getValueType(0);
4861     // Ensure that the input vector size for the merged loads matches the
4862     // cumulative size of the input elements.
4863     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4864       return SDValue();
4865
4866     if (isAfterLegalize &&
4867         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4868       return SDValue();
4869
4870     SDValue NewLd = SDValue();
4871
4872     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4873                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4874                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4875                         LDBase->getAlignment());
4876
4877     if (LDBase->hasAnyUseOfValue(1)) {
4878       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4879                                      SDValue(LDBase, 1),
4880                                      SDValue(NewLd.getNode(), 1));
4881       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4882       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4883                              SDValue(NewLd.getNode(), 1));
4884     }
4885
4886     return NewLd;
4887   }
4888
4889   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4890   //of a v4i32 / v4f32. It's probably worth generalizing.
4891   EVT EltVT = VT.getVectorElementType();
4892   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4893       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4894     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4895     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4896     SDValue ResNode =
4897         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4898                                 LDBase->getPointerInfo(),
4899                                 LDBase->getAlignment(),
4900                                 false/*isVolatile*/, true/*ReadMem*/,
4901                                 false/*WriteMem*/);
4902
4903     // Make sure the newly-created LOAD is in the same position as LDBase in
4904     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4905     // update uses of LDBase's output chain to use the TokenFactor.
4906     if (LDBase->hasAnyUseOfValue(1)) {
4907       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4908                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4909       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4910       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4911                              SDValue(ResNode.getNode(), 1));
4912     }
4913
4914     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4915   }
4916   return SDValue();
4917 }
4918
4919 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4920 /// to generate a splat value for the following cases:
4921 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4922 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4923 /// a scalar load, or a constant.
4924 /// The VBROADCAST node is returned when a pattern is found,
4925 /// or SDValue() otherwise.
4926 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4927                                     SelectionDAG &DAG) {
4928   // VBROADCAST requires AVX.
4929   // TODO: Splats could be generated for non-AVX CPUs using SSE
4930   // instructions, but there's less potential gain for only 128-bit vectors.
4931   if (!Subtarget->hasAVX())
4932     return SDValue();
4933
4934   MVT VT = Op.getSimpleValueType();
4935   SDLoc dl(Op);
4936
4937   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4938          "Unsupported vector type for broadcast.");
4939
4940   SDValue Ld;
4941   bool ConstSplatVal;
4942
4943   switch (Op.getOpcode()) {
4944     default:
4945       // Unknown pattern found.
4946       return SDValue();
4947
4948     case ISD::BUILD_VECTOR: {
4949       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4950       BitVector UndefElements;
4951       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4952
4953       // We need a splat of a single value to use broadcast, and it doesn't
4954       // make any sense if the value is only in one element of the vector.
4955       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4956         return SDValue();
4957
4958       Ld = Splat;
4959       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4960                        Ld.getOpcode() == ISD::ConstantFP);
4961
4962       // Make sure that all of the users of a non-constant load are from the
4963       // BUILD_VECTOR node.
4964       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4965         return SDValue();
4966       break;
4967     }
4968
4969     case ISD::VECTOR_SHUFFLE: {
4970       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4971
4972       // Shuffles must have a splat mask where the first element is
4973       // broadcasted.
4974       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4975         return SDValue();
4976
4977       SDValue Sc = Op.getOperand(0);
4978       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4979           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4980
4981         if (!Subtarget->hasInt256())
4982           return SDValue();
4983
4984         // Use the register form of the broadcast instruction available on AVX2.
4985         if (VT.getSizeInBits() >= 256)
4986           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4987         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4988       }
4989
4990       Ld = Sc.getOperand(0);
4991       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4992                        Ld.getOpcode() == ISD::ConstantFP);
4993
4994       // The scalar_to_vector node and the suspected
4995       // load node must have exactly one user.
4996       // Constants may have multiple users.
4997
4998       // AVX-512 has register version of the broadcast
4999       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5000         Ld.getValueType().getSizeInBits() >= 32;
5001       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5002           !hasRegVer))
5003         return SDValue();
5004       break;
5005     }
5006   }
5007
5008   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5009   bool IsGE256 = (VT.getSizeInBits() >= 256);
5010
5011   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5012   // instruction to save 8 or more bytes of constant pool data.
5013   // TODO: If multiple splats are generated to load the same constant,
5014   // it may be detrimental to overall size. There needs to be a way to detect
5015   // that condition to know if this is truly a size win.
5016   const Function *F = DAG.getMachineFunction().getFunction();
5017   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5018
5019   // Handle broadcasting a single constant scalar from the constant pool
5020   // into a vector.
5021   // On Sandybridge (no AVX2), it is still better to load a constant vector
5022   // from the constant pool and not to broadcast it from a scalar.
5023   // But override that restriction when optimizing for size.
5024   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5025   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5026     EVT CVT = Ld.getValueType();
5027     assert(!CVT.isVector() && "Must not broadcast a vector type");
5028
5029     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5030     // For size optimization, also splat v2f64 and v2i64, and for size opt
5031     // with AVX2, also splat i8 and i16.
5032     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5033     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5034         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5035       const Constant *C = nullptr;
5036       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5037         C = CI->getConstantIntValue();
5038       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5039         C = CF->getConstantFPValue();
5040
5041       assert(C && "Invalid constant type");
5042
5043       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5044       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5045       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5046       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5047                        MachinePointerInfo::getConstantPool(),
5048                        false, false, false, Alignment);
5049
5050       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5051     }
5052   }
5053
5054   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5055
5056   // Handle AVX2 in-register broadcasts.
5057   if (!IsLoad && Subtarget->hasInt256() &&
5058       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5059     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5060
5061   // The scalar source must be a normal load.
5062   if (!IsLoad)
5063     return SDValue();
5064
5065   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5066       (Subtarget->hasVLX() && ScalarSize == 64))
5067     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5068
5069   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5070   // double since there is no vbroadcastsd xmm
5071   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5072     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5073       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5074   }
5075
5076   // Unsupported broadcast.
5077   return SDValue();
5078 }
5079
5080 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5081 /// underlying vector and index.
5082 ///
5083 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5084 /// index.
5085 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5086                                          SDValue ExtIdx) {
5087   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5088   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5089     return Idx;
5090
5091   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5092   // lowered this:
5093   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5094   // to:
5095   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5096   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5097   //                           undef)
5098   //                       Constant<0>)
5099   // In this case the vector is the extract_subvector expression and the index
5100   // is 2, as specified by the shuffle.
5101   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5102   SDValue ShuffleVec = SVOp->getOperand(0);
5103   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5104   assert(ShuffleVecVT.getVectorElementType() ==
5105          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5106
5107   int ShuffleIdx = SVOp->getMaskElt(Idx);
5108   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5109     ExtractedFromVec = ShuffleVec;
5110     return ShuffleIdx;
5111   }
5112   return Idx;
5113 }
5114
5115 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5116   MVT VT = Op.getSimpleValueType();
5117
5118   // Skip if insert_vec_elt is not supported.
5119   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5120   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5121     return SDValue();
5122
5123   SDLoc DL(Op);
5124   unsigned NumElems = Op.getNumOperands();
5125
5126   SDValue VecIn1;
5127   SDValue VecIn2;
5128   SmallVector<unsigned, 4> InsertIndices;
5129   SmallVector<int, 8> Mask(NumElems, -1);
5130
5131   for (unsigned i = 0; i != NumElems; ++i) {
5132     unsigned Opc = Op.getOperand(i).getOpcode();
5133
5134     if (Opc == ISD::UNDEF)
5135       continue;
5136
5137     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5138       // Quit if more than 1 elements need inserting.
5139       if (InsertIndices.size() > 1)
5140         return SDValue();
5141
5142       InsertIndices.push_back(i);
5143       continue;
5144     }
5145
5146     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5147     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5148     // Quit if non-constant index.
5149     if (!isa<ConstantSDNode>(ExtIdx))
5150       return SDValue();
5151     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5152
5153     // Quit if extracted from vector of different type.
5154     if (ExtractedFromVec.getValueType() != VT)
5155       return SDValue();
5156
5157     if (!VecIn1.getNode())
5158       VecIn1 = ExtractedFromVec;
5159     else if (VecIn1 != ExtractedFromVec) {
5160       if (!VecIn2.getNode())
5161         VecIn2 = ExtractedFromVec;
5162       else if (VecIn2 != ExtractedFromVec)
5163         // Quit if more than 2 vectors to shuffle
5164         return SDValue();
5165     }
5166
5167     if (ExtractedFromVec == VecIn1)
5168       Mask[i] = Idx;
5169     else if (ExtractedFromVec == VecIn2)
5170       Mask[i] = Idx + NumElems;
5171   }
5172
5173   if (!VecIn1.getNode())
5174     return SDValue();
5175
5176   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5177   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5178   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5179     unsigned Idx = InsertIndices[i];
5180     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5181                      DAG.getIntPtrConstant(Idx, DL));
5182   }
5183
5184   return NV;
5185 }
5186
5187 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5188 SDValue
5189 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5190
5191   MVT VT = Op.getSimpleValueType();
5192   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5193          "Unexpected type in LowerBUILD_VECTORvXi1!");
5194
5195   SDLoc dl(Op);
5196   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5197     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5198     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5199     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5200   }
5201
5202   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5203     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5204     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5205     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5206   }
5207
5208   bool AllContants = true;
5209   uint64_t Immediate = 0;
5210   int NonConstIdx = -1;
5211   bool IsSplat = true;
5212   unsigned NumNonConsts = 0;
5213   unsigned NumConsts = 0;
5214   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5215     SDValue In = Op.getOperand(idx);
5216     if (In.getOpcode() == ISD::UNDEF)
5217       continue;
5218     if (!isa<ConstantSDNode>(In)) {
5219       AllContants = false;
5220       NonConstIdx = idx;
5221       NumNonConsts++;
5222     } else {
5223       NumConsts++;
5224       if (cast<ConstantSDNode>(In)->getZExtValue())
5225       Immediate |= (1ULL << idx);
5226     }
5227     if (In != Op.getOperand(0))
5228       IsSplat = false;
5229   }
5230
5231   if (AllContants) {
5232     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5233       DAG.getConstant(Immediate, dl, MVT::i16));
5234     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5235                        DAG.getIntPtrConstant(0, dl));
5236   }
5237
5238   if (NumNonConsts == 1 && NonConstIdx != 0) {
5239     SDValue DstVec;
5240     if (NumConsts) {
5241       SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5242                                          MVT::getIntegerVT(VT.getSizeInBits()));
5243       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5244     }
5245     else
5246       DstVec = DAG.getUNDEF(VT);
5247     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5248                        Op.getOperand(NonConstIdx),
5249                        DAG.getIntPtrConstant(NonConstIdx, dl));
5250   }
5251   if (!IsSplat && (NonConstIdx != 0))
5252     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5253   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5254   SDValue Select;
5255   if (IsSplat)
5256     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5257                           DAG.getConstant(-1, dl, SelectVT),
5258                           DAG.getConstant(0, dl, SelectVT));
5259   else
5260     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5261                          DAG.getConstant((Immediate | 1), dl, SelectVT),
5262                          DAG.getConstant(Immediate, dl, SelectVT));
5263   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5264 }
5265
5266 /// \brief Return true if \p N implements a horizontal binop and return the
5267 /// operands for the horizontal binop into V0 and V1.
5268 ///
5269 /// This is a helper function of LowerToHorizontalOp().
5270 /// This function checks that the build_vector \p N in input implements a
5271 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5272 /// operation to match.
5273 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5274 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5275 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5276 /// arithmetic sub.
5277 ///
5278 /// This function only analyzes elements of \p N whose indices are
5279 /// in range [BaseIdx, LastIdx).
5280 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5281                               SelectionDAG &DAG,
5282                               unsigned BaseIdx, unsigned LastIdx,
5283                               SDValue &V0, SDValue &V1) {
5284   EVT VT = N->getValueType(0);
5285
5286   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5287   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5288          "Invalid Vector in input!");
5289
5290   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5291   bool CanFold = true;
5292   unsigned ExpectedVExtractIdx = BaseIdx;
5293   unsigned NumElts = LastIdx - BaseIdx;
5294   V0 = DAG.getUNDEF(VT);
5295   V1 = DAG.getUNDEF(VT);
5296
5297   // Check if N implements a horizontal binop.
5298   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5299     SDValue Op = N->getOperand(i + BaseIdx);
5300
5301     // Skip UNDEFs.
5302     if (Op->getOpcode() == ISD::UNDEF) {
5303       // Update the expected vector extract index.
5304       if (i * 2 == NumElts)
5305         ExpectedVExtractIdx = BaseIdx;
5306       ExpectedVExtractIdx += 2;
5307       continue;
5308     }
5309
5310     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5311
5312     if (!CanFold)
5313       break;
5314
5315     SDValue Op0 = Op.getOperand(0);
5316     SDValue Op1 = Op.getOperand(1);
5317
5318     // Try to match the following pattern:
5319     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5320     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5321         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5322         Op0.getOperand(0) == Op1.getOperand(0) &&
5323         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5324         isa<ConstantSDNode>(Op1.getOperand(1)));
5325     if (!CanFold)
5326       break;
5327
5328     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5329     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5330
5331     if (i * 2 < NumElts) {
5332       if (V0.getOpcode() == ISD::UNDEF) {
5333         V0 = Op0.getOperand(0);
5334         if (V0.getValueType() != VT)
5335           return false;
5336       }
5337     } else {
5338       if (V1.getOpcode() == ISD::UNDEF) {
5339         V1 = Op0.getOperand(0);
5340         if (V1.getValueType() != VT)
5341           return false;
5342       }
5343       if (i * 2 == NumElts)
5344         ExpectedVExtractIdx = BaseIdx;
5345     }
5346
5347     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5348     if (I0 == ExpectedVExtractIdx)
5349       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5350     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5351       // Try to match the following dag sequence:
5352       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5353       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5354     } else
5355       CanFold = false;
5356
5357     ExpectedVExtractIdx += 2;
5358   }
5359
5360   return CanFold;
5361 }
5362
5363 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5364 /// a concat_vector.
5365 ///
5366 /// This is a helper function of LowerToHorizontalOp().
5367 /// This function expects two 256-bit vectors called V0 and V1.
5368 /// At first, each vector is split into two separate 128-bit vectors.
5369 /// Then, the resulting 128-bit vectors are used to implement two
5370 /// horizontal binary operations.
5371 ///
5372 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5373 ///
5374 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5375 /// the two new horizontal binop.
5376 /// When Mode is set, the first horizontal binop dag node would take as input
5377 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5378 /// horizontal binop dag node would take as input the lower 128-bit of V1
5379 /// and the upper 128-bit of V1.
5380 ///   Example:
5381 ///     HADD V0_LO, V0_HI
5382 ///     HADD V1_LO, V1_HI
5383 ///
5384 /// Otherwise, the first horizontal binop dag node takes as input the lower
5385 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5386 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5387 ///   Example:
5388 ///     HADD V0_LO, V1_LO
5389 ///     HADD V0_HI, V1_HI
5390 ///
5391 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5392 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5393 /// the upper 128-bits of the result.
5394 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5395                                      SDLoc DL, SelectionDAG &DAG,
5396                                      unsigned X86Opcode, bool Mode,
5397                                      bool isUndefLO, bool isUndefHI) {
5398   EVT VT = V0.getValueType();
5399   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5400          "Invalid nodes in input!");
5401
5402   unsigned NumElts = VT.getVectorNumElements();
5403   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5404   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5405   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5406   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5407   EVT NewVT = V0_LO.getValueType();
5408
5409   SDValue LO = DAG.getUNDEF(NewVT);
5410   SDValue HI = DAG.getUNDEF(NewVT);
5411
5412   if (Mode) {
5413     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5414     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5415       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5416     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5417       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5418   } else {
5419     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5420     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5421                        V1_LO->getOpcode() != ISD::UNDEF))
5422       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5423
5424     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5425                        V1_HI->getOpcode() != ISD::UNDEF))
5426       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5427   }
5428
5429   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5430 }
5431
5432 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5433 /// node.
5434 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5435                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5436   EVT VT = BV->getValueType(0);
5437   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5438       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5439     return SDValue();
5440
5441   SDLoc DL(BV);
5442   unsigned NumElts = VT.getVectorNumElements();
5443   SDValue InVec0 = DAG.getUNDEF(VT);
5444   SDValue InVec1 = DAG.getUNDEF(VT);
5445
5446   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5447           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5448
5449   // Odd-numbered elements in the input build vector are obtained from
5450   // adding two integer/float elements.
5451   // Even-numbered elements in the input build vector are obtained from
5452   // subtracting two integer/float elements.
5453   unsigned ExpectedOpcode = ISD::FSUB;
5454   unsigned NextExpectedOpcode = ISD::FADD;
5455   bool AddFound = false;
5456   bool SubFound = false;
5457
5458   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5459     SDValue Op = BV->getOperand(i);
5460
5461     // Skip 'undef' values.
5462     unsigned Opcode = Op.getOpcode();
5463     if (Opcode == ISD::UNDEF) {
5464       std::swap(ExpectedOpcode, NextExpectedOpcode);
5465       continue;
5466     }
5467
5468     // Early exit if we found an unexpected opcode.
5469     if (Opcode != ExpectedOpcode)
5470       return SDValue();
5471
5472     SDValue Op0 = Op.getOperand(0);
5473     SDValue Op1 = Op.getOperand(1);
5474
5475     // Try to match the following pattern:
5476     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5477     // Early exit if we cannot match that sequence.
5478     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5479         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5480         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5481         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5482         Op0.getOperand(1) != Op1.getOperand(1))
5483       return SDValue();
5484
5485     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5486     if (I0 != i)
5487       return SDValue();
5488
5489     // We found a valid add/sub node. Update the information accordingly.
5490     if (i & 1)
5491       AddFound = true;
5492     else
5493       SubFound = true;
5494
5495     // Update InVec0 and InVec1.
5496     if (InVec0.getOpcode() == ISD::UNDEF) {
5497       InVec0 = Op0.getOperand(0);
5498       if (InVec0.getValueType() != VT)
5499         return SDValue();
5500     }
5501     if (InVec1.getOpcode() == ISD::UNDEF) {
5502       InVec1 = Op1.getOperand(0);
5503       if (InVec1.getValueType() != VT)
5504         return SDValue();
5505     }
5506
5507     // Make sure that operands in input to each add/sub node always
5508     // come from a same pair of vectors.
5509     if (InVec0 != Op0.getOperand(0)) {
5510       if (ExpectedOpcode == ISD::FSUB)
5511         return SDValue();
5512
5513       // FADD is commutable. Try to commute the operands
5514       // and then test again.
5515       std::swap(Op0, Op1);
5516       if (InVec0 != Op0.getOperand(0))
5517         return SDValue();
5518     }
5519
5520     if (InVec1 != Op1.getOperand(0))
5521       return SDValue();
5522
5523     // Update the pair of expected opcodes.
5524     std::swap(ExpectedOpcode, NextExpectedOpcode);
5525   }
5526
5527   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5528   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5529       InVec1.getOpcode() != ISD::UNDEF)
5530     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5531
5532   return SDValue();
5533 }
5534
5535 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5536 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5537                                    const X86Subtarget *Subtarget,
5538                                    SelectionDAG &DAG) {
5539   EVT VT = BV->getValueType(0);
5540   unsigned NumElts = VT.getVectorNumElements();
5541   unsigned NumUndefsLO = 0;
5542   unsigned NumUndefsHI = 0;
5543   unsigned Half = NumElts/2;
5544
5545   // Count the number of UNDEF operands in the build_vector in input.
5546   for (unsigned i = 0, e = Half; i != e; ++i)
5547     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5548       NumUndefsLO++;
5549
5550   for (unsigned i = Half, e = NumElts; i != e; ++i)
5551     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5552       NumUndefsHI++;
5553
5554   // Early exit if this is either a build_vector of all UNDEFs or all the
5555   // operands but one are UNDEF.
5556   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5557     return SDValue();
5558
5559   SDLoc DL(BV);
5560   SDValue InVec0, InVec1;
5561   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5562     // Try to match an SSE3 float HADD/HSUB.
5563     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5564       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5565
5566     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5567       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5568   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5569     // Try to match an SSSE3 integer HADD/HSUB.
5570     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5571       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5572
5573     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5574       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5575   }
5576
5577   if (!Subtarget->hasAVX())
5578     return SDValue();
5579
5580   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5581     // Try to match an AVX horizontal add/sub of packed single/double
5582     // precision floating point values from 256-bit vectors.
5583     SDValue InVec2, InVec3;
5584     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5585         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5586         ((InVec0.getOpcode() == ISD::UNDEF ||
5587           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5588         ((InVec1.getOpcode() == ISD::UNDEF ||
5589           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5590       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5591
5592     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5593         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5594         ((InVec0.getOpcode() == ISD::UNDEF ||
5595           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5596         ((InVec1.getOpcode() == ISD::UNDEF ||
5597           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5598       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5599   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5600     // Try to match an AVX2 horizontal add/sub of signed integers.
5601     SDValue InVec2, InVec3;
5602     unsigned X86Opcode;
5603     bool CanFold = true;
5604
5605     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5606         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5607         ((InVec0.getOpcode() == ISD::UNDEF ||
5608           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5609         ((InVec1.getOpcode() == ISD::UNDEF ||
5610           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5611       X86Opcode = X86ISD::HADD;
5612     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5613         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5614         ((InVec0.getOpcode() == ISD::UNDEF ||
5615           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5616         ((InVec1.getOpcode() == ISD::UNDEF ||
5617           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5618       X86Opcode = X86ISD::HSUB;
5619     else
5620       CanFold = false;
5621
5622     if (CanFold) {
5623       // Fold this build_vector into a single horizontal add/sub.
5624       // Do this only if the target has AVX2.
5625       if (Subtarget->hasAVX2())
5626         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5627
5628       // Do not try to expand this build_vector into a pair of horizontal
5629       // add/sub if we can emit a pair of scalar add/sub.
5630       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5631         return SDValue();
5632
5633       // Convert this build_vector into a pair of horizontal binop followed by
5634       // a concat vector.
5635       bool isUndefLO = NumUndefsLO == Half;
5636       bool isUndefHI = NumUndefsHI == Half;
5637       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5638                                    isUndefLO, isUndefHI);
5639     }
5640   }
5641
5642   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5643        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5644     unsigned X86Opcode;
5645     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5646       X86Opcode = X86ISD::HADD;
5647     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5648       X86Opcode = X86ISD::HSUB;
5649     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5650       X86Opcode = X86ISD::FHADD;
5651     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5652       X86Opcode = X86ISD::FHSUB;
5653     else
5654       return SDValue();
5655
5656     // Don't try to expand this build_vector into a pair of horizontal add/sub
5657     // if we can simply emit a pair of scalar add/sub.
5658     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5659       return SDValue();
5660
5661     // Convert this build_vector into two horizontal add/sub followed by
5662     // a concat vector.
5663     bool isUndefLO = NumUndefsLO == Half;
5664     bool isUndefHI = NumUndefsHI == Half;
5665     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5666                                  isUndefLO, isUndefHI);
5667   }
5668
5669   return SDValue();
5670 }
5671
5672 SDValue
5673 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5674   SDLoc dl(Op);
5675
5676   MVT VT = Op.getSimpleValueType();
5677   MVT ExtVT = VT.getVectorElementType();
5678   unsigned NumElems = Op.getNumOperands();
5679
5680   // Generate vectors for predicate vectors.
5681   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5682     return LowerBUILD_VECTORvXi1(Op, DAG);
5683
5684   // Vectors containing all zeros can be matched by pxor and xorps later
5685   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5686     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5687     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5688     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5689       return Op;
5690
5691     return getZeroVector(VT, Subtarget, DAG, dl);
5692   }
5693
5694   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5695   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5696   // vpcmpeqd on 256-bit vectors.
5697   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5698     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5699       return Op;
5700
5701     if (!VT.is512BitVector())
5702       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5703   }
5704
5705   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5706   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5707     return AddSub;
5708   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5709     return HorizontalOp;
5710   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5711     return Broadcast;
5712
5713   unsigned EVTBits = ExtVT.getSizeInBits();
5714
5715   unsigned NumZero  = 0;
5716   unsigned NumNonZero = 0;
5717   unsigned NonZeros = 0;
5718   bool IsAllConstants = true;
5719   SmallSet<SDValue, 8> Values;
5720   for (unsigned i = 0; i < NumElems; ++i) {
5721     SDValue Elt = Op.getOperand(i);
5722     if (Elt.getOpcode() == ISD::UNDEF)
5723       continue;
5724     Values.insert(Elt);
5725     if (Elt.getOpcode() != ISD::Constant &&
5726         Elt.getOpcode() != ISD::ConstantFP)
5727       IsAllConstants = false;
5728     if (X86::isZeroNode(Elt))
5729       NumZero++;
5730     else {
5731       NonZeros |= (1 << i);
5732       NumNonZero++;
5733     }
5734   }
5735
5736   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5737   if (NumNonZero == 0)
5738     return DAG.getUNDEF(VT);
5739
5740   // Special case for single non-zero, non-undef, element.
5741   if (NumNonZero == 1) {
5742     unsigned Idx = countTrailingZeros(NonZeros);
5743     SDValue Item = Op.getOperand(Idx);
5744
5745     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5746     // the value are obviously zero, truncate the value to i32 and do the
5747     // insertion that way.  Only do this if the value is non-constant or if the
5748     // value is a constant being inserted into element 0.  It is cheaper to do
5749     // a constant pool load than it is to do a movd + shuffle.
5750     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5751         (!IsAllConstants || Idx == 0)) {
5752       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5753         // Handle SSE only.
5754         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5755         EVT VecVT = MVT::v4i32;
5756
5757         // Truncate the value (which may itself be a constant) to i32, and
5758         // convert it to a vector with movd (S2V+shuffle to zero extend).
5759         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5760         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5761         return DAG.getNode(
5762             ISD::BITCAST, dl, VT,
5763             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5764       }
5765     }
5766
5767     // If we have a constant or non-constant insertion into the low element of
5768     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5769     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5770     // depending on what the source datatype is.
5771     if (Idx == 0) {
5772       if (NumZero == 0)
5773         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5774
5775       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5776           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5777         if (VT.is512BitVector()) {
5778           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5779           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5780                              Item, DAG.getIntPtrConstant(0, dl));
5781         }
5782         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5783                "Expected an SSE value type!");
5784         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5785         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5786         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5787       }
5788
5789       // We can't directly insert an i8 or i16 into a vector, so zero extend
5790       // it to i32 first.
5791       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5792         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5793         if (VT.is256BitVector()) {
5794           if (Subtarget->hasAVX()) {
5795             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5796             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5797           } else {
5798             // Without AVX, we need to extend to a 128-bit vector and then
5799             // insert into the 256-bit vector.
5800             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5801             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5802             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5803           }
5804         } else {
5805           assert(VT.is128BitVector() && "Expected an SSE value type!");
5806           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5807           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5808         }
5809         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5810       }
5811     }
5812
5813     // Is it a vector logical left shift?
5814     if (NumElems == 2 && Idx == 1 &&
5815         X86::isZeroNode(Op.getOperand(0)) &&
5816         !X86::isZeroNode(Op.getOperand(1))) {
5817       unsigned NumBits = VT.getSizeInBits();
5818       return getVShift(true, VT,
5819                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5820                                    VT, Op.getOperand(1)),
5821                        NumBits/2, DAG, *this, dl);
5822     }
5823
5824     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5825       return SDValue();
5826
5827     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5828     // is a non-constant being inserted into an element other than the low one,
5829     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5830     // movd/movss) to move this into the low element, then shuffle it into
5831     // place.
5832     if (EVTBits == 32) {
5833       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5834       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5835     }
5836   }
5837
5838   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5839   if (Values.size() == 1) {
5840     if (EVTBits == 32) {
5841       // Instead of a shuffle like this:
5842       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5843       // Check if it's possible to issue this instead.
5844       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5845       unsigned Idx = countTrailingZeros(NonZeros);
5846       SDValue Item = Op.getOperand(Idx);
5847       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5848         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5849     }
5850     return SDValue();
5851   }
5852
5853   // A vector full of immediates; various special cases are already
5854   // handled, so this is best done with a single constant-pool load.
5855   if (IsAllConstants)
5856     return SDValue();
5857
5858   // For AVX-length vectors, see if we can use a vector load to get all of the
5859   // elements, otherwise build the individual 128-bit pieces and use
5860   // shuffles to put them in place.
5861   if (VT.is256BitVector() || VT.is512BitVector()) {
5862     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5863
5864     // Check for a build vector of consecutive loads.
5865     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5866       return LD;
5867
5868     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5869
5870     // Build both the lower and upper subvector.
5871     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5872                                 makeArrayRef(&V[0], NumElems/2));
5873     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5874                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5875
5876     // Recreate the wider vector with the lower and upper part.
5877     if (VT.is256BitVector())
5878       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5879     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5880   }
5881
5882   // Let legalizer expand 2-wide build_vectors.
5883   if (EVTBits == 64) {
5884     if (NumNonZero == 1) {
5885       // One half is zero or undef.
5886       unsigned Idx = countTrailingZeros(NonZeros);
5887       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5888                                  Op.getOperand(Idx));
5889       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5890     }
5891     return SDValue();
5892   }
5893
5894   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5895   if (EVTBits == 8 && NumElems == 16)
5896     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5897                                         Subtarget, *this))
5898       return V;
5899
5900   if (EVTBits == 16 && NumElems == 8)
5901     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5902                                       Subtarget, *this))
5903       return V;
5904
5905   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5906   if (EVTBits == 32 && NumElems == 4)
5907     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5908       return V;
5909
5910   // If element VT is == 32 bits, turn it into a number of shuffles.
5911   SmallVector<SDValue, 8> V(NumElems);
5912   if (NumElems == 4 && NumZero > 0) {
5913     for (unsigned i = 0; i < 4; ++i) {
5914       bool isZero = !(NonZeros & (1 << i));
5915       if (isZero)
5916         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5917       else
5918         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5919     }
5920
5921     for (unsigned i = 0; i < 2; ++i) {
5922       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5923         default: break;
5924         case 0:
5925           V[i] = V[i*2];  // Must be a zero vector.
5926           break;
5927         case 1:
5928           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5929           break;
5930         case 2:
5931           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5932           break;
5933         case 3:
5934           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5935           break;
5936       }
5937     }
5938
5939     bool Reverse1 = (NonZeros & 0x3) == 2;
5940     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5941     int MaskVec[] = {
5942       Reverse1 ? 1 : 0,
5943       Reverse1 ? 0 : 1,
5944       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5945       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5946     };
5947     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5948   }
5949
5950   if (Values.size() > 1 && VT.is128BitVector()) {
5951     // Check for a build vector of consecutive loads.
5952     for (unsigned i = 0; i < NumElems; ++i)
5953       V[i] = Op.getOperand(i);
5954
5955     // Check for elements which are consecutive loads.
5956     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5957       return LD;
5958
5959     // Check for a build vector from mostly shuffle plus few inserting.
5960     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5961       return Sh;
5962
5963     // For SSE 4.1, use insertps to put the high elements into the low element.
5964     if (Subtarget->hasSSE41()) {
5965       SDValue Result;
5966       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5967         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5968       else
5969         Result = DAG.getUNDEF(VT);
5970
5971       for (unsigned i = 1; i < NumElems; ++i) {
5972         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5973         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5974                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5975       }
5976       return Result;
5977     }
5978
5979     // Otherwise, expand into a number of unpckl*, start by extending each of
5980     // our (non-undef) elements to the full vector width with the element in the
5981     // bottom slot of the vector (which generates no code for SSE).
5982     for (unsigned i = 0; i < NumElems; ++i) {
5983       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5984         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5985       else
5986         V[i] = DAG.getUNDEF(VT);
5987     }
5988
5989     // Next, we iteratively mix elements, e.g. for v4f32:
5990     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5991     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5992     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5993     unsigned EltStride = NumElems >> 1;
5994     while (EltStride != 0) {
5995       for (unsigned i = 0; i < EltStride; ++i) {
5996         // If V[i+EltStride] is undef and this is the first round of mixing,
5997         // then it is safe to just drop this shuffle: V[i] is already in the
5998         // right place, the one element (since it's the first round) being
5999         // inserted as undef can be dropped.  This isn't safe for successive
6000         // rounds because they will permute elements within both vectors.
6001         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6002             EltStride == NumElems/2)
6003           continue;
6004
6005         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6006       }
6007       EltStride >>= 1;
6008     }
6009     return V[0];
6010   }
6011   return SDValue();
6012 }
6013
6014 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6015 // to create 256-bit vectors from two other 128-bit ones.
6016 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6017   SDLoc dl(Op);
6018   MVT ResVT = Op.getSimpleValueType();
6019
6020   assert((ResVT.is256BitVector() ||
6021           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6022
6023   SDValue V1 = Op.getOperand(0);
6024   SDValue V2 = Op.getOperand(1);
6025   unsigned NumElems = ResVT.getVectorNumElements();
6026   if (ResVT.is256BitVector())
6027     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6028
6029   if (Op.getNumOperands() == 4) {
6030     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6031                                 ResVT.getVectorNumElements()/2);
6032     SDValue V3 = Op.getOperand(2);
6033     SDValue V4 = Op.getOperand(3);
6034     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6035       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6036   }
6037   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6038 }
6039
6040 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6041                                        const X86Subtarget *Subtarget,
6042                                        SelectionDAG & DAG) {
6043   SDLoc dl(Op);
6044   MVT ResVT = Op.getSimpleValueType();
6045   unsigned NumOfOperands = Op.getNumOperands();
6046
6047   assert(isPowerOf2_32(NumOfOperands) &&
6048          "Unexpected number of operands in CONCAT_VECTORS");
6049
6050   if (NumOfOperands > 2) {
6051     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6052                                   ResVT.getVectorNumElements()/2);
6053     SmallVector<SDValue, 2> Ops;
6054     for (unsigned i = 0; i < NumOfOperands/2; i++)
6055       Ops.push_back(Op.getOperand(i));
6056     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6057     Ops.clear();
6058     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6059       Ops.push_back(Op.getOperand(i));
6060     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6061     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6062   }
6063
6064   SDValue V1 = Op.getOperand(0);
6065   SDValue V2 = Op.getOperand(1);
6066   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6067   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6068
6069   if (IsZeroV1 && IsZeroV2)
6070     return getZeroVector(ResVT, Subtarget, DAG, dl);
6071
6072   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6073   SDValue Undef = DAG.getUNDEF(ResVT);
6074   unsigned NumElems = ResVT.getVectorNumElements();
6075   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6076
6077   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6078   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6079   if (IsZeroV1)
6080     return V2;
6081
6082   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6083   // Zero the upper bits of V1
6084   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6085   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6086   if (IsZeroV2)
6087     return V1;
6088   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6089 }
6090
6091 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6092                                    const X86Subtarget *Subtarget,
6093                                    SelectionDAG &DAG) {
6094   MVT VT = Op.getSimpleValueType();
6095   if (VT.getVectorElementType() == MVT::i1)
6096     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6097
6098   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6099          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6100           Op.getNumOperands() == 4)));
6101
6102   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6103   // from two other 128-bit ones.
6104
6105   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6106   return LowerAVXCONCAT_VECTORS(Op, DAG);
6107 }
6108
6109
6110 //===----------------------------------------------------------------------===//
6111 // Vector shuffle lowering
6112 //
6113 // This is an experimental code path for lowering vector shuffles on x86. It is
6114 // designed to handle arbitrary vector shuffles and blends, gracefully
6115 // degrading performance as necessary. It works hard to recognize idiomatic
6116 // shuffles and lower them to optimal instruction patterns without leaving
6117 // a framework that allows reasonably efficient handling of all vector shuffle
6118 // patterns.
6119 //===----------------------------------------------------------------------===//
6120
6121 /// \brief Tiny helper function to identify a no-op mask.
6122 ///
6123 /// This is a somewhat boring predicate function. It checks whether the mask
6124 /// array input, which is assumed to be a single-input shuffle mask of the kind
6125 /// used by the X86 shuffle instructions (not a fully general
6126 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6127 /// in-place shuffle are 'no-op's.
6128 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6129   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6130     if (Mask[i] != -1 && Mask[i] != i)
6131       return false;
6132   return true;
6133 }
6134
6135 /// \brief Helper function to classify a mask as a single-input mask.
6136 ///
6137 /// This isn't a generic single-input test because in the vector shuffle
6138 /// lowering we canonicalize single inputs to be the first input operand. This
6139 /// means we can more quickly test for a single input by only checking whether
6140 /// an input from the second operand exists. We also assume that the size of
6141 /// mask corresponds to the size of the input vectors which isn't true in the
6142 /// fully general case.
6143 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6144   for (int M : Mask)
6145     if (M >= (int)Mask.size())
6146       return false;
6147   return true;
6148 }
6149
6150 /// \brief Test whether there are elements crossing 128-bit lanes in this
6151 /// shuffle mask.
6152 ///
6153 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6154 /// and we routinely test for these.
6155 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6156   int LaneSize = 128 / VT.getScalarSizeInBits();
6157   int Size = Mask.size();
6158   for (int i = 0; i < Size; ++i)
6159     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6160       return true;
6161   return false;
6162 }
6163
6164 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6165 ///
6166 /// This checks a shuffle mask to see if it is performing the same
6167 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6168 /// that it is also not lane-crossing. It may however involve a blend from the
6169 /// same lane of a second vector.
6170 ///
6171 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6172 /// non-trivial to compute in the face of undef lanes. The representation is
6173 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6174 /// entries from both V1 and V2 inputs to the wider mask.
6175 static bool
6176 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6177                                 SmallVectorImpl<int> &RepeatedMask) {
6178   int LaneSize = 128 / VT.getScalarSizeInBits();
6179   RepeatedMask.resize(LaneSize, -1);
6180   int Size = Mask.size();
6181   for (int i = 0; i < Size; ++i) {
6182     if (Mask[i] < 0)
6183       continue;
6184     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6185       // This entry crosses lanes, so there is no way to model this shuffle.
6186       return false;
6187
6188     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6189     if (RepeatedMask[i % LaneSize] == -1)
6190       // This is the first non-undef entry in this slot of a 128-bit lane.
6191       RepeatedMask[i % LaneSize] =
6192           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6193     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6194       // Found a mismatch with the repeated mask.
6195       return false;
6196   }
6197   return true;
6198 }
6199
6200 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6201 /// arguments.
6202 ///
6203 /// This is a fast way to test a shuffle mask against a fixed pattern:
6204 ///
6205 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6206 ///
6207 /// It returns true if the mask is exactly as wide as the argument list, and
6208 /// each element of the mask is either -1 (signifying undef) or the value given
6209 /// in the argument.
6210 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6211                                 ArrayRef<int> ExpectedMask) {
6212   if (Mask.size() != ExpectedMask.size())
6213     return false;
6214
6215   int Size = Mask.size();
6216
6217   // If the values are build vectors, we can look through them to find
6218   // equivalent inputs that make the shuffles equivalent.
6219   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6220   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6221
6222   for (int i = 0; i < Size; ++i)
6223     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6224       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6225       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6226       if (!MaskBV || !ExpectedBV ||
6227           MaskBV->getOperand(Mask[i] % Size) !=
6228               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6229         return false;
6230     }
6231
6232   return true;
6233 }
6234
6235 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6236 ///
6237 /// This helper function produces an 8-bit shuffle immediate corresponding to
6238 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6239 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6240 /// example.
6241 ///
6242 /// NB: We rely heavily on "undef" masks preserving the input lane.
6243 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6244                                           SelectionDAG &DAG) {
6245   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6246   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6247   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6248   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6249   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6250
6251   unsigned Imm = 0;
6252   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6253   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6254   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6255   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6256   return DAG.getConstant(Imm, DL, MVT::i8);
6257 }
6258
6259 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6260 ///
6261 /// This is used as a fallback approach when first class blend instructions are
6262 /// unavailable. Currently it is only suitable for integer vectors, but could
6263 /// be generalized for floating point vectors if desirable.
6264 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6265                                             SDValue V2, ArrayRef<int> Mask,
6266                                             SelectionDAG &DAG) {
6267   assert(VT.isInteger() && "Only supports integer vector types!");
6268   MVT EltVT = VT.getScalarType();
6269   int NumEltBits = EltVT.getSizeInBits();
6270   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6271   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6272                                     EltVT);
6273   SmallVector<SDValue, 16> MaskOps;
6274   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6275     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6276       return SDValue(); // Shuffled input!
6277     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6278   }
6279
6280   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6281   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6282   // We have to cast V2 around.
6283   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6284   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6285                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6286                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6287                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6288   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6289 }
6290
6291 /// \brief Try to emit a blend instruction for a shuffle.
6292 ///
6293 /// This doesn't do any checks for the availability of instructions for blending
6294 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6295 /// be matched in the backend with the type given. What it does check for is
6296 /// that the shuffle mask is in fact a blend.
6297 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6298                                          SDValue V2, ArrayRef<int> Mask,
6299                                          const X86Subtarget *Subtarget,
6300                                          SelectionDAG &DAG) {
6301   unsigned BlendMask = 0;
6302   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6303     if (Mask[i] >= Size) {
6304       if (Mask[i] != i + Size)
6305         return SDValue(); // Shuffled V2 input!
6306       BlendMask |= 1u << i;
6307       continue;
6308     }
6309     if (Mask[i] >= 0 && Mask[i] != i)
6310       return SDValue(); // Shuffled V1 input!
6311   }
6312   switch (VT.SimpleTy) {
6313   case MVT::v2f64:
6314   case MVT::v4f32:
6315   case MVT::v4f64:
6316   case MVT::v8f32:
6317     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6318                        DAG.getConstant(BlendMask, DL, MVT::i8));
6319
6320   case MVT::v4i64:
6321   case MVT::v8i32:
6322     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6323     // FALLTHROUGH
6324   case MVT::v2i64:
6325   case MVT::v4i32:
6326     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6327     // that instruction.
6328     if (Subtarget->hasAVX2()) {
6329       // Scale the blend by the number of 32-bit dwords per element.
6330       int Scale =  VT.getScalarSizeInBits() / 32;
6331       BlendMask = 0;
6332       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6333         if (Mask[i] >= Size)
6334           for (int j = 0; j < Scale; ++j)
6335             BlendMask |= 1u << (i * Scale + j);
6336
6337       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6338       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6339       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6340       return DAG.getNode(ISD::BITCAST, DL, VT,
6341                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6342                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6343     }
6344     // FALLTHROUGH
6345   case MVT::v8i16: {
6346     // For integer shuffles we need to expand the mask and cast the inputs to
6347     // v8i16s prior to blending.
6348     int Scale = 8 / VT.getVectorNumElements();
6349     BlendMask = 0;
6350     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6351       if (Mask[i] >= Size)
6352         for (int j = 0; j < Scale; ++j)
6353           BlendMask |= 1u << (i * Scale + j);
6354
6355     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6356     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6357     return DAG.getNode(ISD::BITCAST, DL, VT,
6358                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6359                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6360   }
6361
6362   case MVT::v16i16: {
6363     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6364     SmallVector<int, 8> RepeatedMask;
6365     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6366       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6367       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6368       BlendMask = 0;
6369       for (int i = 0; i < 8; ++i)
6370         if (RepeatedMask[i] >= 16)
6371           BlendMask |= 1u << i;
6372       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6373                          DAG.getConstant(BlendMask, DL, MVT::i8));
6374     }
6375   }
6376     // FALLTHROUGH
6377   case MVT::v16i8:
6378   case MVT::v32i8: {
6379     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6380            "256-bit byte-blends require AVX2 support!");
6381
6382     // Scale the blend by the number of bytes per element.
6383     int Scale = VT.getScalarSizeInBits() / 8;
6384
6385     // This form of blend is always done on bytes. Compute the byte vector
6386     // type.
6387     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6388
6389     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6390     // mix of LLVM's code generator and the x86 backend. We tell the code
6391     // generator that boolean values in the elements of an x86 vector register
6392     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6393     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6394     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6395     // of the element (the remaining are ignored) and 0 in that high bit would
6396     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6397     // the LLVM model for boolean values in vector elements gets the relevant
6398     // bit set, it is set backwards and over constrained relative to x86's
6399     // actual model.
6400     SmallVector<SDValue, 32> VSELECTMask;
6401     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6402       for (int j = 0; j < Scale; ++j)
6403         VSELECTMask.push_back(
6404             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6405                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6406                                           MVT::i8));
6407
6408     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6409     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6410     return DAG.getNode(
6411         ISD::BITCAST, DL, VT,
6412         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6413                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6414                     V1, V2));
6415   }
6416
6417   default:
6418     llvm_unreachable("Not a supported integer vector type!");
6419   }
6420 }
6421
6422 /// \brief Try to lower as a blend of elements from two inputs followed by
6423 /// a single-input permutation.
6424 ///
6425 /// This matches the pattern where we can blend elements from two inputs and
6426 /// then reduce the shuffle to a single-input permutation.
6427 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6428                                                    SDValue V2,
6429                                                    ArrayRef<int> Mask,
6430                                                    SelectionDAG &DAG) {
6431   // We build up the blend mask while checking whether a blend is a viable way
6432   // to reduce the shuffle.
6433   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6434   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6435
6436   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6437     if (Mask[i] < 0)
6438       continue;
6439
6440     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6441
6442     if (BlendMask[Mask[i] % Size] == -1)
6443       BlendMask[Mask[i] % Size] = Mask[i];
6444     else if (BlendMask[Mask[i] % Size] != Mask[i])
6445       return SDValue(); // Can't blend in the needed input!
6446
6447     PermuteMask[i] = Mask[i] % Size;
6448   }
6449
6450   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6451   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6452 }
6453
6454 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6455 /// blends and permutes.
6456 ///
6457 /// This matches the extremely common pattern for handling combined
6458 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6459 /// operations. It will try to pick the best arrangement of shuffles and
6460 /// blends.
6461 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6462                                                           SDValue V1,
6463                                                           SDValue V2,
6464                                                           ArrayRef<int> Mask,
6465                                                           SelectionDAG &DAG) {
6466   // Shuffle the input elements into the desired positions in V1 and V2 and
6467   // blend them together.
6468   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6469   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6470   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6471   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6472     if (Mask[i] >= 0 && Mask[i] < Size) {
6473       V1Mask[i] = Mask[i];
6474       BlendMask[i] = i;
6475     } else if (Mask[i] >= Size) {
6476       V2Mask[i] = Mask[i] - Size;
6477       BlendMask[i] = i + Size;
6478     }
6479
6480   // Try to lower with the simpler initial blend strategy unless one of the
6481   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6482   // shuffle may be able to fold with a load or other benefit. However, when
6483   // we'll have to do 2x as many shuffles in order to achieve this, blending
6484   // first is a better strategy.
6485   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6486     if (SDValue BlendPerm =
6487             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6488       return BlendPerm;
6489
6490   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6491   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6492   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6493 }
6494
6495 /// \brief Try to lower a vector shuffle as a byte rotation.
6496 ///
6497 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6498 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6499 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6500 /// try to generically lower a vector shuffle through such an pattern. It
6501 /// does not check for the profitability of lowering either as PALIGNR or
6502 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6503 /// This matches shuffle vectors that look like:
6504 ///
6505 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6506 ///
6507 /// Essentially it concatenates V1 and V2, shifts right by some number of
6508 /// elements, and takes the low elements as the result. Note that while this is
6509 /// specified as a *right shift* because x86 is little-endian, it is a *left
6510 /// rotate* of the vector lanes.
6511 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6512                                               SDValue V2,
6513                                               ArrayRef<int> Mask,
6514                                               const X86Subtarget *Subtarget,
6515                                               SelectionDAG &DAG) {
6516   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6517
6518   int NumElts = Mask.size();
6519   int NumLanes = VT.getSizeInBits() / 128;
6520   int NumLaneElts = NumElts / NumLanes;
6521
6522   // We need to detect various ways of spelling a rotation:
6523   //   [11, 12, 13, 14, 15,  0,  1,  2]
6524   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6525   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6526   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6527   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6528   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6529   int Rotation = 0;
6530   SDValue Lo, Hi;
6531   for (int l = 0; l < NumElts; l += NumLaneElts) {
6532     for (int i = 0; i < NumLaneElts; ++i) {
6533       if (Mask[l + i] == -1)
6534         continue;
6535       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6536
6537       // Get the mod-Size index and lane correct it.
6538       int LaneIdx = (Mask[l + i] % NumElts) - l;
6539       // Make sure it was in this lane.
6540       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6541         return SDValue();
6542
6543       // Determine where a rotated vector would have started.
6544       int StartIdx = i - LaneIdx;
6545       if (StartIdx == 0)
6546         // The identity rotation isn't interesting, stop.
6547         return SDValue();
6548
6549       // If we found the tail of a vector the rotation must be the missing
6550       // front. If we found the head of a vector, it must be how much of the
6551       // head.
6552       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6553
6554       if (Rotation == 0)
6555         Rotation = CandidateRotation;
6556       else if (Rotation != CandidateRotation)
6557         // The rotations don't match, so we can't match this mask.
6558         return SDValue();
6559
6560       // Compute which value this mask is pointing at.
6561       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6562
6563       // Compute which of the two target values this index should be assigned
6564       // to. This reflects whether the high elements are remaining or the low
6565       // elements are remaining.
6566       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6567
6568       // Either set up this value if we've not encountered it before, or check
6569       // that it remains consistent.
6570       if (!TargetV)
6571         TargetV = MaskV;
6572       else if (TargetV != MaskV)
6573         // This may be a rotation, but it pulls from the inputs in some
6574         // unsupported interleaving.
6575         return SDValue();
6576     }
6577   }
6578
6579   // Check that we successfully analyzed the mask, and normalize the results.
6580   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6581   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6582   if (!Lo)
6583     Lo = Hi;
6584   else if (!Hi)
6585     Hi = Lo;
6586
6587   // The actual rotate instruction rotates bytes, so we need to scale the
6588   // rotation based on how many bytes are in the vector lane.
6589   int Scale = 16 / NumLaneElts;
6590
6591   // SSSE3 targets can use the palignr instruction.
6592   if (Subtarget->hasSSSE3()) {
6593     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6594     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6595     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6596     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6597
6598     return DAG.getNode(ISD::BITCAST, DL, VT,
6599                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6600                                    DAG.getConstant(Rotation * Scale, DL,
6601                                                    MVT::i8)));
6602   }
6603
6604   assert(VT.getSizeInBits() == 128 &&
6605          "Rotate-based lowering only supports 128-bit lowering!");
6606   assert(Mask.size() <= 16 &&
6607          "Can shuffle at most 16 bytes in a 128-bit vector!");
6608
6609   // Default SSE2 implementation
6610   int LoByteShift = 16 - Rotation * Scale;
6611   int HiByteShift = Rotation * Scale;
6612
6613   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6614   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6615   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6616
6617   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6618                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6619   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6620                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6621   return DAG.getNode(ISD::BITCAST, DL, VT,
6622                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6623 }
6624
6625 /// \brief Compute whether each element of a shuffle is zeroable.
6626 ///
6627 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6628 /// Either it is an undef element in the shuffle mask, the element of the input
6629 /// referenced is undef, or the element of the input referenced is known to be
6630 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6631 /// as many lanes with this technique as possible to simplify the remaining
6632 /// shuffle.
6633 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6634                                                      SDValue V1, SDValue V2) {
6635   SmallBitVector Zeroable(Mask.size(), false);
6636
6637   while (V1.getOpcode() == ISD::BITCAST)
6638     V1 = V1->getOperand(0);
6639   while (V2.getOpcode() == ISD::BITCAST)
6640     V2 = V2->getOperand(0);
6641
6642   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6643   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6644
6645   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6646     int M = Mask[i];
6647     // Handle the easy cases.
6648     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6649       Zeroable[i] = true;
6650       continue;
6651     }
6652
6653     // If this is an index into a build_vector node (which has the same number
6654     // of elements), dig out the input value and use it.
6655     SDValue V = M < Size ? V1 : V2;
6656     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6657       continue;
6658
6659     SDValue Input = V.getOperand(M % Size);
6660     // The UNDEF opcode check really should be dead code here, but not quite
6661     // worth asserting on (it isn't invalid, just unexpected).
6662     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6663       Zeroable[i] = true;
6664   }
6665
6666   return Zeroable;
6667 }
6668
6669 /// \brief Try to emit a bitmask instruction for a shuffle.
6670 ///
6671 /// This handles cases where we can model a blend exactly as a bitmask due to
6672 /// one of the inputs being zeroable.
6673 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6674                                            SDValue V2, ArrayRef<int> Mask,
6675                                            SelectionDAG &DAG) {
6676   MVT EltVT = VT.getScalarType();
6677   int NumEltBits = EltVT.getSizeInBits();
6678   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6679   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6680   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6681                                     IntEltVT);
6682   if (EltVT.isFloatingPoint()) {
6683     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6684     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6685   }
6686   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6687   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6688   SDValue V;
6689   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6690     if (Zeroable[i])
6691       continue;
6692     if (Mask[i] % Size != i)
6693       return SDValue(); // Not a blend.
6694     if (!V)
6695       V = Mask[i] < Size ? V1 : V2;
6696     else if (V != (Mask[i] < Size ? V1 : V2))
6697       return SDValue(); // Can only let one input through the mask.
6698
6699     VMaskOps[i] = AllOnes;
6700   }
6701   if (!V)
6702     return SDValue(); // No non-zeroable elements!
6703
6704   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6705   V = DAG.getNode(VT.isFloatingPoint()
6706                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6707                   DL, VT, V, VMask);
6708   return V;
6709 }
6710
6711 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6712 ///
6713 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6714 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6715 /// matches elements from one of the input vectors shuffled to the left or
6716 /// right with zeroable elements 'shifted in'. It handles both the strictly
6717 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6718 /// quad word lane.
6719 ///
6720 /// PSHL : (little-endian) left bit shift.
6721 /// [ zz, 0, zz,  2 ]
6722 /// [ -1, 4, zz, -1 ]
6723 /// PSRL : (little-endian) right bit shift.
6724 /// [  1, zz,  3, zz]
6725 /// [ -1, -1,  7, zz]
6726 /// PSLLDQ : (little-endian) left byte shift
6727 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6728 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6729 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6730 /// PSRLDQ : (little-endian) right byte shift
6731 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6732 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6733 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6734 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6735                                          SDValue V2, ArrayRef<int> Mask,
6736                                          SelectionDAG &DAG) {
6737   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6738
6739   int Size = Mask.size();
6740   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6741
6742   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6743     for (int i = 0; i < Size; i += Scale)
6744       for (int j = 0; j < Shift; ++j)
6745         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6746           return false;
6747
6748     return true;
6749   };
6750
6751   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6752     for (int i = 0; i != Size; i += Scale) {
6753       unsigned Pos = Left ? i + Shift : i;
6754       unsigned Low = Left ? i : i + Shift;
6755       unsigned Len = Scale - Shift;
6756       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6757                                       Low + (V == V1 ? 0 : Size)))
6758         return SDValue();
6759     }
6760
6761     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6762     bool ByteShift = ShiftEltBits > 64;
6763     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6764                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6765     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6766
6767     // Normalize the scale for byte shifts to still produce an i64 element
6768     // type.
6769     Scale = ByteShift ? Scale / 2 : Scale;
6770
6771     // We need to round trip through the appropriate type for the shift.
6772     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6773     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6774     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6775            "Illegal integer vector type");
6776     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6777
6778     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6779                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6780     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6781   };
6782
6783   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6784   // keep doubling the size of the integer elements up to that. We can
6785   // then shift the elements of the integer vector by whole multiples of
6786   // their width within the elements of the larger integer vector. Test each
6787   // multiple to see if we can find a match with the moved element indices
6788   // and that the shifted in elements are all zeroable.
6789   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6790     for (int Shift = 1; Shift != Scale; ++Shift)
6791       for (bool Left : {true, false})
6792         if (CheckZeros(Shift, Scale, Left))
6793           for (SDValue V : {V1, V2})
6794             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6795               return Match;
6796
6797   // no match
6798   return SDValue();
6799 }
6800
6801 /// \brief Lower a vector shuffle as a zero or any extension.
6802 ///
6803 /// Given a specific number of elements, element bit width, and extension
6804 /// stride, produce either a zero or any extension based on the available
6805 /// features of the subtarget.
6806 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6807     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6808     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6809   assert(Scale > 1 && "Need a scale to extend.");
6810   int NumElements = VT.getVectorNumElements();
6811   int EltBits = VT.getScalarSizeInBits();
6812   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6813          "Only 8, 16, and 32 bit elements can be extended.");
6814   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6815
6816   // Found a valid zext mask! Try various lowering strategies based on the
6817   // input type and available ISA extensions.
6818   if (Subtarget->hasSSE41()) {
6819     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6820                                  NumElements / Scale);
6821     return DAG.getNode(ISD::BITCAST, DL, VT,
6822                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6823   }
6824
6825   // For any extends we can cheat for larger element sizes and use shuffle
6826   // instructions that can fold with a load and/or copy.
6827   if (AnyExt && EltBits == 32) {
6828     int PSHUFDMask[4] = {0, -1, 1, -1};
6829     return DAG.getNode(
6830         ISD::BITCAST, DL, VT,
6831         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6832                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6833                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6834   }
6835   if (AnyExt && EltBits == 16 && Scale > 2) {
6836     int PSHUFDMask[4] = {0, -1, 0, -1};
6837     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6838                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6839                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6840     int PSHUFHWMask[4] = {1, -1, -1, -1};
6841     return DAG.getNode(
6842         ISD::BITCAST, DL, VT,
6843         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6844                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6845                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6846   }
6847
6848   // If this would require more than 2 unpack instructions to expand, use
6849   // pshufb when available. We can only use more than 2 unpack instructions
6850   // when zero extending i8 elements which also makes it easier to use pshufb.
6851   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6852     assert(NumElements == 16 && "Unexpected byte vector width!");
6853     SDValue PSHUFBMask[16];
6854     for (int i = 0; i < 16; ++i)
6855       PSHUFBMask[i] =
6856           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6857     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6858     return DAG.getNode(ISD::BITCAST, DL, VT,
6859                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6860                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6861                                                MVT::v16i8, PSHUFBMask)));
6862   }
6863
6864   // Otherwise emit a sequence of unpacks.
6865   do {
6866     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6867     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6868                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6869     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6870     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6871     Scale /= 2;
6872     EltBits *= 2;
6873     NumElements /= 2;
6874   } while (Scale > 1);
6875   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6876 }
6877
6878 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6879 ///
6880 /// This routine will try to do everything in its power to cleverly lower
6881 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6882 /// check for the profitability of this lowering,  it tries to aggressively
6883 /// match this pattern. It will use all of the micro-architectural details it
6884 /// can to emit an efficient lowering. It handles both blends with all-zero
6885 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6886 /// masking out later).
6887 ///
6888 /// The reason we have dedicated lowering for zext-style shuffles is that they
6889 /// are both incredibly common and often quite performance sensitive.
6890 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6891     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6892     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6893   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6894
6895   int Bits = VT.getSizeInBits();
6896   int NumElements = VT.getVectorNumElements();
6897   assert(VT.getScalarSizeInBits() <= 32 &&
6898          "Exceeds 32-bit integer zero extension limit");
6899   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6900
6901   // Define a helper function to check a particular ext-scale and lower to it if
6902   // valid.
6903   auto Lower = [&](int Scale) -> SDValue {
6904     SDValue InputV;
6905     bool AnyExt = true;
6906     for (int i = 0; i < NumElements; ++i) {
6907       if (Mask[i] == -1)
6908         continue; // Valid anywhere but doesn't tell us anything.
6909       if (i % Scale != 0) {
6910         // Each of the extended elements need to be zeroable.
6911         if (!Zeroable[i])
6912           return SDValue();
6913
6914         // We no longer are in the anyext case.
6915         AnyExt = false;
6916         continue;
6917       }
6918
6919       // Each of the base elements needs to be consecutive indices into the
6920       // same input vector.
6921       SDValue V = Mask[i] < NumElements ? V1 : V2;
6922       if (!InputV)
6923         InputV = V;
6924       else if (InputV != V)
6925         return SDValue(); // Flip-flopping inputs.
6926
6927       if (Mask[i] % NumElements != i / Scale)
6928         return SDValue(); // Non-consecutive strided elements.
6929     }
6930
6931     // If we fail to find an input, we have a zero-shuffle which should always
6932     // have already been handled.
6933     // FIXME: Maybe handle this here in case during blending we end up with one?
6934     if (!InputV)
6935       return SDValue();
6936
6937     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6938         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6939   };
6940
6941   // The widest scale possible for extending is to a 64-bit integer.
6942   assert(Bits % 64 == 0 &&
6943          "The number of bits in a vector must be divisible by 64 on x86!");
6944   int NumExtElements = Bits / 64;
6945
6946   // Each iteration, try extending the elements half as much, but into twice as
6947   // many elements.
6948   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6949     assert(NumElements % NumExtElements == 0 &&
6950            "The input vector size must be divisible by the extended size.");
6951     if (SDValue V = Lower(NumElements / NumExtElements))
6952       return V;
6953   }
6954
6955   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6956   if (Bits != 128)
6957     return SDValue();
6958
6959   // Returns one of the source operands if the shuffle can be reduced to a
6960   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6961   auto CanZExtLowHalf = [&]() {
6962     for (int i = NumElements / 2; i != NumElements; ++i)
6963       if (!Zeroable[i])
6964         return SDValue();
6965     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6966       return V1;
6967     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6968       return V2;
6969     return SDValue();
6970   };
6971
6972   if (SDValue V = CanZExtLowHalf()) {
6973     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6974     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6975     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6976   }
6977
6978   // No viable ext lowering found.
6979   return SDValue();
6980 }
6981
6982 /// \brief Try to get a scalar value for a specific element of a vector.
6983 ///
6984 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6985 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6986                                               SelectionDAG &DAG) {
6987   MVT VT = V.getSimpleValueType();
6988   MVT EltVT = VT.getVectorElementType();
6989   while (V.getOpcode() == ISD::BITCAST)
6990     V = V.getOperand(0);
6991   // If the bitcasts shift the element size, we can't extract an equivalent
6992   // element from it.
6993   MVT NewVT = V.getSimpleValueType();
6994   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6995     return SDValue();
6996
6997   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6998       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6999     // Ensure the scalar operand is the same size as the destination.
7000     // FIXME: Add support for scalar truncation where possible.
7001     SDValue S = V.getOperand(Idx);
7002     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7003       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7004   }
7005
7006   return SDValue();
7007 }
7008
7009 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7010 ///
7011 /// This is particularly important because the set of instructions varies
7012 /// significantly based on whether the operand is a load or not.
7013 static bool isShuffleFoldableLoad(SDValue V) {
7014   while (V.getOpcode() == ISD::BITCAST)
7015     V = V.getOperand(0);
7016
7017   return ISD::isNON_EXTLoad(V.getNode());
7018 }
7019
7020 /// \brief Try to lower insertion of a single element into a zero vector.
7021 ///
7022 /// This is a common pattern that we have especially efficient patterns to lower
7023 /// across all subtarget feature sets.
7024 static SDValue lowerVectorShuffleAsElementInsertion(
7025     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7026     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7027   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7028   MVT ExtVT = VT;
7029   MVT EltVT = VT.getVectorElementType();
7030
7031   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7032                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7033                 Mask.begin();
7034   bool IsV1Zeroable = true;
7035   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7036     if (i != V2Index && !Zeroable[i]) {
7037       IsV1Zeroable = false;
7038       break;
7039     }
7040
7041   // Check for a single input from a SCALAR_TO_VECTOR node.
7042   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7043   // all the smarts here sunk into that routine. However, the current
7044   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7045   // vector shuffle lowering is dead.
7046   if (SDValue V2S = getScalarValueForVectorElement(
7047           V2, Mask[V2Index] - Mask.size(), DAG)) {
7048     // We need to zext the scalar if it is smaller than an i32.
7049     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7050     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7051       // Using zext to expand a narrow element won't work for non-zero
7052       // insertions.
7053       if (!IsV1Zeroable)
7054         return SDValue();
7055
7056       // Zero-extend directly to i32.
7057       ExtVT = MVT::v4i32;
7058       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7059     }
7060     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7061   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7062              EltVT == MVT::i16) {
7063     // Either not inserting from the low element of the input or the input
7064     // element size is too small to use VZEXT_MOVL to clear the high bits.
7065     return SDValue();
7066   }
7067
7068   if (!IsV1Zeroable) {
7069     // If V1 can't be treated as a zero vector we have fewer options to lower
7070     // this. We can't support integer vectors or non-zero targets cheaply, and
7071     // the V1 elements can't be permuted in any way.
7072     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7073     if (!VT.isFloatingPoint() || V2Index != 0)
7074       return SDValue();
7075     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7076     V1Mask[V2Index] = -1;
7077     if (!isNoopShuffleMask(V1Mask))
7078       return SDValue();
7079     // This is essentially a special case blend operation, but if we have
7080     // general purpose blend operations, they are always faster. Bail and let
7081     // the rest of the lowering handle these as blends.
7082     if (Subtarget->hasSSE41())
7083       return SDValue();
7084
7085     // Otherwise, use MOVSD or MOVSS.
7086     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7087            "Only two types of floating point element types to handle!");
7088     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7089                        ExtVT, V1, V2);
7090   }
7091
7092   // This lowering only works for the low element with floating point vectors.
7093   if (VT.isFloatingPoint() && V2Index != 0)
7094     return SDValue();
7095
7096   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7097   if (ExtVT != VT)
7098     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7099
7100   if (V2Index != 0) {
7101     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7102     // the desired position. Otherwise it is more efficient to do a vector
7103     // shift left. We know that we can do a vector shift left because all
7104     // the inputs are zero.
7105     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7106       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7107       V2Shuffle[V2Index] = 0;
7108       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7109     } else {
7110       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7111       V2 = DAG.getNode(
7112           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7113           DAG.getConstant(
7114               V2Index * EltVT.getSizeInBits()/8, DL,
7115               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7116       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7117     }
7118   }
7119   return V2;
7120 }
7121
7122 /// \brief Try to lower broadcast of a single element.
7123 ///
7124 /// For convenience, this code also bundles all of the subtarget feature set
7125 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7126 /// a convenient way to factor it out.
7127 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7128                                              ArrayRef<int> Mask,
7129                                              const X86Subtarget *Subtarget,
7130                                              SelectionDAG &DAG) {
7131   if (!Subtarget->hasAVX())
7132     return SDValue();
7133   if (VT.isInteger() && !Subtarget->hasAVX2())
7134     return SDValue();
7135
7136   // Check that the mask is a broadcast.
7137   int BroadcastIdx = -1;
7138   for (int M : Mask)
7139     if (M >= 0 && BroadcastIdx == -1)
7140       BroadcastIdx = M;
7141     else if (M >= 0 && M != BroadcastIdx)
7142       return SDValue();
7143
7144   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7145                                             "a sorted mask where the broadcast "
7146                                             "comes from V1.");
7147
7148   // Go up the chain of (vector) values to find a scalar load that we can
7149   // combine with the broadcast.
7150   for (;;) {
7151     switch (V.getOpcode()) {
7152     case ISD::CONCAT_VECTORS: {
7153       int OperandSize = Mask.size() / V.getNumOperands();
7154       V = V.getOperand(BroadcastIdx / OperandSize);
7155       BroadcastIdx %= OperandSize;
7156       continue;
7157     }
7158
7159     case ISD::INSERT_SUBVECTOR: {
7160       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7161       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7162       if (!ConstantIdx)
7163         break;
7164
7165       int BeginIdx = (int)ConstantIdx->getZExtValue();
7166       int EndIdx =
7167           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7168       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7169         BroadcastIdx -= BeginIdx;
7170         V = VInner;
7171       } else {
7172         V = VOuter;
7173       }
7174       continue;
7175     }
7176     }
7177     break;
7178   }
7179
7180   // Check if this is a broadcast of a scalar. We special case lowering
7181   // for scalars so that we can more effectively fold with loads.
7182   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7183       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7184     V = V.getOperand(BroadcastIdx);
7185
7186     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7187     // Only AVX2 has register broadcasts.
7188     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7189       return SDValue();
7190   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7191     // We can't broadcast from a vector register without AVX2, and we can only
7192     // broadcast from the zero-element of a vector register.
7193     return SDValue();
7194   }
7195
7196   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7197 }
7198
7199 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7200 // INSERTPS when the V1 elements are already in the correct locations
7201 // because otherwise we can just always use two SHUFPS instructions which
7202 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7203 // perform INSERTPS if a single V1 element is out of place and all V2
7204 // elements are zeroable.
7205 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7206                                             ArrayRef<int> Mask,
7207                                             SelectionDAG &DAG) {
7208   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7209   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7210   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7211   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7212
7213   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7214
7215   unsigned ZMask = 0;
7216   int V1DstIndex = -1;
7217   int V2DstIndex = -1;
7218   bool V1UsedInPlace = false;
7219
7220   for (int i = 0; i < 4; ++i) {
7221     // Synthesize a zero mask from the zeroable elements (includes undefs).
7222     if (Zeroable[i]) {
7223       ZMask |= 1 << i;
7224       continue;
7225     }
7226
7227     // Flag if we use any V1 inputs in place.
7228     if (i == Mask[i]) {
7229       V1UsedInPlace = true;
7230       continue;
7231     }
7232
7233     // We can only insert a single non-zeroable element.
7234     if (V1DstIndex != -1 || V2DstIndex != -1)
7235       return SDValue();
7236
7237     if (Mask[i] < 4) {
7238       // V1 input out of place for insertion.
7239       V1DstIndex = i;
7240     } else {
7241       // V2 input for insertion.
7242       V2DstIndex = i;
7243     }
7244   }
7245
7246   // Don't bother if we have no (non-zeroable) element for insertion.
7247   if (V1DstIndex == -1 && V2DstIndex == -1)
7248     return SDValue();
7249
7250   // Determine element insertion src/dst indices. The src index is from the
7251   // start of the inserted vector, not the start of the concatenated vector.
7252   unsigned V2SrcIndex = 0;
7253   if (V1DstIndex != -1) {
7254     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7255     // and don't use the original V2 at all.
7256     V2SrcIndex = Mask[V1DstIndex];
7257     V2DstIndex = V1DstIndex;
7258     V2 = V1;
7259   } else {
7260     V2SrcIndex = Mask[V2DstIndex] - 4;
7261   }
7262
7263   // If no V1 inputs are used in place, then the result is created only from
7264   // the zero mask and the V2 insertion - so remove V1 dependency.
7265   if (!V1UsedInPlace)
7266     V1 = DAG.getUNDEF(MVT::v4f32);
7267
7268   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7269   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7270
7271   // Insert the V2 element into the desired position.
7272   SDLoc DL(Op);
7273   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7274                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7275 }
7276
7277 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7278 /// UNPCK instruction.
7279 ///
7280 /// This specifically targets cases where we end up with alternating between
7281 /// the two inputs, and so can permute them into something that feeds a single
7282 /// UNPCK instruction. Note that this routine only targets integer vectors
7283 /// because for floating point vectors we have a generalized SHUFPS lowering
7284 /// strategy that handles everything that doesn't *exactly* match an unpack,
7285 /// making this clever lowering unnecessary.
7286 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7287                                           SDValue V2, ArrayRef<int> Mask,
7288                                           SelectionDAG &DAG) {
7289   assert(!VT.isFloatingPoint() &&
7290          "This routine only supports integer vectors.");
7291   assert(!isSingleInputShuffleMask(Mask) &&
7292          "This routine should only be used when blending two inputs.");
7293   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7294
7295   int Size = Mask.size();
7296
7297   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7298     return M >= 0 && M % Size < Size / 2;
7299   });
7300   int NumHiInputs = std::count_if(
7301       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7302
7303   bool UnpackLo = NumLoInputs >= NumHiInputs;
7304
7305   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7306     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7307     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7308
7309     for (int i = 0; i < Size; ++i) {
7310       if (Mask[i] < 0)
7311         continue;
7312
7313       // Each element of the unpack contains Scale elements from this mask.
7314       int UnpackIdx = i / Scale;
7315
7316       // We only handle the case where V1 feeds the first slots of the unpack.
7317       // We rely on canonicalization to ensure this is the case.
7318       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7319         return SDValue();
7320
7321       // Setup the mask for this input. The indexing is tricky as we have to
7322       // handle the unpack stride.
7323       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7324       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7325           Mask[i] % Size;
7326     }
7327
7328     // If we will have to shuffle both inputs to use the unpack, check whether
7329     // we can just unpack first and shuffle the result. If so, skip this unpack.
7330     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7331         !isNoopShuffleMask(V2Mask))
7332       return SDValue();
7333
7334     // Shuffle the inputs into place.
7335     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7336     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7337
7338     // Cast the inputs to the type we will use to unpack them.
7339     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7340     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7341
7342     // Unpack the inputs and cast the result back to the desired type.
7343     return DAG.getNode(ISD::BITCAST, DL, VT,
7344                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7345                                    DL, UnpackVT, V1, V2));
7346   };
7347
7348   // We try each unpack from the largest to the smallest to try and find one
7349   // that fits this mask.
7350   int OrigNumElements = VT.getVectorNumElements();
7351   int OrigScalarSize = VT.getScalarSizeInBits();
7352   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7353     int Scale = ScalarSize / OrigScalarSize;
7354     int NumElements = OrigNumElements / Scale;
7355     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7356     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7357       return Unpack;
7358   }
7359
7360   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7361   // initial unpack.
7362   if (NumLoInputs == 0 || NumHiInputs == 0) {
7363     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7364            "We have to have *some* inputs!");
7365     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7366
7367     // FIXME: We could consider the total complexity of the permute of each
7368     // possible unpacking. Or at the least we should consider how many
7369     // half-crossings are created.
7370     // FIXME: We could consider commuting the unpacks.
7371
7372     SmallVector<int, 32> PermMask;
7373     PermMask.assign(Size, -1);
7374     for (int i = 0; i < Size; ++i) {
7375       if (Mask[i] < 0)
7376         continue;
7377
7378       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7379
7380       PermMask[i] =
7381           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7382     }
7383     return DAG.getVectorShuffle(
7384         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7385                             DL, VT, V1, V2),
7386         DAG.getUNDEF(VT), PermMask);
7387   }
7388
7389   return SDValue();
7390 }
7391
7392 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7393 ///
7394 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7395 /// support for floating point shuffles but not integer shuffles. These
7396 /// instructions will incur a domain crossing penalty on some chips though so
7397 /// it is better to avoid lowering through this for integer vectors where
7398 /// possible.
7399 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7400                                        const X86Subtarget *Subtarget,
7401                                        SelectionDAG &DAG) {
7402   SDLoc DL(Op);
7403   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7404   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7405   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7406   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7407   ArrayRef<int> Mask = SVOp->getMask();
7408   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7409
7410   if (isSingleInputShuffleMask(Mask)) {
7411     // Use low duplicate instructions for masks that match their pattern.
7412     if (Subtarget->hasSSE3())
7413       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7414         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7415
7416     // Straight shuffle of a single input vector. Simulate this by using the
7417     // single input as both of the "inputs" to this instruction..
7418     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7419
7420     if (Subtarget->hasAVX()) {
7421       // If we have AVX, we can use VPERMILPS which will allow folding a load
7422       // into the shuffle.
7423       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7424                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7425     }
7426
7427     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7428                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7429   }
7430   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7431   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7432
7433   // If we have a single input, insert that into V1 if we can do so cheaply.
7434   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7435     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7436             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7437       return Insertion;
7438     // Try inverting the insertion since for v2 masks it is easy to do and we
7439     // can't reliably sort the mask one way or the other.
7440     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7441                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7442     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7443             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7444       return Insertion;
7445   }
7446
7447   // Try to use one of the special instruction patterns to handle two common
7448   // blend patterns if a zero-blend above didn't work.
7449   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7450       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7451     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7452       // We can either use a special instruction to load over the low double or
7453       // to move just the low double.
7454       return DAG.getNode(
7455           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7456           DL, MVT::v2f64, V2,
7457           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7458
7459   if (Subtarget->hasSSE41())
7460     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7461                                                   Subtarget, DAG))
7462       return Blend;
7463
7464   // Use dedicated unpack instructions for masks that match their pattern.
7465   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7466     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7467   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7468     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7469
7470   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7471   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7472                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7473 }
7474
7475 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7476 ///
7477 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7478 /// the integer unit to minimize domain crossing penalties. However, for blends
7479 /// it falls back to the floating point shuffle operation with appropriate bit
7480 /// casting.
7481 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7482                                        const X86Subtarget *Subtarget,
7483                                        SelectionDAG &DAG) {
7484   SDLoc DL(Op);
7485   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7486   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7487   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7488   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7489   ArrayRef<int> Mask = SVOp->getMask();
7490   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7491
7492   if (isSingleInputShuffleMask(Mask)) {
7493     // Check for being able to broadcast a single element.
7494     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7495                                                           Mask, Subtarget, DAG))
7496       return Broadcast;
7497
7498     // Straight shuffle of a single input vector. For everything from SSE2
7499     // onward this has a single fast instruction with no scary immediates.
7500     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7501     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7502     int WidenedMask[4] = {
7503         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7504         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7505     return DAG.getNode(
7506         ISD::BITCAST, DL, MVT::v2i64,
7507         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7508                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7509   }
7510   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7511   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7512   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7513   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7514
7515   // If we have a blend of two PACKUS operations an the blend aligns with the
7516   // low and half halves, we can just merge the PACKUS operations. This is
7517   // particularly important as it lets us merge shuffles that this routine itself
7518   // creates.
7519   auto GetPackNode = [](SDValue V) {
7520     while (V.getOpcode() == ISD::BITCAST)
7521       V = V.getOperand(0);
7522
7523     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7524   };
7525   if (SDValue V1Pack = GetPackNode(V1))
7526     if (SDValue V2Pack = GetPackNode(V2))
7527       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7528                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7529                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7530                                                   : V1Pack.getOperand(1),
7531                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7532                                                   : V2Pack.getOperand(1)));
7533
7534   // Try to use shift instructions.
7535   if (SDValue Shift =
7536           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7537     return Shift;
7538
7539   // When loading a scalar and then shuffling it into a vector we can often do
7540   // the insertion cheaply.
7541   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7542           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7543     return Insertion;
7544   // Try inverting the insertion since for v2 masks it is easy to do and we
7545   // can't reliably sort the mask one way or the other.
7546   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7547   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7548           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7549     return Insertion;
7550
7551   // We have different paths for blend lowering, but they all must use the
7552   // *exact* same predicate.
7553   bool IsBlendSupported = Subtarget->hasSSE41();
7554   if (IsBlendSupported)
7555     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7556                                                   Subtarget, DAG))
7557       return Blend;
7558
7559   // Use dedicated unpack instructions for masks that match their pattern.
7560   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7561     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7562   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7563     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7564
7565   // Try to use byte rotation instructions.
7566   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7567   if (Subtarget->hasSSSE3())
7568     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7569             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7570       return Rotate;
7571
7572   // If we have direct support for blends, we should lower by decomposing into
7573   // a permute. That will be faster than the domain cross.
7574   if (IsBlendSupported)
7575     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7576                                                       Mask, DAG);
7577
7578   // We implement this with SHUFPD which is pretty lame because it will likely
7579   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7580   // However, all the alternatives are still more cycles and newer chips don't
7581   // have this problem. It would be really nice if x86 had better shuffles here.
7582   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7583   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7584   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7585                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7586 }
7587
7588 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7589 ///
7590 /// This is used to disable more specialized lowerings when the shufps lowering
7591 /// will happen to be efficient.
7592 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7593   // This routine only handles 128-bit shufps.
7594   assert(Mask.size() == 4 && "Unsupported mask size!");
7595
7596   // To lower with a single SHUFPS we need to have the low half and high half
7597   // each requiring a single input.
7598   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7599     return false;
7600   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7601     return false;
7602
7603   return true;
7604 }
7605
7606 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7607 ///
7608 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7609 /// It makes no assumptions about whether this is the *best* lowering, it simply
7610 /// uses it.
7611 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7612                                             ArrayRef<int> Mask, SDValue V1,
7613                                             SDValue V2, SelectionDAG &DAG) {
7614   SDValue LowV = V1, HighV = V2;
7615   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7616
7617   int NumV2Elements =
7618       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7619
7620   if (NumV2Elements == 1) {
7621     int V2Index =
7622         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7623         Mask.begin();
7624
7625     // Compute the index adjacent to V2Index and in the same half by toggling
7626     // the low bit.
7627     int V2AdjIndex = V2Index ^ 1;
7628
7629     if (Mask[V2AdjIndex] == -1) {
7630       // Handles all the cases where we have a single V2 element and an undef.
7631       // This will only ever happen in the high lanes because we commute the
7632       // vector otherwise.
7633       if (V2Index < 2)
7634         std::swap(LowV, HighV);
7635       NewMask[V2Index] -= 4;
7636     } else {
7637       // Handle the case where the V2 element ends up adjacent to a V1 element.
7638       // To make this work, blend them together as the first step.
7639       int V1Index = V2AdjIndex;
7640       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7641       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7642                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7643
7644       // Now proceed to reconstruct the final blend as we have the necessary
7645       // high or low half formed.
7646       if (V2Index < 2) {
7647         LowV = V2;
7648         HighV = V1;
7649       } else {
7650         HighV = V2;
7651       }
7652       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7653       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7654     }
7655   } else if (NumV2Elements == 2) {
7656     if (Mask[0] < 4 && Mask[1] < 4) {
7657       // Handle the easy case where we have V1 in the low lanes and V2 in the
7658       // high lanes.
7659       NewMask[2] -= 4;
7660       NewMask[3] -= 4;
7661     } else if (Mask[2] < 4 && Mask[3] < 4) {
7662       // We also handle the reversed case because this utility may get called
7663       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7664       // arrange things in the right direction.
7665       NewMask[0] -= 4;
7666       NewMask[1] -= 4;
7667       HighV = V1;
7668       LowV = V2;
7669     } else {
7670       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7671       // trying to place elements directly, just blend them and set up the final
7672       // shuffle to place them.
7673
7674       // The first two blend mask elements are for V1, the second two are for
7675       // V2.
7676       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7677                           Mask[2] < 4 ? Mask[2] : Mask[3],
7678                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7679                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7680       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7681                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7682
7683       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7684       // a blend.
7685       LowV = HighV = V1;
7686       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7687       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7688       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7689       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7690     }
7691   }
7692   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7693                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7694 }
7695
7696 /// \brief Lower 4-lane 32-bit floating point shuffles.
7697 ///
7698 /// Uses instructions exclusively from the floating point unit to minimize
7699 /// domain crossing penalties, as these are sufficient to implement all v4f32
7700 /// shuffles.
7701 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7702                                        const X86Subtarget *Subtarget,
7703                                        SelectionDAG &DAG) {
7704   SDLoc DL(Op);
7705   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7706   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7707   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7708   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7709   ArrayRef<int> Mask = SVOp->getMask();
7710   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7711
7712   int NumV2Elements =
7713       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7714
7715   if (NumV2Elements == 0) {
7716     // Check for being able to broadcast a single element.
7717     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7718                                                           Mask, Subtarget, DAG))
7719       return Broadcast;
7720
7721     // Use even/odd duplicate instructions for masks that match their pattern.
7722     if (Subtarget->hasSSE3()) {
7723       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7724         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7725       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7726         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7727     }
7728
7729     if (Subtarget->hasAVX()) {
7730       // If we have AVX, we can use VPERMILPS which will allow folding a load
7731       // into the shuffle.
7732       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7733                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7734     }
7735
7736     // Otherwise, use a straight shuffle of a single input vector. We pass the
7737     // input vector to both operands to simulate this with a SHUFPS.
7738     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7739                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7740   }
7741
7742   // There are special ways we can lower some single-element blends. However, we
7743   // have custom ways we can lower more complex single-element blends below that
7744   // we defer to if both this and BLENDPS fail to match, so restrict this to
7745   // when the V2 input is targeting element 0 of the mask -- that is the fast
7746   // case here.
7747   if (NumV2Elements == 1 && Mask[0] >= 4)
7748     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7749                                                          Mask, Subtarget, DAG))
7750       return V;
7751
7752   if (Subtarget->hasSSE41()) {
7753     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7754                                                   Subtarget, DAG))
7755       return Blend;
7756
7757     // Use INSERTPS if we can complete the shuffle efficiently.
7758     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7759       return V;
7760
7761     if (!isSingleSHUFPSMask(Mask))
7762       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7763               DL, MVT::v4f32, V1, V2, Mask, DAG))
7764         return BlendPerm;
7765   }
7766
7767   // Use dedicated unpack instructions for masks that match their pattern.
7768   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7769     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7770   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7771     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7772   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7773     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7774   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7775     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7776
7777   // Otherwise fall back to a SHUFPS lowering strategy.
7778   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7779 }
7780
7781 /// \brief Lower 4-lane i32 vector shuffles.
7782 ///
7783 /// We try to handle these with integer-domain shuffles where we can, but for
7784 /// blends we use the floating point domain blend instructions.
7785 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7786                                        const X86Subtarget *Subtarget,
7787                                        SelectionDAG &DAG) {
7788   SDLoc DL(Op);
7789   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7790   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7791   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7792   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7793   ArrayRef<int> Mask = SVOp->getMask();
7794   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7795
7796   // Whenever we can lower this as a zext, that instruction is strictly faster
7797   // than any alternative. It also allows us to fold memory operands into the
7798   // shuffle in many cases.
7799   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7800                                                          Mask, Subtarget, DAG))
7801     return ZExt;
7802
7803   int NumV2Elements =
7804       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7805
7806   if (NumV2Elements == 0) {
7807     // Check for being able to broadcast a single element.
7808     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7809                                                           Mask, Subtarget, DAG))
7810       return Broadcast;
7811
7812     // Straight shuffle of a single input vector. For everything from SSE2
7813     // onward this has a single fast instruction with no scary immediates.
7814     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7815     // but we aren't actually going to use the UNPCK instruction because doing
7816     // so prevents folding a load into this instruction or making a copy.
7817     const int UnpackLoMask[] = {0, 0, 1, 1};
7818     const int UnpackHiMask[] = {2, 2, 3, 3};
7819     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7820       Mask = UnpackLoMask;
7821     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7822       Mask = UnpackHiMask;
7823
7824     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7825                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7826   }
7827
7828   // Try to use shift instructions.
7829   if (SDValue Shift =
7830           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7831     return Shift;
7832
7833   // There are special ways we can lower some single-element blends.
7834   if (NumV2Elements == 1)
7835     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7836                                                          Mask, Subtarget, DAG))
7837       return V;
7838
7839   // We have different paths for blend lowering, but they all must use the
7840   // *exact* same predicate.
7841   bool IsBlendSupported = Subtarget->hasSSE41();
7842   if (IsBlendSupported)
7843     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7844                                                   Subtarget, DAG))
7845       return Blend;
7846
7847   if (SDValue Masked =
7848           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7849     return Masked;
7850
7851   // Use dedicated unpack instructions for masks that match their pattern.
7852   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7853     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7854   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7855     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7856   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7857     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7858   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7859     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7860
7861   // Try to use byte rotation instructions.
7862   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7863   if (Subtarget->hasSSSE3())
7864     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7865             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7866       return Rotate;
7867
7868   // If we have direct support for blends, we should lower by decomposing into
7869   // a permute. That will be faster than the domain cross.
7870   if (IsBlendSupported)
7871     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7872                                                       Mask, DAG);
7873
7874   // Try to lower by permuting the inputs into an unpack instruction.
7875   if (SDValue Unpack =
7876           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7877     return Unpack;
7878
7879   // We implement this with SHUFPS because it can blend from two vectors.
7880   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7881   // up the inputs, bypassing domain shift penalties that we would encur if we
7882   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7883   // relevant.
7884   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7885                      DAG.getVectorShuffle(
7886                          MVT::v4f32, DL,
7887                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7888                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7889 }
7890
7891 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7892 /// shuffle lowering, and the most complex part.
7893 ///
7894 /// The lowering strategy is to try to form pairs of input lanes which are
7895 /// targeted at the same half of the final vector, and then use a dword shuffle
7896 /// to place them onto the right half, and finally unpack the paired lanes into
7897 /// their final position.
7898 ///
7899 /// The exact breakdown of how to form these dword pairs and align them on the
7900 /// correct sides is really tricky. See the comments within the function for
7901 /// more of the details.
7902 ///
7903 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7904 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7905 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7906 /// vector, form the analogous 128-bit 8-element Mask.
7907 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7908     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7909     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7910   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7911   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7912
7913   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7914   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7915   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7916
7917   SmallVector<int, 4> LoInputs;
7918   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7919                [](int M) { return M >= 0; });
7920   std::sort(LoInputs.begin(), LoInputs.end());
7921   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7922   SmallVector<int, 4> HiInputs;
7923   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7924                [](int M) { return M >= 0; });
7925   std::sort(HiInputs.begin(), HiInputs.end());
7926   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7927   int NumLToL =
7928       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7929   int NumHToL = LoInputs.size() - NumLToL;
7930   int NumLToH =
7931       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7932   int NumHToH = HiInputs.size() - NumLToH;
7933   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7934   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7935   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7936   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7937
7938   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7939   // such inputs we can swap two of the dwords across the half mark and end up
7940   // with <=2 inputs to each half in each half. Once there, we can fall through
7941   // to the generic code below. For example:
7942   //
7943   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7944   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7945   //
7946   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7947   // and an existing 2-into-2 on the other half. In this case we may have to
7948   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7949   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7950   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7951   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7952   // half than the one we target for fixing) will be fixed when we re-enter this
7953   // path. We will also combine away any sequence of PSHUFD instructions that
7954   // result into a single instruction. Here is an example of the tricky case:
7955   //
7956   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7957   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7958   //
7959   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7960   //
7961   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7962   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7963   //
7964   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7965   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7966   //
7967   // The result is fine to be handled by the generic logic.
7968   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7969                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7970                           int AOffset, int BOffset) {
7971     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7972            "Must call this with A having 3 or 1 inputs from the A half.");
7973     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7974            "Must call this with B having 1 or 3 inputs from the B half.");
7975     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7976            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7977
7978     // Compute the index of dword with only one word among the three inputs in
7979     // a half by taking the sum of the half with three inputs and subtracting
7980     // the sum of the actual three inputs. The difference is the remaining
7981     // slot.
7982     int ADWord, BDWord;
7983     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7984     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7985     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7986     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7987     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7988     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7989     int TripleNonInputIdx =
7990         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7991     TripleDWord = TripleNonInputIdx / 2;
7992
7993     // We use xor with one to compute the adjacent DWord to whichever one the
7994     // OneInput is in.
7995     OneInputDWord = (OneInput / 2) ^ 1;
7996
7997     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7998     // and BToA inputs. If there is also such a problem with the BToB and AToB
7999     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8000     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8001     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8002     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8003       // Compute how many inputs will be flipped by swapping these DWords. We
8004       // need
8005       // to balance this to ensure we don't form a 3-1 shuffle in the other
8006       // half.
8007       int NumFlippedAToBInputs =
8008           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8009           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8010       int NumFlippedBToBInputs =
8011           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8012           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8013       if ((NumFlippedAToBInputs == 1 &&
8014            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8015           (NumFlippedBToBInputs == 1 &&
8016            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8017         // We choose whether to fix the A half or B half based on whether that
8018         // half has zero flipped inputs. At zero, we may not be able to fix it
8019         // with that half. We also bias towards fixing the B half because that
8020         // will more commonly be the high half, and we have to bias one way.
8021         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8022                                                        ArrayRef<int> Inputs) {
8023           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8024           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8025                                          PinnedIdx ^ 1) != Inputs.end();
8026           // Determine whether the free index is in the flipped dword or the
8027           // unflipped dword based on where the pinned index is. We use this bit
8028           // in an xor to conditionally select the adjacent dword.
8029           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8030           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8031                                              FixFreeIdx) != Inputs.end();
8032           if (IsFixIdxInput == IsFixFreeIdxInput)
8033             FixFreeIdx += 1;
8034           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8035                                         FixFreeIdx) != Inputs.end();
8036           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8037                  "We need to be changing the number of flipped inputs!");
8038           int PSHUFHalfMask[] = {0, 1, 2, 3};
8039           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8040           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8041                           MVT::v8i16, V,
8042                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8043
8044           for (int &M : Mask)
8045             if (M != -1 && M == FixIdx)
8046               M = FixFreeIdx;
8047             else if (M != -1 && M == FixFreeIdx)
8048               M = FixIdx;
8049         };
8050         if (NumFlippedBToBInputs != 0) {
8051           int BPinnedIdx =
8052               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8053           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8054         } else {
8055           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8056           int APinnedIdx =
8057               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8058           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8059         }
8060       }
8061     }
8062
8063     int PSHUFDMask[] = {0, 1, 2, 3};
8064     PSHUFDMask[ADWord] = BDWord;
8065     PSHUFDMask[BDWord] = ADWord;
8066     V = DAG.getNode(ISD::BITCAST, DL, VT,
8067                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8068                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8069                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8070                                                            DAG)));
8071
8072     // Adjust the mask to match the new locations of A and B.
8073     for (int &M : Mask)
8074       if (M != -1 && M/2 == ADWord)
8075         M = 2 * BDWord + M % 2;
8076       else if (M != -1 && M/2 == BDWord)
8077         M = 2 * ADWord + M % 2;
8078
8079     // Recurse back into this routine to re-compute state now that this isn't
8080     // a 3 and 1 problem.
8081     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8082                                                      DAG);
8083   };
8084   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8085     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8086   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8087     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8088
8089   // At this point there are at most two inputs to the low and high halves from
8090   // each half. That means the inputs can always be grouped into dwords and
8091   // those dwords can then be moved to the correct half with a dword shuffle.
8092   // We use at most one low and one high word shuffle to collect these paired
8093   // inputs into dwords, and finally a dword shuffle to place them.
8094   int PSHUFLMask[4] = {-1, -1, -1, -1};
8095   int PSHUFHMask[4] = {-1, -1, -1, -1};
8096   int PSHUFDMask[4] = {-1, -1, -1, -1};
8097
8098   // First fix the masks for all the inputs that are staying in their
8099   // original halves. This will then dictate the targets of the cross-half
8100   // shuffles.
8101   auto fixInPlaceInputs =
8102       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8103                     MutableArrayRef<int> SourceHalfMask,
8104                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8105     if (InPlaceInputs.empty())
8106       return;
8107     if (InPlaceInputs.size() == 1) {
8108       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8109           InPlaceInputs[0] - HalfOffset;
8110       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8111       return;
8112     }
8113     if (IncomingInputs.empty()) {
8114       // Just fix all of the in place inputs.
8115       for (int Input : InPlaceInputs) {
8116         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8117         PSHUFDMask[Input / 2] = Input / 2;
8118       }
8119       return;
8120     }
8121
8122     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8123     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8124         InPlaceInputs[0] - HalfOffset;
8125     // Put the second input next to the first so that they are packed into
8126     // a dword. We find the adjacent index by toggling the low bit.
8127     int AdjIndex = InPlaceInputs[0] ^ 1;
8128     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8129     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8130     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8131   };
8132   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8133   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8134
8135   // Now gather the cross-half inputs and place them into a free dword of
8136   // their target half.
8137   // FIXME: This operation could almost certainly be simplified dramatically to
8138   // look more like the 3-1 fixing operation.
8139   auto moveInputsToRightHalf = [&PSHUFDMask](
8140       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8141       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8142       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8143       int DestOffset) {
8144     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8145       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8146     };
8147     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8148                                                int Word) {
8149       int LowWord = Word & ~1;
8150       int HighWord = Word | 1;
8151       return isWordClobbered(SourceHalfMask, LowWord) ||
8152              isWordClobbered(SourceHalfMask, HighWord);
8153     };
8154
8155     if (IncomingInputs.empty())
8156       return;
8157
8158     if (ExistingInputs.empty()) {
8159       // Map any dwords with inputs from them into the right half.
8160       for (int Input : IncomingInputs) {
8161         // If the source half mask maps over the inputs, turn those into
8162         // swaps and use the swapped lane.
8163         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8164           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8165             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8166                 Input - SourceOffset;
8167             // We have to swap the uses in our half mask in one sweep.
8168             for (int &M : HalfMask)
8169               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8170                 M = Input;
8171               else if (M == Input)
8172                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8173           } else {
8174             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8175                        Input - SourceOffset &&
8176                    "Previous placement doesn't match!");
8177           }
8178           // Note that this correctly re-maps both when we do a swap and when
8179           // we observe the other side of the swap above. We rely on that to
8180           // avoid swapping the members of the input list directly.
8181           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8182         }
8183
8184         // Map the input's dword into the correct half.
8185         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8186           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8187         else
8188           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8189                      Input / 2 &&
8190                  "Previous placement doesn't match!");
8191       }
8192
8193       // And just directly shift any other-half mask elements to be same-half
8194       // as we will have mirrored the dword containing the element into the
8195       // same position within that half.
8196       for (int &M : HalfMask)
8197         if (M >= SourceOffset && M < SourceOffset + 4) {
8198           M = M - SourceOffset + DestOffset;
8199           assert(M >= 0 && "This should never wrap below zero!");
8200         }
8201       return;
8202     }
8203
8204     // Ensure we have the input in a viable dword of its current half. This
8205     // is particularly tricky because the original position may be clobbered
8206     // by inputs being moved and *staying* in that half.
8207     if (IncomingInputs.size() == 1) {
8208       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8209         int InputFixed = std::find(std::begin(SourceHalfMask),
8210                                    std::end(SourceHalfMask), -1) -
8211                          std::begin(SourceHalfMask) + SourceOffset;
8212         SourceHalfMask[InputFixed - SourceOffset] =
8213             IncomingInputs[0] - SourceOffset;
8214         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8215                      InputFixed);
8216         IncomingInputs[0] = InputFixed;
8217       }
8218     } else if (IncomingInputs.size() == 2) {
8219       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8220           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8221         // We have two non-adjacent or clobbered inputs we need to extract from
8222         // the source half. To do this, we need to map them into some adjacent
8223         // dword slot in the source mask.
8224         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8225                               IncomingInputs[1] - SourceOffset};
8226
8227         // If there is a free slot in the source half mask adjacent to one of
8228         // the inputs, place the other input in it. We use (Index XOR 1) to
8229         // compute an adjacent index.
8230         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8231             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8232           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8233           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8234           InputsFixed[1] = InputsFixed[0] ^ 1;
8235         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8236                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8237           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8238           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8239           InputsFixed[0] = InputsFixed[1] ^ 1;
8240         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8241                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8242           // The two inputs are in the same DWord but it is clobbered and the
8243           // adjacent DWord isn't used at all. Move both inputs to the free
8244           // slot.
8245           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8246           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8247           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8248           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8249         } else {
8250           // The only way we hit this point is if there is no clobbering
8251           // (because there are no off-half inputs to this half) and there is no
8252           // free slot adjacent to one of the inputs. In this case, we have to
8253           // swap an input with a non-input.
8254           for (int i = 0; i < 4; ++i)
8255             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8256                    "We can't handle any clobbers here!");
8257           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8258                  "Cannot have adjacent inputs here!");
8259
8260           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8261           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8262
8263           // We also have to update the final source mask in this case because
8264           // it may need to undo the above swap.
8265           for (int &M : FinalSourceHalfMask)
8266             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8267               M = InputsFixed[1] + SourceOffset;
8268             else if (M == InputsFixed[1] + SourceOffset)
8269               M = (InputsFixed[0] ^ 1) + SourceOffset;
8270
8271           InputsFixed[1] = InputsFixed[0] ^ 1;
8272         }
8273
8274         // Point everything at the fixed inputs.
8275         for (int &M : HalfMask)
8276           if (M == IncomingInputs[0])
8277             M = InputsFixed[0] + SourceOffset;
8278           else if (M == IncomingInputs[1])
8279             M = InputsFixed[1] + SourceOffset;
8280
8281         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8282         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8283       }
8284     } else {
8285       llvm_unreachable("Unhandled input size!");
8286     }
8287
8288     // Now hoist the DWord down to the right half.
8289     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8290     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8291     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8292     for (int &M : HalfMask)
8293       for (int Input : IncomingInputs)
8294         if (M == Input)
8295           M = FreeDWord * 2 + Input % 2;
8296   };
8297   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8298                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8299   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8300                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8301
8302   // Now enact all the shuffles we've computed to move the inputs into their
8303   // target half.
8304   if (!isNoopShuffleMask(PSHUFLMask))
8305     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8306                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8307   if (!isNoopShuffleMask(PSHUFHMask))
8308     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8309                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8310   if (!isNoopShuffleMask(PSHUFDMask))
8311     V = DAG.getNode(ISD::BITCAST, DL, VT,
8312                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8313                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8314                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8315                                                            DAG)));
8316
8317   // At this point, each half should contain all its inputs, and we can then
8318   // just shuffle them into their final position.
8319   assert(std::count_if(LoMask.begin(), LoMask.end(),
8320                        [](int M) { return M >= 4; }) == 0 &&
8321          "Failed to lift all the high half inputs to the low mask!");
8322   assert(std::count_if(HiMask.begin(), HiMask.end(),
8323                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8324          "Failed to lift all the low half inputs to the high mask!");
8325
8326   // Do a half shuffle for the low mask.
8327   if (!isNoopShuffleMask(LoMask))
8328     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8329                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8330
8331   // Do a half shuffle with the high mask after shifting its values down.
8332   for (int &M : HiMask)
8333     if (M >= 0)
8334       M -= 4;
8335   if (!isNoopShuffleMask(HiMask))
8336     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8337                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8338
8339   return V;
8340 }
8341
8342 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8343 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8344                                           SDValue V2, ArrayRef<int> Mask,
8345                                           SelectionDAG &DAG, bool &V1InUse,
8346                                           bool &V2InUse) {
8347   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8348   SDValue V1Mask[16];
8349   SDValue V2Mask[16];
8350   V1InUse = false;
8351   V2InUse = false;
8352
8353   int Size = Mask.size();
8354   int Scale = 16 / Size;
8355   for (int i = 0; i < 16; ++i) {
8356     if (Mask[i / Scale] == -1) {
8357       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8358     } else {
8359       const int ZeroMask = 0x80;
8360       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8361                                           : ZeroMask;
8362       int V2Idx = Mask[i / Scale] < Size
8363                       ? ZeroMask
8364                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8365       if (Zeroable[i / Scale])
8366         V1Idx = V2Idx = ZeroMask;
8367       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8368       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8369       V1InUse |= (ZeroMask != V1Idx);
8370       V2InUse |= (ZeroMask != V2Idx);
8371     }
8372   }
8373
8374   if (V1InUse)
8375     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8376                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8377                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8378   if (V2InUse)
8379     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8380                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8381                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8382
8383   // If we need shuffled inputs from both, blend the two.
8384   SDValue V;
8385   if (V1InUse && V2InUse)
8386     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8387   else
8388     V = V1InUse ? V1 : V2;
8389
8390   // Cast the result back to the correct type.
8391   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8392 }
8393
8394 /// \brief Generic lowering of 8-lane i16 shuffles.
8395 ///
8396 /// This handles both single-input shuffles and combined shuffle/blends with
8397 /// two inputs. The single input shuffles are immediately delegated to
8398 /// a dedicated lowering routine.
8399 ///
8400 /// The blends are lowered in one of three fundamental ways. If there are few
8401 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8402 /// of the input is significantly cheaper when lowered as an interleaving of
8403 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8404 /// halves of the inputs separately (making them have relatively few inputs)
8405 /// and then concatenate them.
8406 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8407                                        const X86Subtarget *Subtarget,
8408                                        SelectionDAG &DAG) {
8409   SDLoc DL(Op);
8410   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8411   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8412   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8413   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8414   ArrayRef<int> OrigMask = SVOp->getMask();
8415   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8416                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8417   MutableArrayRef<int> Mask(MaskStorage);
8418
8419   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8420
8421   // Whenever we can lower this as a zext, that instruction is strictly faster
8422   // than any alternative.
8423   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8424           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8425     return ZExt;
8426
8427   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8428   (void)isV1;
8429   auto isV2 = [](int M) { return M >= 8; };
8430
8431   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8432
8433   if (NumV2Inputs == 0) {
8434     // Check for being able to broadcast a single element.
8435     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8436                                                           Mask, Subtarget, DAG))
8437       return Broadcast;
8438
8439     // Try to use shift instructions.
8440     if (SDValue Shift =
8441             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8442       return Shift;
8443
8444     // Use dedicated unpack instructions for masks that match their pattern.
8445     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8446       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8447     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8448       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8449
8450     // Try to use byte rotation instructions.
8451     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8452                                                         Mask, Subtarget, DAG))
8453       return Rotate;
8454
8455     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8456                                                      Subtarget, DAG);
8457   }
8458
8459   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8460          "All single-input shuffles should be canonicalized to be V1-input "
8461          "shuffles.");
8462
8463   // Try to use shift instructions.
8464   if (SDValue Shift =
8465           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8466     return Shift;
8467
8468   // There are special ways we can lower some single-element blends.
8469   if (NumV2Inputs == 1)
8470     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8471                                                          Mask, Subtarget, DAG))
8472       return V;
8473
8474   // We have different paths for blend lowering, but they all must use the
8475   // *exact* same predicate.
8476   bool IsBlendSupported = Subtarget->hasSSE41();
8477   if (IsBlendSupported)
8478     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8479                                                   Subtarget, DAG))
8480       return Blend;
8481
8482   if (SDValue Masked =
8483           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8484     return Masked;
8485
8486   // Use dedicated unpack instructions for masks that match their pattern.
8487   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8488     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8489   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8490     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8491
8492   // Try to use byte rotation instructions.
8493   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8494           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8495     return Rotate;
8496
8497   if (SDValue BitBlend =
8498           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8499     return BitBlend;
8500
8501   if (SDValue Unpack =
8502           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8503     return Unpack;
8504
8505   // If we can't directly blend but can use PSHUFB, that will be better as it
8506   // can both shuffle and set up the inefficient blend.
8507   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8508     bool V1InUse, V2InUse;
8509     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8510                                       V1InUse, V2InUse);
8511   }
8512
8513   // We can always bit-blend if we have to so the fallback strategy is to
8514   // decompose into single-input permutes and blends.
8515   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8516                                                       Mask, DAG);
8517 }
8518
8519 /// \brief Check whether a compaction lowering can be done by dropping even
8520 /// elements and compute how many times even elements must be dropped.
8521 ///
8522 /// This handles shuffles which take every Nth element where N is a power of
8523 /// two. Example shuffle masks:
8524 ///
8525 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8526 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8527 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8528 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8529 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8530 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8531 ///
8532 /// Any of these lanes can of course be undef.
8533 ///
8534 /// This routine only supports N <= 3.
8535 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8536 /// for larger N.
8537 ///
8538 /// \returns N above, or the number of times even elements must be dropped if
8539 /// there is such a number. Otherwise returns zero.
8540 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8541   // Figure out whether we're looping over two inputs or just one.
8542   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8543
8544   // The modulus for the shuffle vector entries is based on whether this is
8545   // a single input or not.
8546   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8547   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8548          "We should only be called with masks with a power-of-2 size!");
8549
8550   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8551
8552   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8553   // and 2^3 simultaneously. This is because we may have ambiguity with
8554   // partially undef inputs.
8555   bool ViableForN[3] = {true, true, true};
8556
8557   for (int i = 0, e = Mask.size(); i < e; ++i) {
8558     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8559     // want.
8560     if (Mask[i] == -1)
8561       continue;
8562
8563     bool IsAnyViable = false;
8564     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8565       if (ViableForN[j]) {
8566         uint64_t N = j + 1;
8567
8568         // The shuffle mask must be equal to (i * 2^N) % M.
8569         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8570           IsAnyViable = true;
8571         else
8572           ViableForN[j] = false;
8573       }
8574     // Early exit if we exhaust the possible powers of two.
8575     if (!IsAnyViable)
8576       break;
8577   }
8578
8579   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8580     if (ViableForN[j])
8581       return j + 1;
8582
8583   // Return 0 as there is no viable power of two.
8584   return 0;
8585 }
8586
8587 /// \brief Generic lowering of v16i8 shuffles.
8588 ///
8589 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8590 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8591 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8592 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8593 /// back together.
8594 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8595                                        const X86Subtarget *Subtarget,
8596                                        SelectionDAG &DAG) {
8597   SDLoc DL(Op);
8598   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8599   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8600   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8601   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8602   ArrayRef<int> Mask = SVOp->getMask();
8603   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8604
8605   // Try to use shift instructions.
8606   if (SDValue Shift =
8607           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8608     return Shift;
8609
8610   // Try to use byte rotation instructions.
8611   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8612           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8613     return Rotate;
8614
8615   // Try to use a zext lowering.
8616   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8617           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8618     return ZExt;
8619
8620   int NumV2Elements =
8621       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8622
8623   // For single-input shuffles, there are some nicer lowering tricks we can use.
8624   if (NumV2Elements == 0) {
8625     // Check for being able to broadcast a single element.
8626     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8627                                                           Mask, Subtarget, DAG))
8628       return Broadcast;
8629
8630     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8631     // Notably, this handles splat and partial-splat shuffles more efficiently.
8632     // However, it only makes sense if the pre-duplication shuffle simplifies
8633     // things significantly. Currently, this means we need to be able to
8634     // express the pre-duplication shuffle as an i16 shuffle.
8635     //
8636     // FIXME: We should check for other patterns which can be widened into an
8637     // i16 shuffle as well.
8638     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8639       for (int i = 0; i < 16; i += 2)
8640         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8641           return false;
8642
8643       return true;
8644     };
8645     auto tryToWidenViaDuplication = [&]() -> SDValue {
8646       if (!canWidenViaDuplication(Mask))
8647         return SDValue();
8648       SmallVector<int, 4> LoInputs;
8649       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8650                    [](int M) { return M >= 0 && M < 8; });
8651       std::sort(LoInputs.begin(), LoInputs.end());
8652       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8653                      LoInputs.end());
8654       SmallVector<int, 4> HiInputs;
8655       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8656                    [](int M) { return M >= 8; });
8657       std::sort(HiInputs.begin(), HiInputs.end());
8658       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8659                      HiInputs.end());
8660
8661       bool TargetLo = LoInputs.size() >= HiInputs.size();
8662       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8663       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8664
8665       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8666       SmallDenseMap<int, int, 8> LaneMap;
8667       for (int I : InPlaceInputs) {
8668         PreDupI16Shuffle[I/2] = I/2;
8669         LaneMap[I] = I;
8670       }
8671       int j = TargetLo ? 0 : 4, je = j + 4;
8672       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8673         // Check if j is already a shuffle of this input. This happens when
8674         // there are two adjacent bytes after we move the low one.
8675         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8676           // If we haven't yet mapped the input, search for a slot into which
8677           // we can map it.
8678           while (j < je && PreDupI16Shuffle[j] != -1)
8679             ++j;
8680
8681           if (j == je)
8682             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8683             return SDValue();
8684
8685           // Map this input with the i16 shuffle.
8686           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8687         }
8688
8689         // Update the lane map based on the mapping we ended up with.
8690         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8691       }
8692       V1 = DAG.getNode(
8693           ISD::BITCAST, DL, MVT::v16i8,
8694           DAG.getVectorShuffle(MVT::v8i16, DL,
8695                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8696                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8697
8698       // Unpack the bytes to form the i16s that will be shuffled into place.
8699       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8700                        MVT::v16i8, V1, V1);
8701
8702       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8703       for (int i = 0; i < 16; ++i)
8704         if (Mask[i] != -1) {
8705           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8706           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8707           if (PostDupI16Shuffle[i / 2] == -1)
8708             PostDupI16Shuffle[i / 2] = MappedMask;
8709           else
8710             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8711                    "Conflicting entrties in the original shuffle!");
8712         }
8713       return DAG.getNode(
8714           ISD::BITCAST, DL, MVT::v16i8,
8715           DAG.getVectorShuffle(MVT::v8i16, DL,
8716                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8717                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8718     };
8719     if (SDValue V = tryToWidenViaDuplication())
8720       return V;
8721   }
8722
8723   // Use dedicated unpack instructions for masks that match their pattern.
8724   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8725                                          0, 16, 1, 17, 2, 18, 3, 19,
8726                                          // High half.
8727                                          4, 20, 5, 21, 6, 22, 7, 23}))
8728     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8729   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8730                                          8, 24, 9, 25, 10, 26, 11, 27,
8731                                          // High half.
8732                                          12, 28, 13, 29, 14, 30, 15, 31}))
8733     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8734
8735   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8736   // with PSHUFB. It is important to do this before we attempt to generate any
8737   // blends but after all of the single-input lowerings. If the single input
8738   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8739   // want to preserve that and we can DAG combine any longer sequences into
8740   // a PSHUFB in the end. But once we start blending from multiple inputs,
8741   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8742   // and there are *very* few patterns that would actually be faster than the
8743   // PSHUFB approach because of its ability to zero lanes.
8744   //
8745   // FIXME: The only exceptions to the above are blends which are exact
8746   // interleavings with direct instructions supporting them. We currently don't
8747   // handle those well here.
8748   if (Subtarget->hasSSSE3()) {
8749     bool V1InUse = false;
8750     bool V2InUse = false;
8751
8752     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8753                                                 DAG, V1InUse, V2InUse);
8754
8755     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8756     // do so. This avoids using them to handle blends-with-zero which is
8757     // important as a single pshufb is significantly faster for that.
8758     if (V1InUse && V2InUse) {
8759       if (Subtarget->hasSSE41())
8760         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8761                                                       Mask, Subtarget, DAG))
8762           return Blend;
8763
8764       // We can use an unpack to do the blending rather than an or in some
8765       // cases. Even though the or may be (very minorly) more efficient, we
8766       // preference this lowering because there are common cases where part of
8767       // the complexity of the shuffles goes away when we do the final blend as
8768       // an unpack.
8769       // FIXME: It might be worth trying to detect if the unpack-feeding
8770       // shuffles will both be pshufb, in which case we shouldn't bother with
8771       // this.
8772       if (SDValue Unpack =
8773               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8774         return Unpack;
8775     }
8776
8777     return PSHUFB;
8778   }
8779
8780   // There are special ways we can lower some single-element blends.
8781   if (NumV2Elements == 1)
8782     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8783                                                          Mask, Subtarget, DAG))
8784       return V;
8785
8786   if (SDValue BitBlend =
8787           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8788     return BitBlend;
8789
8790   // Check whether a compaction lowering can be done. This handles shuffles
8791   // which take every Nth element for some even N. See the helper function for
8792   // details.
8793   //
8794   // We special case these as they can be particularly efficiently handled with
8795   // the PACKUSB instruction on x86 and they show up in common patterns of
8796   // rearranging bytes to truncate wide elements.
8797   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8798     // NumEvenDrops is the power of two stride of the elements. Another way of
8799     // thinking about it is that we need to drop the even elements this many
8800     // times to get the original input.
8801     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8802
8803     // First we need to zero all the dropped bytes.
8804     assert(NumEvenDrops <= 3 &&
8805            "No support for dropping even elements more than 3 times.");
8806     // We use the mask type to pick which bytes are preserved based on how many
8807     // elements are dropped.
8808     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8809     SDValue ByteClearMask =
8810         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8811                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8812     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8813     if (!IsSingleInput)
8814       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8815
8816     // Now pack things back together.
8817     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8818     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8819     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8820     for (int i = 1; i < NumEvenDrops; ++i) {
8821       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8822       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8823     }
8824
8825     return Result;
8826   }
8827
8828   // Handle multi-input cases by blending single-input shuffles.
8829   if (NumV2Elements > 0)
8830     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8831                                                       Mask, DAG);
8832
8833   // The fallback path for single-input shuffles widens this into two v8i16
8834   // vectors with unpacks, shuffles those, and then pulls them back together
8835   // with a pack.
8836   SDValue V = V1;
8837
8838   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8839   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8840   for (int i = 0; i < 16; ++i)
8841     if (Mask[i] >= 0)
8842       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8843
8844   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8845
8846   SDValue VLoHalf, VHiHalf;
8847   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8848   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8849   // i16s.
8850   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8851                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8852       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8853                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8854     // Use a mask to drop the high bytes.
8855     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8856     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8857                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8858
8859     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8860     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8861
8862     // Squash the masks to point directly into VLoHalf.
8863     for (int &M : LoBlendMask)
8864       if (M >= 0)
8865         M /= 2;
8866     for (int &M : HiBlendMask)
8867       if (M >= 0)
8868         M /= 2;
8869   } else {
8870     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8871     // VHiHalf so that we can blend them as i16s.
8872     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8873                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8874     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8875                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8876   }
8877
8878   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8879   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8880
8881   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8882 }
8883
8884 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8885 ///
8886 /// This routine breaks down the specific type of 128-bit shuffle and
8887 /// dispatches to the lowering routines accordingly.
8888 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8889                                         MVT VT, const X86Subtarget *Subtarget,
8890                                         SelectionDAG &DAG) {
8891   switch (VT.SimpleTy) {
8892   case MVT::v2i64:
8893     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8894   case MVT::v2f64:
8895     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8896   case MVT::v4i32:
8897     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8898   case MVT::v4f32:
8899     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8900   case MVT::v8i16:
8901     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8902   case MVT::v16i8:
8903     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8904
8905   default:
8906     llvm_unreachable("Unimplemented!");
8907   }
8908 }
8909
8910 /// \brief Helper function to test whether a shuffle mask could be
8911 /// simplified by widening the elements being shuffled.
8912 ///
8913 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8914 /// leaves it in an unspecified state.
8915 ///
8916 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8917 /// shuffle masks. The latter have the special property of a '-2' representing
8918 /// a zero-ed lane of a vector.
8919 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8920                                     SmallVectorImpl<int> &WidenedMask) {
8921   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8922     // If both elements are undef, its trivial.
8923     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8924       WidenedMask.push_back(SM_SentinelUndef);
8925       continue;
8926     }
8927
8928     // Check for an undef mask and a mask value properly aligned to fit with
8929     // a pair of values. If we find such a case, use the non-undef mask's value.
8930     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8931       WidenedMask.push_back(Mask[i + 1] / 2);
8932       continue;
8933     }
8934     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8935       WidenedMask.push_back(Mask[i] / 2);
8936       continue;
8937     }
8938
8939     // When zeroing, we need to spread the zeroing across both lanes to widen.
8940     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8941       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8942           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8943         WidenedMask.push_back(SM_SentinelZero);
8944         continue;
8945       }
8946       return false;
8947     }
8948
8949     // Finally check if the two mask values are adjacent and aligned with
8950     // a pair.
8951     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8952       WidenedMask.push_back(Mask[i] / 2);
8953       continue;
8954     }
8955
8956     // Otherwise we can't safely widen the elements used in this shuffle.
8957     return false;
8958   }
8959   assert(WidenedMask.size() == Mask.size() / 2 &&
8960          "Incorrect size of mask after widening the elements!");
8961
8962   return true;
8963 }
8964
8965 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8966 ///
8967 /// This routine just extracts two subvectors, shuffles them independently, and
8968 /// then concatenates them back together. This should work effectively with all
8969 /// AVX vector shuffle types.
8970 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8971                                           SDValue V2, ArrayRef<int> Mask,
8972                                           SelectionDAG &DAG) {
8973   assert(VT.getSizeInBits() >= 256 &&
8974          "Only for 256-bit or wider vector shuffles!");
8975   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8976   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8977
8978   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8979   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8980
8981   int NumElements = VT.getVectorNumElements();
8982   int SplitNumElements = NumElements / 2;
8983   MVT ScalarVT = VT.getScalarType();
8984   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8985
8986   // Rather than splitting build-vectors, just build two narrower build
8987   // vectors. This helps shuffling with splats and zeros.
8988   auto SplitVector = [&](SDValue V) {
8989     while (V.getOpcode() == ISD::BITCAST)
8990       V = V->getOperand(0);
8991
8992     MVT OrigVT = V.getSimpleValueType();
8993     int OrigNumElements = OrigVT.getVectorNumElements();
8994     int OrigSplitNumElements = OrigNumElements / 2;
8995     MVT OrigScalarVT = OrigVT.getScalarType();
8996     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8997
8998     SDValue LoV, HiV;
8999
9000     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9001     if (!BV) {
9002       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9003                         DAG.getIntPtrConstant(0, DL));
9004       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9005                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9006     } else {
9007
9008       SmallVector<SDValue, 16> LoOps, HiOps;
9009       for (int i = 0; i < OrigSplitNumElements; ++i) {
9010         LoOps.push_back(BV->getOperand(i));
9011         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9012       }
9013       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9014       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9015     }
9016     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9017                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9018   };
9019
9020   SDValue LoV1, HiV1, LoV2, HiV2;
9021   std::tie(LoV1, HiV1) = SplitVector(V1);
9022   std::tie(LoV2, HiV2) = SplitVector(V2);
9023
9024   // Now create two 4-way blends of these half-width vectors.
9025   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9026     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9027     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9028     for (int i = 0; i < SplitNumElements; ++i) {
9029       int M = HalfMask[i];
9030       if (M >= NumElements) {
9031         if (M >= NumElements + SplitNumElements)
9032           UseHiV2 = true;
9033         else
9034           UseLoV2 = true;
9035         V2BlendMask.push_back(M - NumElements);
9036         V1BlendMask.push_back(-1);
9037         BlendMask.push_back(SplitNumElements + i);
9038       } else if (M >= 0) {
9039         if (M >= SplitNumElements)
9040           UseHiV1 = true;
9041         else
9042           UseLoV1 = true;
9043         V2BlendMask.push_back(-1);
9044         V1BlendMask.push_back(M);
9045         BlendMask.push_back(i);
9046       } else {
9047         V2BlendMask.push_back(-1);
9048         V1BlendMask.push_back(-1);
9049         BlendMask.push_back(-1);
9050       }
9051     }
9052
9053     // Because the lowering happens after all combining takes place, we need to
9054     // manually combine these blend masks as much as possible so that we create
9055     // a minimal number of high-level vector shuffle nodes.
9056
9057     // First try just blending the halves of V1 or V2.
9058     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9059       return DAG.getUNDEF(SplitVT);
9060     if (!UseLoV2 && !UseHiV2)
9061       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9062     if (!UseLoV1 && !UseHiV1)
9063       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9064
9065     SDValue V1Blend, V2Blend;
9066     if (UseLoV1 && UseHiV1) {
9067       V1Blend =
9068         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9069     } else {
9070       // We only use half of V1 so map the usage down into the final blend mask.
9071       V1Blend = UseLoV1 ? LoV1 : HiV1;
9072       for (int i = 0; i < SplitNumElements; ++i)
9073         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9074           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9075     }
9076     if (UseLoV2 && UseHiV2) {
9077       V2Blend =
9078         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9079     } else {
9080       // We only use half of V2 so map the usage down into the final blend mask.
9081       V2Blend = UseLoV2 ? LoV2 : HiV2;
9082       for (int i = 0; i < SplitNumElements; ++i)
9083         if (BlendMask[i] >= SplitNumElements)
9084           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9085     }
9086     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9087   };
9088   SDValue Lo = HalfBlend(LoMask);
9089   SDValue Hi = HalfBlend(HiMask);
9090   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9091 }
9092
9093 /// \brief Either split a vector in halves or decompose the shuffles and the
9094 /// blend.
9095 ///
9096 /// This is provided as a good fallback for many lowerings of non-single-input
9097 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9098 /// between splitting the shuffle into 128-bit components and stitching those
9099 /// back together vs. extracting the single-input shuffles and blending those
9100 /// results.
9101 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9102                                                 SDValue V2, ArrayRef<int> Mask,
9103                                                 SelectionDAG &DAG) {
9104   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9105                                             "lower single-input shuffles as it "
9106                                             "could then recurse on itself.");
9107   int Size = Mask.size();
9108
9109   // If this can be modeled as a broadcast of two elements followed by a blend,
9110   // prefer that lowering. This is especially important because broadcasts can
9111   // often fold with memory operands.
9112   auto DoBothBroadcast = [&] {
9113     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9114     for (int M : Mask)
9115       if (M >= Size) {
9116         if (V2BroadcastIdx == -1)
9117           V2BroadcastIdx = M - Size;
9118         else if (M - Size != V2BroadcastIdx)
9119           return false;
9120       } else if (M >= 0) {
9121         if (V1BroadcastIdx == -1)
9122           V1BroadcastIdx = M;
9123         else if (M != V1BroadcastIdx)
9124           return false;
9125       }
9126     return true;
9127   };
9128   if (DoBothBroadcast())
9129     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9130                                                       DAG);
9131
9132   // If the inputs all stem from a single 128-bit lane of each input, then we
9133   // split them rather than blending because the split will decompose to
9134   // unusually few instructions.
9135   int LaneCount = VT.getSizeInBits() / 128;
9136   int LaneSize = Size / LaneCount;
9137   SmallBitVector LaneInputs[2];
9138   LaneInputs[0].resize(LaneCount, false);
9139   LaneInputs[1].resize(LaneCount, false);
9140   for (int i = 0; i < Size; ++i)
9141     if (Mask[i] >= 0)
9142       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9143   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9144     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9145
9146   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9147   // that the decomposed single-input shuffles don't end up here.
9148   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9149 }
9150
9151 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9152 /// a permutation and blend of those lanes.
9153 ///
9154 /// This essentially blends the out-of-lane inputs to each lane into the lane
9155 /// from a permuted copy of the vector. This lowering strategy results in four
9156 /// instructions in the worst case for a single-input cross lane shuffle which
9157 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9158 /// of. Special cases for each particular shuffle pattern should be handled
9159 /// prior to trying this lowering.
9160 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9161                                                        SDValue V1, SDValue V2,
9162                                                        ArrayRef<int> Mask,
9163                                                        SelectionDAG &DAG) {
9164   // FIXME: This should probably be generalized for 512-bit vectors as well.
9165   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9166   int LaneSize = Mask.size() / 2;
9167
9168   // If there are only inputs from one 128-bit lane, splitting will in fact be
9169   // less expensive. The flags track whether the given lane contains an element
9170   // that crosses to another lane.
9171   bool LaneCrossing[2] = {false, false};
9172   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9173     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9174       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9175   if (!LaneCrossing[0] || !LaneCrossing[1])
9176     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9177
9178   if (isSingleInputShuffleMask(Mask)) {
9179     SmallVector<int, 32> FlippedBlendMask;
9180     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9181       FlippedBlendMask.push_back(
9182           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9183                                   ? Mask[i]
9184                                   : Mask[i] % LaneSize +
9185                                         (i / LaneSize) * LaneSize + Size));
9186
9187     // Flip the vector, and blend the results which should now be in-lane. The
9188     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9189     // 5 for the high source. The value 3 selects the high half of source 2 and
9190     // the value 2 selects the low half of source 2. We only use source 2 to
9191     // allow folding it into a memory operand.
9192     unsigned PERMMask = 3 | 2 << 4;
9193     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9194                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9195     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9196   }
9197
9198   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9199   // will be handled by the above logic and a blend of the results, much like
9200   // other patterns in AVX.
9201   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9202 }
9203
9204 /// \brief Handle lowering 2-lane 128-bit shuffles.
9205 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9206                                         SDValue V2, ArrayRef<int> Mask,
9207                                         const X86Subtarget *Subtarget,
9208                                         SelectionDAG &DAG) {
9209   // TODO: If minimizing size and one of the inputs is a zero vector and the
9210   // the zero vector has only one use, we could use a VPERM2X128 to save the
9211   // instruction bytes needed to explicitly generate the zero vector.
9212
9213   // Blends are faster and handle all the non-lane-crossing cases.
9214   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9215                                                 Subtarget, DAG))
9216     return Blend;
9217
9218   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9219   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9220
9221   // If either input operand is a zero vector, use VPERM2X128 because its mask
9222   // allows us to replace the zero input with an implicit zero.
9223   if (!IsV1Zero && !IsV2Zero) {
9224     // Check for patterns which can be matched with a single insert of a 128-bit
9225     // subvector.
9226     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9227     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9228       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9229                                    VT.getVectorNumElements() / 2);
9230       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9231                                 DAG.getIntPtrConstant(0, DL));
9232       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9233                                 OnlyUsesV1 ? V1 : V2,
9234                                 DAG.getIntPtrConstant(0, DL));
9235       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9236     }
9237   }
9238
9239   // Otherwise form a 128-bit permutation. After accounting for undefs,
9240   // convert the 64-bit shuffle mask selection values into 128-bit
9241   // selection bits by dividing the indexes by 2 and shifting into positions
9242   // defined by a vperm2*128 instruction's immediate control byte.
9243
9244   // The immediate permute control byte looks like this:
9245   //    [1:0] - select 128 bits from sources for low half of destination
9246   //    [2]   - ignore
9247   //    [3]   - zero low half of destination
9248   //    [5:4] - select 128 bits from sources for high half of destination
9249   //    [6]   - ignore
9250   //    [7]   - zero high half of destination
9251
9252   int MaskLO = Mask[0];
9253   if (MaskLO == SM_SentinelUndef)
9254     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9255
9256   int MaskHI = Mask[2];
9257   if (MaskHI == SM_SentinelUndef)
9258     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9259
9260   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9261
9262   // If either input is a zero vector, replace it with an undef input.
9263   // Shuffle mask values <  4 are selecting elements of V1.
9264   // Shuffle mask values >= 4 are selecting elements of V2.
9265   // Adjust each half of the permute mask by clearing the half that was
9266   // selecting the zero vector and setting the zero mask bit.
9267   if (IsV1Zero) {
9268     V1 = DAG.getUNDEF(VT);
9269     if (MaskLO < 4)
9270       PermMask = (PermMask & 0xf0) | 0x08;
9271     if (MaskHI < 4)
9272       PermMask = (PermMask & 0x0f) | 0x80;
9273   }
9274   if (IsV2Zero) {
9275     V2 = DAG.getUNDEF(VT);
9276     if (MaskLO >= 4)
9277       PermMask = (PermMask & 0xf0) | 0x08;
9278     if (MaskHI >= 4)
9279       PermMask = (PermMask & 0x0f) | 0x80;
9280   }
9281
9282   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9283                      DAG.getConstant(PermMask, DL, MVT::i8));
9284 }
9285
9286 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9287 /// shuffling each lane.
9288 ///
9289 /// This will only succeed when the result of fixing the 128-bit lanes results
9290 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9291 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9292 /// the lane crosses early and then use simpler shuffles within each lane.
9293 ///
9294 /// FIXME: It might be worthwhile at some point to support this without
9295 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9296 /// in x86 only floating point has interesting non-repeating shuffles, and even
9297 /// those are still *marginally* more expensive.
9298 static SDValue lowerVectorShuffleByMerging128BitLanes(
9299     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9300     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9301   assert(!isSingleInputShuffleMask(Mask) &&
9302          "This is only useful with multiple inputs.");
9303
9304   int Size = Mask.size();
9305   int LaneSize = 128 / VT.getScalarSizeInBits();
9306   int NumLanes = Size / LaneSize;
9307   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9308
9309   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9310   // check whether the in-128-bit lane shuffles share a repeating pattern.
9311   SmallVector<int, 4> Lanes;
9312   Lanes.resize(NumLanes, -1);
9313   SmallVector<int, 4> InLaneMask;
9314   InLaneMask.resize(LaneSize, -1);
9315   for (int i = 0; i < Size; ++i) {
9316     if (Mask[i] < 0)
9317       continue;
9318
9319     int j = i / LaneSize;
9320
9321     if (Lanes[j] < 0) {
9322       // First entry we've seen for this lane.
9323       Lanes[j] = Mask[i] / LaneSize;
9324     } else if (Lanes[j] != Mask[i] / LaneSize) {
9325       // This doesn't match the lane selected previously!
9326       return SDValue();
9327     }
9328
9329     // Check that within each lane we have a consistent shuffle mask.
9330     int k = i % LaneSize;
9331     if (InLaneMask[k] < 0) {
9332       InLaneMask[k] = Mask[i] % LaneSize;
9333     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9334       // This doesn't fit a repeating in-lane mask.
9335       return SDValue();
9336     }
9337   }
9338
9339   // First shuffle the lanes into place.
9340   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9341                                 VT.getSizeInBits() / 64);
9342   SmallVector<int, 8> LaneMask;
9343   LaneMask.resize(NumLanes * 2, -1);
9344   for (int i = 0; i < NumLanes; ++i)
9345     if (Lanes[i] >= 0) {
9346       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9347       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9348     }
9349
9350   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9351   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9352   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9353
9354   // Cast it back to the type we actually want.
9355   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9356
9357   // Now do a simple shuffle that isn't lane crossing.
9358   SmallVector<int, 8> NewMask;
9359   NewMask.resize(Size, -1);
9360   for (int i = 0; i < Size; ++i)
9361     if (Mask[i] >= 0)
9362       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9363   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9364          "Must not introduce lane crosses at this point!");
9365
9366   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9367 }
9368
9369 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9370 /// given mask.
9371 ///
9372 /// This returns true if the elements from a particular input are already in the
9373 /// slot required by the given mask and require no permutation.
9374 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9375   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9376   int Size = Mask.size();
9377   for (int i = 0; i < Size; ++i)
9378     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9379       return false;
9380
9381   return true;
9382 }
9383
9384 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9385 ///
9386 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9387 /// isn't available.
9388 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9389                                        const X86Subtarget *Subtarget,
9390                                        SelectionDAG &DAG) {
9391   SDLoc DL(Op);
9392   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9393   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9394   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9395   ArrayRef<int> Mask = SVOp->getMask();
9396   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9397
9398   SmallVector<int, 4> WidenedMask;
9399   if (canWidenShuffleElements(Mask, WidenedMask))
9400     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9401                                     DAG);
9402
9403   if (isSingleInputShuffleMask(Mask)) {
9404     // Check for being able to broadcast a single element.
9405     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9406                                                           Mask, Subtarget, DAG))
9407       return Broadcast;
9408
9409     // Use low duplicate instructions for masks that match their pattern.
9410     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9411       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9412
9413     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9414       // Non-half-crossing single input shuffles can be lowerid with an
9415       // interleaved permutation.
9416       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9417                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9418       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9419                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9420     }
9421
9422     // With AVX2 we have direct support for this permutation.
9423     if (Subtarget->hasAVX2())
9424       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9425                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9426
9427     // Otherwise, fall back.
9428     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9429                                                    DAG);
9430   }
9431
9432   // X86 has dedicated unpack instructions that can handle specific blend
9433   // operations: UNPCKH and UNPCKL.
9434   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9435     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9436   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9437     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9438   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9439     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9440   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9441     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9442
9443   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9444                                                 Subtarget, DAG))
9445     return Blend;
9446
9447   // Check if the blend happens to exactly fit that of SHUFPD.
9448   if ((Mask[0] == -1 || Mask[0] < 2) &&
9449       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9450       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9451       (Mask[3] == -1 || Mask[3] >= 6)) {
9452     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9453                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9454     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9455                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9456   }
9457   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9458       (Mask[1] == -1 || Mask[1] < 2) &&
9459       (Mask[2] == -1 || Mask[2] >= 6) &&
9460       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9461     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9462                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9463     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9464                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9465   }
9466
9467   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9468   // shuffle. However, if we have AVX2 and either inputs are already in place,
9469   // we will be able to shuffle even across lanes the other input in a single
9470   // instruction so skip this pattern.
9471   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9472                                  isShuffleMaskInputInPlace(1, Mask))))
9473     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9474             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9475       return Result;
9476
9477   // If we have AVX2 then we always want to lower with a blend because an v4 we
9478   // can fully permute the elements.
9479   if (Subtarget->hasAVX2())
9480     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9481                                                       Mask, DAG);
9482
9483   // Otherwise fall back on generic lowering.
9484   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9485 }
9486
9487 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9488 ///
9489 /// This routine is only called when we have AVX2 and thus a reasonable
9490 /// instruction set for v4i64 shuffling..
9491 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9492                                        const X86Subtarget *Subtarget,
9493                                        SelectionDAG &DAG) {
9494   SDLoc DL(Op);
9495   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9496   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9497   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9498   ArrayRef<int> Mask = SVOp->getMask();
9499   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9500   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9501
9502   SmallVector<int, 4> WidenedMask;
9503   if (canWidenShuffleElements(Mask, WidenedMask))
9504     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9505                                     DAG);
9506
9507   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9508                                                 Subtarget, DAG))
9509     return Blend;
9510
9511   // Check for being able to broadcast a single element.
9512   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9513                                                         Mask, Subtarget, DAG))
9514     return Broadcast;
9515
9516   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9517   // use lower latency instructions that will operate on both 128-bit lanes.
9518   SmallVector<int, 2> RepeatedMask;
9519   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9520     if (isSingleInputShuffleMask(Mask)) {
9521       int PSHUFDMask[] = {-1, -1, -1, -1};
9522       for (int i = 0; i < 2; ++i)
9523         if (RepeatedMask[i] >= 0) {
9524           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9525           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9526         }
9527       return DAG.getNode(
9528           ISD::BITCAST, DL, MVT::v4i64,
9529           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9530                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9531                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9532     }
9533   }
9534
9535   // AVX2 provides a direct instruction for permuting a single input across
9536   // lanes.
9537   if (isSingleInputShuffleMask(Mask))
9538     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9539                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9540
9541   // Try to use shift instructions.
9542   if (SDValue Shift =
9543           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9544     return Shift;
9545
9546   // Use dedicated unpack instructions for masks that match their pattern.
9547   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9548     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9549   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9550     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9551   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9552     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9553   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9554     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9555
9556   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9557   // shuffle. However, if we have AVX2 and either inputs are already in place,
9558   // we will be able to shuffle even across lanes the other input in a single
9559   // instruction so skip this pattern.
9560   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9561                                  isShuffleMaskInputInPlace(1, Mask))))
9562     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9563             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9564       return Result;
9565
9566   // Otherwise fall back on generic blend lowering.
9567   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9568                                                     Mask, DAG);
9569 }
9570
9571 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9572 ///
9573 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9574 /// isn't available.
9575 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9576                                        const X86Subtarget *Subtarget,
9577                                        SelectionDAG &DAG) {
9578   SDLoc DL(Op);
9579   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9580   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9581   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9582   ArrayRef<int> Mask = SVOp->getMask();
9583   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9584
9585   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, 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::v8f32, V1,
9591                                                         Mask, Subtarget, DAG))
9592     return Broadcast;
9593
9594   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9595   // options to efficiently lower the shuffle.
9596   SmallVector<int, 4> RepeatedMask;
9597   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9598     assert(RepeatedMask.size() == 4 &&
9599            "Repeated masks must be half the mask width!");
9600
9601     // Use even/odd duplicate instructions for masks that match their pattern.
9602     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9603       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9604     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9605       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9606
9607     if (isSingleInputShuffleMask(Mask))
9608       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9609                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9610
9611     // Use dedicated unpack instructions for masks that match their pattern.
9612     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9613       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9614     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9615       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9616     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9617       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9618     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9619       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9620
9621     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9622     // have already handled any direct blends. We also need to squash the
9623     // repeated mask into a simulated v4f32 mask.
9624     for (int i = 0; i < 4; ++i)
9625       if (RepeatedMask[i] >= 8)
9626         RepeatedMask[i] -= 4;
9627     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9628   }
9629
9630   // If we have a single input shuffle with different shuffle patterns in the
9631   // two 128-bit lanes use the variable mask to VPERMILPS.
9632   if (isSingleInputShuffleMask(Mask)) {
9633     SDValue VPermMask[8];
9634     for (int i = 0; i < 8; ++i)
9635       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9636                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9637     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9638       return DAG.getNode(
9639           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9640           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9641
9642     if (Subtarget->hasAVX2())
9643       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9644                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9645                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9646                                                  MVT::v8i32, VPermMask)),
9647                          V1);
9648
9649     // Otherwise, fall back.
9650     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9651                                                    DAG);
9652   }
9653
9654   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9655   // shuffle.
9656   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9657           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9658     return Result;
9659
9660   // If we have AVX2 then we always want to lower with a blend because at v8 we
9661   // can fully permute the elements.
9662   if (Subtarget->hasAVX2())
9663     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9664                                                       Mask, DAG);
9665
9666   // Otherwise fall back on generic lowering.
9667   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9668 }
9669
9670 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9671 ///
9672 /// This routine is only called when we have AVX2 and thus a reasonable
9673 /// instruction set for v8i32 shuffling..
9674 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9675                                        const X86Subtarget *Subtarget,
9676                                        SelectionDAG &DAG) {
9677   SDLoc DL(Op);
9678   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9679   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9680   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9681   ArrayRef<int> Mask = SVOp->getMask();
9682   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9683   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9684
9685   // Whenever we can lower this as a zext, that instruction is strictly faster
9686   // than any alternative. It also allows us to fold memory operands into the
9687   // shuffle in many cases.
9688   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9689                                                          Mask, Subtarget, DAG))
9690     return ZExt;
9691
9692   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9693                                                 Subtarget, DAG))
9694     return Blend;
9695
9696   // Check for being able to broadcast a single element.
9697   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9698                                                         Mask, Subtarget, DAG))
9699     return Broadcast;
9700
9701   // If the shuffle mask is repeated in each 128-bit lane we can use more
9702   // efficient instructions that mirror the shuffles across the two 128-bit
9703   // lanes.
9704   SmallVector<int, 4> RepeatedMask;
9705   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9706     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9707     if (isSingleInputShuffleMask(Mask))
9708       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9709                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9710
9711     // Use dedicated unpack instructions for masks that match their pattern.
9712     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9713       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9714     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9715       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9716     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9717       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9718     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9719       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9720   }
9721
9722   // Try to use shift instructions.
9723   if (SDValue Shift =
9724           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9725     return Shift;
9726
9727   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9728           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9729     return Rotate;
9730
9731   // If the shuffle patterns aren't repeated but it is a single input, directly
9732   // generate a cross-lane VPERMD instruction.
9733   if (isSingleInputShuffleMask(Mask)) {
9734     SDValue VPermMask[8];
9735     for (int i = 0; i < 8; ++i)
9736       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9737                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9738     return DAG.getNode(
9739         X86ISD::VPERMV, DL, MVT::v8i32,
9740         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9741   }
9742
9743   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9744   // shuffle.
9745   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9746           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9747     return Result;
9748
9749   // Otherwise fall back on generic blend lowering.
9750   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9751                                                     Mask, DAG);
9752 }
9753
9754 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9755 ///
9756 /// This routine is only called when we have AVX2 and thus a reasonable
9757 /// instruction set for v16i16 shuffling..
9758 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9759                                         const X86Subtarget *Subtarget,
9760                                         SelectionDAG &DAG) {
9761   SDLoc DL(Op);
9762   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9763   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9764   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9765   ArrayRef<int> Mask = SVOp->getMask();
9766   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9767   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9768
9769   // Whenever we can lower this as a zext, that instruction is strictly faster
9770   // than any alternative. It also allows us to fold memory operands into the
9771   // shuffle in many cases.
9772   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9773                                                          Mask, Subtarget, DAG))
9774     return ZExt;
9775
9776   // Check for being able to broadcast a single element.
9777   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9778                                                         Mask, Subtarget, DAG))
9779     return Broadcast;
9780
9781   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9782                                                 Subtarget, DAG))
9783     return Blend;
9784
9785   // Use dedicated unpack instructions for masks that match their pattern.
9786   if (isShuffleEquivalent(V1, V2, Mask,
9787                           {// First 128-bit lane:
9788                            0, 16, 1, 17, 2, 18, 3, 19,
9789                            // Second 128-bit lane:
9790                            8, 24, 9, 25, 10, 26, 11, 27}))
9791     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9792   if (isShuffleEquivalent(V1, V2, Mask,
9793                           {// First 128-bit lane:
9794                            4, 20, 5, 21, 6, 22, 7, 23,
9795                            // Second 128-bit lane:
9796                            12, 28, 13, 29, 14, 30, 15, 31}))
9797     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9798
9799   // Try to use shift instructions.
9800   if (SDValue Shift =
9801           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9802     return Shift;
9803
9804   // Try to use byte rotation instructions.
9805   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9806           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9807     return Rotate;
9808
9809   if (isSingleInputShuffleMask(Mask)) {
9810     // There are no generalized cross-lane shuffle operations available on i16
9811     // element types.
9812     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9813       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9814                                                      Mask, DAG);
9815
9816     SmallVector<int, 8> RepeatedMask;
9817     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9818       // As this is a single-input shuffle, the repeated mask should be
9819       // a strictly valid v8i16 mask that we can pass through to the v8i16
9820       // lowering to handle even the v16 case.
9821       return lowerV8I16GeneralSingleInputVectorShuffle(
9822           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9823     }
9824
9825     SDValue PSHUFBMask[32];
9826     for (int i = 0; i < 16; ++i) {
9827       if (Mask[i] == -1) {
9828         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9829         continue;
9830       }
9831
9832       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9833       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9834       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9835       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9836     }
9837     return DAG.getNode(
9838         ISD::BITCAST, DL, MVT::v16i16,
9839         DAG.getNode(
9840             X86ISD::PSHUFB, DL, MVT::v32i8,
9841             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9842             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9843   }
9844
9845   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9846   // shuffle.
9847   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9848           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9849     return Result;
9850
9851   // Otherwise fall back on generic lowering.
9852   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9853 }
9854
9855 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9856 ///
9857 /// This routine is only called when we have AVX2 and thus a reasonable
9858 /// instruction set for v32i8 shuffling..
9859 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9860                                        const X86Subtarget *Subtarget,
9861                                        SelectionDAG &DAG) {
9862   SDLoc DL(Op);
9863   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9864   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9865   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9866   ArrayRef<int> Mask = SVOp->getMask();
9867   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9868   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9869
9870   // Whenever we can lower this as a zext, that instruction is strictly faster
9871   // than any alternative. It also allows us to fold memory operands into the
9872   // shuffle in many cases.
9873   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9874                                                          Mask, Subtarget, DAG))
9875     return ZExt;
9876
9877   // Check for being able to broadcast a single element.
9878   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9879                                                         Mask, Subtarget, DAG))
9880     return Broadcast;
9881
9882   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9883                                                 Subtarget, DAG))
9884     return Blend;
9885
9886   // Use dedicated unpack instructions for masks that match their pattern.
9887   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9888   // 256-bit lanes.
9889   if (isShuffleEquivalent(
9890           V1, V2, Mask,
9891           {// First 128-bit lane:
9892            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9893            // Second 128-bit lane:
9894            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9895     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9896   if (isShuffleEquivalent(
9897           V1, V2, Mask,
9898           {// First 128-bit lane:
9899            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9900            // Second 128-bit lane:
9901            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9902     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9903
9904   // Try to use shift instructions.
9905   if (SDValue Shift =
9906           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9907     return Shift;
9908
9909   // Try to use byte rotation instructions.
9910   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9911           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9912     return Rotate;
9913
9914   if (isSingleInputShuffleMask(Mask)) {
9915     // There are no generalized cross-lane shuffle operations available on i8
9916     // element types.
9917     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9918       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9919                                                      Mask, DAG);
9920
9921     SDValue PSHUFBMask[32];
9922     for (int i = 0; i < 32; ++i)
9923       PSHUFBMask[i] =
9924           Mask[i] < 0
9925               ? DAG.getUNDEF(MVT::i8)
9926               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9927                                 MVT::i8);
9928
9929     return DAG.getNode(
9930         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9931         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9932   }
9933
9934   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9935   // shuffle.
9936   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9937           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9938     return Result;
9939
9940   // Otherwise fall back on generic lowering.
9941   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9942 }
9943
9944 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9945 ///
9946 /// This routine either breaks down the specific type of a 256-bit x86 vector
9947 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9948 /// together based on the available instructions.
9949 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9950                                         MVT VT, const X86Subtarget *Subtarget,
9951                                         SelectionDAG &DAG) {
9952   SDLoc DL(Op);
9953   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9954   ArrayRef<int> Mask = SVOp->getMask();
9955
9956   // If we have a single input to the zero element, insert that into V1 if we
9957   // can do so cheaply.
9958   int NumElts = VT.getVectorNumElements();
9959   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9960     return M >= NumElts;
9961   });
9962
9963   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9964     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9965                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9966       return Insertion;
9967
9968   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9969   // check for those subtargets here and avoid much of the subtarget querying in
9970   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9971   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9972   // floating point types there eventually, just immediately cast everything to
9973   // a float and operate entirely in that domain.
9974   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9975     int ElementBits = VT.getScalarSizeInBits();
9976     if (ElementBits < 32)
9977       // No floating point type available, decompose into 128-bit vectors.
9978       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9979
9980     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9981                                 VT.getVectorNumElements());
9982     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9983     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9984     return DAG.getNode(ISD::BITCAST, DL, VT,
9985                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9986   }
9987
9988   switch (VT.SimpleTy) {
9989   case MVT::v4f64:
9990     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9991   case MVT::v4i64:
9992     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9993   case MVT::v8f32:
9994     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9995   case MVT::v8i32:
9996     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9997   case MVT::v16i16:
9998     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9999   case MVT::v32i8:
10000     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10001
10002   default:
10003     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10004   }
10005 }
10006
10007 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10008 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10009                                        const X86Subtarget *Subtarget,
10010                                        SelectionDAG &DAG) {
10011   SDLoc DL(Op);
10012   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10013   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10014   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10015   ArrayRef<int> Mask = SVOp->getMask();
10016   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10017
10018   // X86 has dedicated unpack instructions that can handle specific blend
10019   // operations: UNPCKH and UNPCKL.
10020   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10021     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10022   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10023     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10024
10025   // FIXME: Implement direct support for this type!
10026   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10027 }
10028
10029 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10030 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10031                                        const X86Subtarget *Subtarget,
10032                                        SelectionDAG &DAG) {
10033   SDLoc DL(Op);
10034   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10035   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10036   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10037   ArrayRef<int> Mask = SVOp->getMask();
10038   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10039
10040   // Use dedicated unpack instructions for masks that match their pattern.
10041   if (isShuffleEquivalent(V1, V2, Mask,
10042                           {// First 128-bit lane.
10043                            0, 16, 1, 17, 4, 20, 5, 21,
10044                            // Second 128-bit lane.
10045                            8, 24, 9, 25, 12, 28, 13, 29}))
10046     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10047   if (isShuffleEquivalent(V1, V2, Mask,
10048                           {// First 128-bit lane.
10049                            2, 18, 3, 19, 6, 22, 7, 23,
10050                            // Second 128-bit lane.
10051                            10, 26, 11, 27, 14, 30, 15, 31}))
10052     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10053
10054   // FIXME: Implement direct support for this type!
10055   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10056 }
10057
10058 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10059 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10060                                        const X86Subtarget *Subtarget,
10061                                        SelectionDAG &DAG) {
10062   SDLoc DL(Op);
10063   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10064   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10065   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10066   ArrayRef<int> Mask = SVOp->getMask();
10067   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10068
10069   // X86 has dedicated unpack instructions that can handle specific blend
10070   // operations: UNPCKH and UNPCKL.
10071   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10072     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10073   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10074     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10075
10076   // FIXME: Implement direct support for this type!
10077   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10078 }
10079
10080 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10081 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10082                                        const X86Subtarget *Subtarget,
10083                                        SelectionDAG &DAG) {
10084   SDLoc DL(Op);
10085   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10086   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10087   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10088   ArrayRef<int> Mask = SVOp->getMask();
10089   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10090
10091   // Use dedicated unpack instructions for masks that match their pattern.
10092   if (isShuffleEquivalent(V1, V2, Mask,
10093                           {// First 128-bit lane.
10094                            0, 16, 1, 17, 4, 20, 5, 21,
10095                            // Second 128-bit lane.
10096                            8, 24, 9, 25, 12, 28, 13, 29}))
10097     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10098   if (isShuffleEquivalent(V1, V2, Mask,
10099                           {// First 128-bit lane.
10100                            2, 18, 3, 19, 6, 22, 7, 23,
10101                            // Second 128-bit lane.
10102                            10, 26, 11, 27, 14, 30, 15, 31}))
10103     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10104
10105   // FIXME: Implement direct support for this type!
10106   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10107 }
10108
10109 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10110 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10111                                         const X86Subtarget *Subtarget,
10112                                         SelectionDAG &DAG) {
10113   SDLoc DL(Op);
10114   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10115   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10116   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10117   ArrayRef<int> Mask = SVOp->getMask();
10118   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10119   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10120
10121   // FIXME: Implement direct support for this type!
10122   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10123 }
10124
10125 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10126 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10127                                        const X86Subtarget *Subtarget,
10128                                        SelectionDAG &DAG) {
10129   SDLoc DL(Op);
10130   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10131   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10132   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10133   ArrayRef<int> Mask = SVOp->getMask();
10134   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10135   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10136
10137   // FIXME: Implement direct support for this type!
10138   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10139 }
10140
10141 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10142 ///
10143 /// This routine either breaks down the specific type of a 512-bit x86 vector
10144 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10145 /// together based on the available instructions.
10146 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10147                                         MVT VT, const X86Subtarget *Subtarget,
10148                                         SelectionDAG &DAG) {
10149   SDLoc DL(Op);
10150   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10151   ArrayRef<int> Mask = SVOp->getMask();
10152   assert(Subtarget->hasAVX512() &&
10153          "Cannot lower 512-bit vectors w/ basic ISA!");
10154
10155   // Check for being able to broadcast a single element.
10156   if (SDValue Broadcast =
10157           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10158     return Broadcast;
10159
10160   // Dispatch to each element type for lowering. If we don't have supprot for
10161   // specific element type shuffles at 512 bits, immediately split them and
10162   // lower them. Each lowering routine of a given type is allowed to assume that
10163   // the requisite ISA extensions for that element type are available.
10164   switch (VT.SimpleTy) {
10165   case MVT::v8f64:
10166     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10167   case MVT::v16f32:
10168     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10169   case MVT::v8i64:
10170     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10171   case MVT::v16i32:
10172     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10173   case MVT::v32i16:
10174     if (Subtarget->hasBWI())
10175       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10176     break;
10177   case MVT::v64i8:
10178     if (Subtarget->hasBWI())
10179       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10180     break;
10181
10182   default:
10183     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10184   }
10185
10186   // Otherwise fall back on splitting.
10187   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10188 }
10189
10190 /// \brief Top-level lowering for x86 vector shuffles.
10191 ///
10192 /// This handles decomposition, canonicalization, and lowering of all x86
10193 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10194 /// above in helper routines. The canonicalization attempts to widen shuffles
10195 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10196 /// s.t. only one of the two inputs needs to be tested, etc.
10197 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10198                                   SelectionDAG &DAG) {
10199   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10200   ArrayRef<int> Mask = SVOp->getMask();
10201   SDValue V1 = Op.getOperand(0);
10202   SDValue V2 = Op.getOperand(1);
10203   MVT VT = Op.getSimpleValueType();
10204   int NumElements = VT.getVectorNumElements();
10205   SDLoc dl(Op);
10206
10207   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10208
10209   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10210   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10211   if (V1IsUndef && V2IsUndef)
10212     return DAG.getUNDEF(VT);
10213
10214   // When we create a shuffle node we put the UNDEF node to second operand,
10215   // but in some cases the first operand may be transformed to UNDEF.
10216   // In this case we should just commute the node.
10217   if (V1IsUndef)
10218     return DAG.getCommutedVectorShuffle(*SVOp);
10219
10220   // Check for non-undef masks pointing at an undef vector and make the masks
10221   // undef as well. This makes it easier to match the shuffle based solely on
10222   // the mask.
10223   if (V2IsUndef)
10224     for (int M : Mask)
10225       if (M >= NumElements) {
10226         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10227         for (int &M : NewMask)
10228           if (M >= NumElements)
10229             M = -1;
10230         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10231       }
10232
10233   // We actually see shuffles that are entirely re-arrangements of a set of
10234   // zero inputs. This mostly happens while decomposing complex shuffles into
10235   // simple ones. Directly lower these as a buildvector of zeros.
10236   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10237   if (Zeroable.all())
10238     return getZeroVector(VT, Subtarget, DAG, dl);
10239
10240   // Try to collapse shuffles into using a vector type with fewer elements but
10241   // wider element types. We cap this to not form integers or floating point
10242   // elements wider than 64 bits, but it might be interesting to form i128
10243   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10244   SmallVector<int, 16> WidenedMask;
10245   if (VT.getScalarSizeInBits() < 64 &&
10246       canWidenShuffleElements(Mask, WidenedMask)) {
10247     MVT NewEltVT = VT.isFloatingPoint()
10248                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10249                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10250     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10251     // Make sure that the new vector type is legal. For example, v2f64 isn't
10252     // legal on SSE1.
10253     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10254       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10255       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10256       return DAG.getNode(ISD::BITCAST, dl, VT,
10257                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10258     }
10259   }
10260
10261   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10262   for (int M : SVOp->getMask())
10263     if (M < 0)
10264       ++NumUndefElements;
10265     else if (M < NumElements)
10266       ++NumV1Elements;
10267     else
10268       ++NumV2Elements;
10269
10270   // Commute the shuffle as needed such that more elements come from V1 than
10271   // V2. This allows us to match the shuffle pattern strictly on how many
10272   // elements come from V1 without handling the symmetric cases.
10273   if (NumV2Elements > NumV1Elements)
10274     return DAG.getCommutedVectorShuffle(*SVOp);
10275
10276   // When the number of V1 and V2 elements are the same, try to minimize the
10277   // number of uses of V2 in the low half of the vector. When that is tied,
10278   // ensure that the sum of indices for V1 is equal to or lower than the sum
10279   // indices for V2. When those are equal, try to ensure that the number of odd
10280   // indices for V1 is lower than the number of odd indices for V2.
10281   if (NumV1Elements == NumV2Elements) {
10282     int LowV1Elements = 0, LowV2Elements = 0;
10283     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10284       if (M >= NumElements)
10285         ++LowV2Elements;
10286       else if (M >= 0)
10287         ++LowV1Elements;
10288     if (LowV2Elements > LowV1Elements) {
10289       return DAG.getCommutedVectorShuffle(*SVOp);
10290     } else if (LowV2Elements == LowV1Elements) {
10291       int SumV1Indices = 0, SumV2Indices = 0;
10292       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10293         if (SVOp->getMask()[i] >= NumElements)
10294           SumV2Indices += i;
10295         else if (SVOp->getMask()[i] >= 0)
10296           SumV1Indices += i;
10297       if (SumV2Indices < SumV1Indices) {
10298         return DAG.getCommutedVectorShuffle(*SVOp);
10299       } else if (SumV2Indices == SumV1Indices) {
10300         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10301         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10302           if (SVOp->getMask()[i] >= NumElements)
10303             NumV2OddIndices += i % 2;
10304           else if (SVOp->getMask()[i] >= 0)
10305             NumV1OddIndices += i % 2;
10306         if (NumV2OddIndices < NumV1OddIndices)
10307           return DAG.getCommutedVectorShuffle(*SVOp);
10308       }
10309     }
10310   }
10311
10312   // For each vector width, delegate to a specialized lowering routine.
10313   if (VT.getSizeInBits() == 128)
10314     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10315
10316   if (VT.getSizeInBits() == 256)
10317     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10318
10319   // Force AVX-512 vectors to be scalarized for now.
10320   // FIXME: Implement AVX-512 support!
10321   if (VT.getSizeInBits() == 512)
10322     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10323
10324   llvm_unreachable("Unimplemented!");
10325 }
10326
10327 // This function assumes its argument is a BUILD_VECTOR of constants or
10328 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10329 // true.
10330 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10331                                     unsigned &MaskValue) {
10332   MaskValue = 0;
10333   unsigned NumElems = BuildVector->getNumOperands();
10334   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10335   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10336   unsigned NumElemsInLane = NumElems / NumLanes;
10337
10338   // Blend for v16i16 should be symetric for the both lanes.
10339   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10340     SDValue EltCond = BuildVector->getOperand(i);
10341     SDValue SndLaneEltCond =
10342         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10343
10344     int Lane1Cond = -1, Lane2Cond = -1;
10345     if (isa<ConstantSDNode>(EltCond))
10346       Lane1Cond = !isZero(EltCond);
10347     if (isa<ConstantSDNode>(SndLaneEltCond))
10348       Lane2Cond = !isZero(SndLaneEltCond);
10349
10350     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10351       // Lane1Cond != 0, means we want the first argument.
10352       // Lane1Cond == 0, means we want the second argument.
10353       // The encoding of this argument is 0 for the first argument, 1
10354       // for the second. Therefore, invert the condition.
10355       MaskValue |= !Lane1Cond << i;
10356     else if (Lane1Cond < 0)
10357       MaskValue |= !Lane2Cond << i;
10358     else
10359       return false;
10360   }
10361   return true;
10362 }
10363
10364 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10365 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10366                                            const X86Subtarget *Subtarget,
10367                                            SelectionDAG &DAG) {
10368   SDValue Cond = Op.getOperand(0);
10369   SDValue LHS = Op.getOperand(1);
10370   SDValue RHS = Op.getOperand(2);
10371   SDLoc dl(Op);
10372   MVT VT = Op.getSimpleValueType();
10373
10374   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10375     return SDValue();
10376   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10377
10378   // Only non-legal VSELECTs reach this lowering, convert those into generic
10379   // shuffles and re-use the shuffle lowering path for blends.
10380   SmallVector<int, 32> Mask;
10381   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10382     SDValue CondElt = CondBV->getOperand(i);
10383     Mask.push_back(
10384         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10385   }
10386   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10387 }
10388
10389 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10390   // A vselect where all conditions and data are constants can be optimized into
10391   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10392   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10393       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10394       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10395     return SDValue();
10396
10397   // Try to lower this to a blend-style vector shuffle. This can handle all
10398   // constant condition cases.
10399   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10400     return BlendOp;
10401
10402   // Variable blends are only legal from SSE4.1 onward.
10403   if (!Subtarget->hasSSE41())
10404     return SDValue();
10405
10406   // Only some types will be legal on some subtargets. If we can emit a legal
10407   // VSELECT-matching blend, return Op, and but if we need to expand, return
10408   // a null value.
10409   switch (Op.getSimpleValueType().SimpleTy) {
10410   default:
10411     // Most of the vector types have blends past SSE4.1.
10412     return Op;
10413
10414   case MVT::v32i8:
10415     // The byte blends for AVX vectors were introduced only in AVX2.
10416     if (Subtarget->hasAVX2())
10417       return Op;
10418
10419     return SDValue();
10420
10421   case MVT::v8i16:
10422   case MVT::v16i16:
10423     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10424     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10425       return Op;
10426
10427     // FIXME: We should custom lower this by fixing the condition and using i8
10428     // blends.
10429     return SDValue();
10430   }
10431 }
10432
10433 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10434   MVT VT = Op.getSimpleValueType();
10435   SDLoc dl(Op);
10436
10437   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10438     return SDValue();
10439
10440   if (VT.getSizeInBits() == 8) {
10441     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10442                                   Op.getOperand(0), Op.getOperand(1));
10443     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10444                                   DAG.getValueType(VT));
10445     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10446   }
10447
10448   if (VT.getSizeInBits() == 16) {
10449     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10450     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10451     if (Idx == 0)
10452       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10453                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10454                                      DAG.getNode(ISD::BITCAST, dl,
10455                                                  MVT::v4i32,
10456                                                  Op.getOperand(0)),
10457                                      Op.getOperand(1)));
10458     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10459                                   Op.getOperand(0), Op.getOperand(1));
10460     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10461                                   DAG.getValueType(VT));
10462     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10463   }
10464
10465   if (VT == MVT::f32) {
10466     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10467     // the result back to FR32 register. It's only worth matching if the
10468     // result has a single use which is a store or a bitcast to i32.  And in
10469     // the case of a store, it's not worth it if the index is a constant 0,
10470     // because a MOVSSmr can be used instead, which is smaller and faster.
10471     if (!Op.hasOneUse())
10472       return SDValue();
10473     SDNode *User = *Op.getNode()->use_begin();
10474     if ((User->getOpcode() != ISD::STORE ||
10475          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10476           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10477         (User->getOpcode() != ISD::BITCAST ||
10478          User->getValueType(0) != MVT::i32))
10479       return SDValue();
10480     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10481                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10482                                               Op.getOperand(0)),
10483                                               Op.getOperand(1));
10484     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10485   }
10486
10487   if (VT == MVT::i32 || VT == MVT::i64) {
10488     // ExtractPS/pextrq works with constant index.
10489     if (isa<ConstantSDNode>(Op.getOperand(1)))
10490       return Op;
10491   }
10492   return SDValue();
10493 }
10494
10495 /// Extract one bit from mask vector, like v16i1 or v8i1.
10496 /// AVX-512 feature.
10497 SDValue
10498 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10499   SDValue Vec = Op.getOperand(0);
10500   SDLoc dl(Vec);
10501   MVT VecVT = Vec.getSimpleValueType();
10502   SDValue Idx = Op.getOperand(1);
10503   MVT EltVT = Op.getSimpleValueType();
10504
10505   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10506   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10507          "Unexpected vector type in ExtractBitFromMaskVector");
10508
10509   // variable index can't be handled in mask registers,
10510   // extend vector to VR512
10511   if (!isa<ConstantSDNode>(Idx)) {
10512     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10513     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10514     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10515                               ExtVT.getVectorElementType(), Ext, Idx);
10516     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10517   }
10518
10519   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10520   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10521   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10522     rc = getRegClassFor(MVT::v16i1);
10523   unsigned MaxSift = rc->getSize()*8 - 1;
10524   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10525                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10526   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10527                     DAG.getConstant(MaxSift, dl, MVT::i8));
10528   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10529                        DAG.getIntPtrConstant(0, dl));
10530 }
10531
10532 SDValue
10533 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10534                                            SelectionDAG &DAG) const {
10535   SDLoc dl(Op);
10536   SDValue Vec = Op.getOperand(0);
10537   MVT VecVT = Vec.getSimpleValueType();
10538   SDValue Idx = Op.getOperand(1);
10539
10540   if (Op.getSimpleValueType() == MVT::i1)
10541     return ExtractBitFromMaskVector(Op, DAG);
10542
10543   if (!isa<ConstantSDNode>(Idx)) {
10544     if (VecVT.is512BitVector() ||
10545         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10546          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10547
10548       MVT MaskEltVT =
10549         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10550       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10551                                     MaskEltVT.getSizeInBits());
10552
10553       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10554       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10555                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10556                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10557       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10558       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10559                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10560     }
10561     return SDValue();
10562   }
10563
10564   // If this is a 256-bit vector result, first extract the 128-bit vector and
10565   // then extract the element from the 128-bit vector.
10566   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10567
10568     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10569     // Get the 128-bit vector.
10570     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10571     MVT EltVT = VecVT.getVectorElementType();
10572
10573     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10574
10575     //if (IdxVal >= NumElems/2)
10576     //  IdxVal -= NumElems/2;
10577     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10578     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10579                        DAG.getConstant(IdxVal, dl, MVT::i32));
10580   }
10581
10582   assert(VecVT.is128BitVector() && "Unexpected vector length");
10583
10584   if (Subtarget->hasSSE41()) {
10585     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10586     if (Res.getNode())
10587       return Res;
10588   }
10589
10590   MVT VT = Op.getSimpleValueType();
10591   // TODO: handle v16i8.
10592   if (VT.getSizeInBits() == 16) {
10593     SDValue Vec = Op.getOperand(0);
10594     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10595     if (Idx == 0)
10596       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10597                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10598                                      DAG.getNode(ISD::BITCAST, dl,
10599                                                  MVT::v4i32, Vec),
10600                                      Op.getOperand(1)));
10601     // Transform it so it match pextrw which produces a 32-bit result.
10602     MVT EltVT = MVT::i32;
10603     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10604                                   Op.getOperand(0), Op.getOperand(1));
10605     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10606                                   DAG.getValueType(VT));
10607     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10608   }
10609
10610   if (VT.getSizeInBits() == 32) {
10611     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10612     if (Idx == 0)
10613       return Op;
10614
10615     // SHUFPS the element to the lowest double word, then movss.
10616     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10617     MVT VVT = Op.getOperand(0).getSimpleValueType();
10618     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10619                                        DAG.getUNDEF(VVT), Mask);
10620     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10621                        DAG.getIntPtrConstant(0, dl));
10622   }
10623
10624   if (VT.getSizeInBits() == 64) {
10625     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10626     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10627     //        to match extract_elt for f64.
10628     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10629     if (Idx == 0)
10630       return Op;
10631
10632     // UNPCKHPD the element to the lowest double word, then movsd.
10633     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10634     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10635     int Mask[2] = { 1, -1 };
10636     MVT VVT = Op.getOperand(0).getSimpleValueType();
10637     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10638                                        DAG.getUNDEF(VVT), Mask);
10639     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10640                        DAG.getIntPtrConstant(0, dl));
10641   }
10642
10643   return SDValue();
10644 }
10645
10646 /// Insert one bit to mask vector, like v16i1 or v8i1.
10647 /// AVX-512 feature.
10648 SDValue
10649 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10650   SDLoc dl(Op);
10651   SDValue Vec = Op.getOperand(0);
10652   SDValue Elt = Op.getOperand(1);
10653   SDValue Idx = Op.getOperand(2);
10654   MVT VecVT = Vec.getSimpleValueType();
10655
10656   if (!isa<ConstantSDNode>(Idx)) {
10657     // Non constant index. Extend source and destination,
10658     // insert element and then truncate the result.
10659     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10660     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10661     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10662       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10663       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10664     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10665   }
10666
10667   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10668   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10669   if (Vec.getOpcode() == ISD::UNDEF)
10670     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10671                        DAG.getConstant(IdxVal, dl, MVT::i8));
10672   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10673   unsigned MaxSift = rc->getSize()*8 - 1;
10674   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10675                     DAG.getConstant(MaxSift, dl, MVT::i8));
10676   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10677                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10678   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10679 }
10680
10681 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10682                                                   SelectionDAG &DAG) const {
10683   MVT VT = Op.getSimpleValueType();
10684   MVT EltVT = VT.getVectorElementType();
10685
10686   if (EltVT == MVT::i1)
10687     return InsertBitToMaskVector(Op, DAG);
10688
10689   SDLoc dl(Op);
10690   SDValue N0 = Op.getOperand(0);
10691   SDValue N1 = Op.getOperand(1);
10692   SDValue N2 = Op.getOperand(2);
10693   if (!isa<ConstantSDNode>(N2))
10694     return SDValue();
10695   auto *N2C = cast<ConstantSDNode>(N2);
10696   unsigned IdxVal = N2C->getZExtValue();
10697
10698   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10699   // into that, and then insert the subvector back into the result.
10700   if (VT.is256BitVector() || VT.is512BitVector()) {
10701     // With a 256-bit vector, we can insert into the zero element efficiently
10702     // using a blend if we have AVX or AVX2 and the right data type.
10703     if (VT.is256BitVector() && IdxVal == 0) {
10704       // TODO: It is worthwhile to cast integer to floating point and back
10705       // and incur a domain crossing penalty if that's what we'll end up
10706       // doing anyway after extracting to a 128-bit vector.
10707       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10708           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10709         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10710         N2 = DAG.getIntPtrConstant(1, dl);
10711         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10712       }
10713     }
10714
10715     // Get the desired 128-bit vector chunk.
10716     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10717
10718     // Insert the element into the desired chunk.
10719     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10720     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10721
10722     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10723                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10724
10725     // Insert the changed part back into the bigger vector
10726     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10727   }
10728   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10729
10730   if (Subtarget->hasSSE41()) {
10731     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10732       unsigned Opc;
10733       if (VT == MVT::v8i16) {
10734         Opc = X86ISD::PINSRW;
10735       } else {
10736         assert(VT == MVT::v16i8);
10737         Opc = X86ISD::PINSRB;
10738       }
10739
10740       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10741       // argument.
10742       if (N1.getValueType() != MVT::i32)
10743         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10744       if (N2.getValueType() != MVT::i32)
10745         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10746       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10747     }
10748
10749     if (EltVT == MVT::f32) {
10750       // Bits [7:6] of the constant are the source select. This will always be
10751       //   zero here. The DAG Combiner may combine an extract_elt index into
10752       //   these bits. For example (insert (extract, 3), 2) could be matched by
10753       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10754       // Bits [5:4] of the constant are the destination select. This is the
10755       //   value of the incoming immediate.
10756       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10757       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10758
10759       const Function *F = DAG.getMachineFunction().getFunction();
10760       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10761       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10762         // If this is an insertion of 32-bits into the low 32-bits of
10763         // a vector, we prefer to generate a blend with immediate rather
10764         // than an insertps. Blends are simpler operations in hardware and so
10765         // will always have equal or better performance than insertps.
10766         // But if optimizing for size and there's a load folding opportunity,
10767         // generate insertps because blendps does not have a 32-bit memory
10768         // operand form.
10769         N2 = DAG.getIntPtrConstant(1, dl);
10770         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10771         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10772       }
10773       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10774       // Create this as a scalar to vector..
10775       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10776       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10777     }
10778
10779     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10780       // PINSR* works with constant index.
10781       return Op;
10782     }
10783   }
10784
10785   if (EltVT == MVT::i8)
10786     return SDValue();
10787
10788   if (EltVT.getSizeInBits() == 16) {
10789     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10790     // as its second argument.
10791     if (N1.getValueType() != MVT::i32)
10792       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10793     if (N2.getValueType() != MVT::i32)
10794       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10795     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10796   }
10797   return SDValue();
10798 }
10799
10800 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10801   SDLoc dl(Op);
10802   MVT OpVT = Op.getSimpleValueType();
10803
10804   // If this is a 256-bit vector result, first insert into a 128-bit
10805   // vector and then insert into the 256-bit vector.
10806   if (!OpVT.is128BitVector()) {
10807     // Insert into a 128-bit vector.
10808     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10809     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10810                                  OpVT.getVectorNumElements() / SizeFactor);
10811
10812     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10813
10814     // Insert the 128-bit vector.
10815     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10816   }
10817
10818   if (OpVT == MVT::v1i64 &&
10819       Op.getOperand(0).getValueType() == MVT::i64)
10820     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10821
10822   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10823   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10824   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10825                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10826 }
10827
10828 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10829 // a simple subregister reference or explicit instructions to grab
10830 // upper bits of a vector.
10831 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10832                                       SelectionDAG &DAG) {
10833   SDLoc dl(Op);
10834   SDValue In =  Op.getOperand(0);
10835   SDValue Idx = Op.getOperand(1);
10836   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10837   MVT ResVT   = Op.getSimpleValueType();
10838   MVT InVT    = In.getSimpleValueType();
10839
10840   if (Subtarget->hasFp256()) {
10841     if (ResVT.is128BitVector() &&
10842         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10843         isa<ConstantSDNode>(Idx)) {
10844       return Extract128BitVector(In, IdxVal, DAG, dl);
10845     }
10846     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10847         isa<ConstantSDNode>(Idx)) {
10848       return Extract256BitVector(In, IdxVal, DAG, dl);
10849     }
10850   }
10851   return SDValue();
10852 }
10853
10854 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10855 // simple superregister reference or explicit instructions to insert
10856 // the upper bits of a vector.
10857 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10858                                      SelectionDAG &DAG) {
10859   if (!Subtarget->hasAVX())
10860     return SDValue();
10861
10862   SDLoc dl(Op);
10863   SDValue Vec = Op.getOperand(0);
10864   SDValue SubVec = Op.getOperand(1);
10865   SDValue Idx = Op.getOperand(2);
10866
10867   if (!isa<ConstantSDNode>(Idx))
10868     return SDValue();
10869
10870   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10871   MVT OpVT = Op.getSimpleValueType();
10872   MVT SubVecVT = SubVec.getSimpleValueType();
10873
10874   // Fold two 16-byte subvector loads into one 32-byte load:
10875   // (insert_subvector (insert_subvector undef, (load addr), 0),
10876   //                   (load addr + 16), Elts/2)
10877   // --> load32 addr
10878   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10879       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10880       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10881       !Subtarget->isUnalignedMem32Slow()) {
10882     SDValue SubVec2 = Vec.getOperand(1);
10883     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10884       if (Idx2->getZExtValue() == 0) {
10885         SDValue Ops[] = { SubVec2, SubVec };
10886         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10887         if (LD.getNode())
10888           return LD;
10889       }
10890     }
10891   }
10892
10893   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10894       SubVecVT.is128BitVector())
10895     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10896
10897   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10898     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10899
10900   if (OpVT.getVectorElementType() == MVT::i1) {
10901     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10902       return Op;
10903     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10904     SDValue Undef = DAG.getUNDEF(OpVT);
10905     unsigned NumElems = OpVT.getVectorNumElements();
10906     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10907
10908     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10909       // Zero upper bits of the Vec
10910       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10911       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10912
10913       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10914                                  SubVec, ZeroIdx);
10915       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10916       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10917     }
10918     if (IdxVal == 0) {
10919       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10920                                  SubVec, ZeroIdx);
10921       // Zero upper bits of the Vec2
10922       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10923       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10924       // Zero lower bits of the Vec
10925       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10926       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10927       // Merge them together
10928       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10929     }
10930   }
10931   return SDValue();
10932 }
10933
10934 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10935 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10936 // one of the above mentioned nodes. It has to be wrapped because otherwise
10937 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10938 // be used to form addressing mode. These wrapped nodes will be selected
10939 // into MOV32ri.
10940 SDValue
10941 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10942   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10943
10944   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10945   // global base reg.
10946   unsigned char OpFlag = 0;
10947   unsigned WrapperKind = X86ISD::Wrapper;
10948   CodeModel::Model M = DAG.getTarget().getCodeModel();
10949
10950   if (Subtarget->isPICStyleRIPRel() &&
10951       (M == CodeModel::Small || M == CodeModel::Kernel))
10952     WrapperKind = X86ISD::WrapperRIP;
10953   else if (Subtarget->isPICStyleGOT())
10954     OpFlag = X86II::MO_GOTOFF;
10955   else if (Subtarget->isPICStyleStubPIC())
10956     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10957
10958   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10959                                              CP->getAlignment(),
10960                                              CP->getOffset(), OpFlag);
10961   SDLoc DL(CP);
10962   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10963   // With PIC, the address is actually $g + Offset.
10964   if (OpFlag) {
10965     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10966                          DAG.getNode(X86ISD::GlobalBaseReg,
10967                                      SDLoc(), getPointerTy()),
10968                          Result);
10969   }
10970
10971   return Result;
10972 }
10973
10974 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10975   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10976
10977   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10978   // global base reg.
10979   unsigned char OpFlag = 0;
10980   unsigned WrapperKind = X86ISD::Wrapper;
10981   CodeModel::Model M = DAG.getTarget().getCodeModel();
10982
10983   if (Subtarget->isPICStyleRIPRel() &&
10984       (M == CodeModel::Small || M == CodeModel::Kernel))
10985     WrapperKind = X86ISD::WrapperRIP;
10986   else if (Subtarget->isPICStyleGOT())
10987     OpFlag = X86II::MO_GOTOFF;
10988   else if (Subtarget->isPICStyleStubPIC())
10989     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10990
10991   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10992                                           OpFlag);
10993   SDLoc DL(JT);
10994   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10995
10996   // With PIC, the address is actually $g + Offset.
10997   if (OpFlag)
10998     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10999                          DAG.getNode(X86ISD::GlobalBaseReg,
11000                                      SDLoc(), getPointerTy()),
11001                          Result);
11002
11003   return Result;
11004 }
11005
11006 SDValue
11007 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11008   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11009
11010   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11011   // global base reg.
11012   unsigned char OpFlag = 0;
11013   unsigned WrapperKind = X86ISD::Wrapper;
11014   CodeModel::Model M = DAG.getTarget().getCodeModel();
11015
11016   if (Subtarget->isPICStyleRIPRel() &&
11017       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11018     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11019       OpFlag = X86II::MO_GOTPCREL;
11020     WrapperKind = X86ISD::WrapperRIP;
11021   } else if (Subtarget->isPICStyleGOT()) {
11022     OpFlag = X86II::MO_GOT;
11023   } else if (Subtarget->isPICStyleStubPIC()) {
11024     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11025   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11026     OpFlag = X86II::MO_DARWIN_NONLAZY;
11027   }
11028
11029   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11030
11031   SDLoc DL(Op);
11032   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11033
11034   // With PIC, the address is actually $g + Offset.
11035   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11036       !Subtarget->is64Bit()) {
11037     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11038                          DAG.getNode(X86ISD::GlobalBaseReg,
11039                                      SDLoc(), getPointerTy()),
11040                          Result);
11041   }
11042
11043   // For symbols that require a load from a stub to get the address, emit the
11044   // load.
11045   if (isGlobalStubReference(OpFlag))
11046     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11047                          MachinePointerInfo::getGOT(), false, false, false, 0);
11048
11049   return Result;
11050 }
11051
11052 SDValue
11053 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11054   // Create the TargetBlockAddressAddress node.
11055   unsigned char OpFlags =
11056     Subtarget->ClassifyBlockAddressReference();
11057   CodeModel::Model M = DAG.getTarget().getCodeModel();
11058   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11059   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11060   SDLoc dl(Op);
11061   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11062                                              OpFlags);
11063
11064   if (Subtarget->isPICStyleRIPRel() &&
11065       (M == CodeModel::Small || M == CodeModel::Kernel))
11066     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11067   else
11068     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11069
11070   // With PIC, the address is actually $g + Offset.
11071   if (isGlobalRelativeToPICBase(OpFlags)) {
11072     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11073                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11074                          Result);
11075   }
11076
11077   return Result;
11078 }
11079
11080 SDValue
11081 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11082                                       int64_t Offset, SelectionDAG &DAG) const {
11083   // Create the TargetGlobalAddress node, folding in the constant
11084   // offset if it is legal.
11085   unsigned char OpFlags =
11086       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11087   CodeModel::Model M = DAG.getTarget().getCodeModel();
11088   SDValue Result;
11089   if (OpFlags == X86II::MO_NO_FLAG &&
11090       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11091     // A direct static reference to a global.
11092     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11093     Offset = 0;
11094   } else {
11095     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11096   }
11097
11098   if (Subtarget->isPICStyleRIPRel() &&
11099       (M == CodeModel::Small || M == CodeModel::Kernel))
11100     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11101   else
11102     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11103
11104   // With PIC, the address is actually $g + Offset.
11105   if (isGlobalRelativeToPICBase(OpFlags)) {
11106     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11107                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11108                          Result);
11109   }
11110
11111   // For globals that require a load from a stub to get the address, emit the
11112   // load.
11113   if (isGlobalStubReference(OpFlags))
11114     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11115                          MachinePointerInfo::getGOT(), false, false, false, 0);
11116
11117   // If there was a non-zero offset that we didn't fold, create an explicit
11118   // addition for it.
11119   if (Offset != 0)
11120     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11121                          DAG.getConstant(Offset, dl, getPointerTy()));
11122
11123   return Result;
11124 }
11125
11126 SDValue
11127 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11128   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11129   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11130   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11131 }
11132
11133 static SDValue
11134 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11135            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11136            unsigned char OperandFlags, bool LocalDynamic = false) {
11137   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11138   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11139   SDLoc dl(GA);
11140   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11141                                            GA->getValueType(0),
11142                                            GA->getOffset(),
11143                                            OperandFlags);
11144
11145   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11146                                            : X86ISD::TLSADDR;
11147
11148   if (InFlag) {
11149     SDValue Ops[] = { Chain,  TGA, *InFlag };
11150     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11151   } else {
11152     SDValue Ops[]  = { Chain, TGA };
11153     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11154   }
11155
11156   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11157   MFI->setAdjustsStack(true);
11158   MFI->setHasCalls(true);
11159
11160   SDValue Flag = Chain.getValue(1);
11161   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11162 }
11163
11164 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11165 static SDValue
11166 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11167                                 const EVT PtrVT) {
11168   SDValue InFlag;
11169   SDLoc dl(GA);  // ? function entry point might be better
11170   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11171                                    DAG.getNode(X86ISD::GlobalBaseReg,
11172                                                SDLoc(), PtrVT), InFlag);
11173   InFlag = Chain.getValue(1);
11174
11175   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11176 }
11177
11178 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11179 static SDValue
11180 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11181                                 const EVT PtrVT) {
11182   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11183                     X86::RAX, X86II::MO_TLSGD);
11184 }
11185
11186 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11187                                            SelectionDAG &DAG,
11188                                            const EVT PtrVT,
11189                                            bool is64Bit) {
11190   SDLoc dl(GA);
11191
11192   // Get the start address of the TLS block for this module.
11193   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11194       .getInfo<X86MachineFunctionInfo>();
11195   MFI->incNumLocalDynamicTLSAccesses();
11196
11197   SDValue Base;
11198   if (is64Bit) {
11199     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11200                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11201   } else {
11202     SDValue InFlag;
11203     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11204         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11205     InFlag = Chain.getValue(1);
11206     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11207                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11208   }
11209
11210   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11211   // of Base.
11212
11213   // Build x@dtpoff.
11214   unsigned char OperandFlags = X86II::MO_DTPOFF;
11215   unsigned WrapperKind = X86ISD::Wrapper;
11216   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11217                                            GA->getValueType(0),
11218                                            GA->getOffset(), OperandFlags);
11219   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11220
11221   // Add x@dtpoff with the base.
11222   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11223 }
11224
11225 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11226 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11227                                    const EVT PtrVT, TLSModel::Model model,
11228                                    bool is64Bit, bool isPIC) {
11229   SDLoc dl(GA);
11230
11231   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11232   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11233                                                          is64Bit ? 257 : 256));
11234
11235   SDValue ThreadPointer =
11236       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11237                   MachinePointerInfo(Ptr), false, false, false, 0);
11238
11239   unsigned char OperandFlags = 0;
11240   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11241   // initialexec.
11242   unsigned WrapperKind = X86ISD::Wrapper;
11243   if (model == TLSModel::LocalExec) {
11244     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11245   } else if (model == TLSModel::InitialExec) {
11246     if (is64Bit) {
11247       OperandFlags = X86II::MO_GOTTPOFF;
11248       WrapperKind = X86ISD::WrapperRIP;
11249     } else {
11250       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11251     }
11252   } else {
11253     llvm_unreachable("Unexpected model");
11254   }
11255
11256   // emit "addl x@ntpoff,%eax" (local exec)
11257   // or "addl x@indntpoff,%eax" (initial exec)
11258   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11259   SDValue TGA =
11260       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11261                                  GA->getOffset(), OperandFlags);
11262   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11263
11264   if (model == TLSModel::InitialExec) {
11265     if (isPIC && !is64Bit) {
11266       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11267                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11268                            Offset);
11269     }
11270
11271     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11272                          MachinePointerInfo::getGOT(), false, false, false, 0);
11273   }
11274
11275   // The address of the thread local variable is the add of the thread
11276   // pointer with the offset of the variable.
11277   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11278 }
11279
11280 SDValue
11281 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11282
11283   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11284   const GlobalValue *GV = GA->getGlobal();
11285
11286   if (Subtarget->isTargetELF()) {
11287     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11288
11289     switch (model) {
11290       case TLSModel::GeneralDynamic:
11291         if (Subtarget->is64Bit())
11292           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11293         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11294       case TLSModel::LocalDynamic:
11295         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11296                                            Subtarget->is64Bit());
11297       case TLSModel::InitialExec:
11298       case TLSModel::LocalExec:
11299         return LowerToTLSExecModel(
11300             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11301             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11302     }
11303     llvm_unreachable("Unknown TLS model.");
11304   }
11305
11306   if (Subtarget->isTargetDarwin()) {
11307     // Darwin only has one model of TLS.  Lower to that.
11308     unsigned char OpFlag = 0;
11309     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11310                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11311
11312     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11313     // global base reg.
11314     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11315                  !Subtarget->is64Bit();
11316     if (PIC32)
11317       OpFlag = X86II::MO_TLVP_PIC_BASE;
11318     else
11319       OpFlag = X86II::MO_TLVP;
11320     SDLoc DL(Op);
11321     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11322                                                 GA->getValueType(0),
11323                                                 GA->getOffset(), OpFlag);
11324     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11325
11326     // With PIC32, the address is actually $g + Offset.
11327     if (PIC32)
11328       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11329                            DAG.getNode(X86ISD::GlobalBaseReg,
11330                                        SDLoc(), getPointerTy()),
11331                            Offset);
11332
11333     // Lowering the machine isd will make sure everything is in the right
11334     // location.
11335     SDValue Chain = DAG.getEntryNode();
11336     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11337     SDValue Args[] = { Chain, Offset };
11338     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11339
11340     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11341     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11342     MFI->setAdjustsStack(true);
11343
11344     // And our return value (tls address) is in the standard call return value
11345     // location.
11346     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11347     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11348                               Chain.getValue(1));
11349   }
11350
11351   if (Subtarget->isTargetKnownWindowsMSVC() ||
11352       Subtarget->isTargetWindowsGNU()) {
11353     // Just use the implicit TLS architecture
11354     // Need to generate someting similar to:
11355     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11356     //                                  ; from TEB
11357     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11358     //   mov     rcx, qword [rdx+rcx*8]
11359     //   mov     eax, .tls$:tlsvar
11360     //   [rax+rcx] contains the address
11361     // Windows 64bit: gs:0x58
11362     // Windows 32bit: fs:__tls_array
11363
11364     SDLoc dl(GA);
11365     SDValue Chain = DAG.getEntryNode();
11366
11367     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11368     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11369     // use its literal value of 0x2C.
11370     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11371                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11372                                                              256)
11373                                         : Type::getInt32PtrTy(*DAG.getContext(),
11374                                                               257));
11375
11376     SDValue TlsArray =
11377         Subtarget->is64Bit()
11378             ? DAG.getIntPtrConstant(0x58, dl)
11379             : (Subtarget->isTargetWindowsGNU()
11380                    ? DAG.getIntPtrConstant(0x2C, dl)
11381                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11382
11383     SDValue ThreadPointer =
11384         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11385                     MachinePointerInfo(Ptr), false, false, false, 0);
11386
11387     // Load the _tls_index variable
11388     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11389     if (Subtarget->is64Bit())
11390       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11391                            IDX, MachinePointerInfo(), MVT::i32,
11392                            false, false, false, 0);
11393     else
11394       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11395                         false, false, false, 0);
11396
11397     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11398                                     getPointerTy());
11399     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11400
11401     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11402     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11403                       false, false, false, 0);
11404
11405     // Get the offset of start of .tls section
11406     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11407                                              GA->getValueType(0),
11408                                              GA->getOffset(), X86II::MO_SECREL);
11409     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11410
11411     // The address of the thread local variable is the add of the thread
11412     // pointer with the offset of the variable.
11413     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11414   }
11415
11416   llvm_unreachable("TLS not implemented for this target.");
11417 }
11418
11419 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11420 /// and take a 2 x i32 value to shift plus a shift amount.
11421 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11422   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11423   MVT VT = Op.getSimpleValueType();
11424   unsigned VTBits = VT.getSizeInBits();
11425   SDLoc dl(Op);
11426   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11427   SDValue ShOpLo = Op.getOperand(0);
11428   SDValue ShOpHi = Op.getOperand(1);
11429   SDValue ShAmt  = Op.getOperand(2);
11430   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11431   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11432   // during isel.
11433   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11434                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11435   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11436                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11437                        : DAG.getConstant(0, dl, VT);
11438
11439   SDValue Tmp2, Tmp3;
11440   if (Op.getOpcode() == ISD::SHL_PARTS) {
11441     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11442     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11443   } else {
11444     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11445     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11446   }
11447
11448   // If the shift amount is larger or equal than the width of a part we can't
11449   // rely on the results of shld/shrd. Insert a test and select the appropriate
11450   // values for large shift amounts.
11451   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11452                                 DAG.getConstant(VTBits, dl, MVT::i8));
11453   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11454                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11455
11456   SDValue Hi, Lo;
11457   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11458   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11459   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11460
11461   if (Op.getOpcode() == ISD::SHL_PARTS) {
11462     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11463     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11464   } else {
11465     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11466     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11467   }
11468
11469   SDValue Ops[2] = { Lo, Hi };
11470   return DAG.getMergeValues(Ops, dl);
11471 }
11472
11473 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11474                                            SelectionDAG &DAG) const {
11475   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11476   SDLoc dl(Op);
11477
11478   if (SrcVT.isVector()) {
11479     if (SrcVT.getVectorElementType() == MVT::i1) {
11480       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11481       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11482                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11483                                      Op.getOperand(0)));
11484     }
11485     return SDValue();
11486   }
11487
11488   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11489          "Unknown SINT_TO_FP to lower!");
11490
11491   // These are really Legal; return the operand so the caller accepts it as
11492   // Legal.
11493   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11494     return Op;
11495   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11496       Subtarget->is64Bit()) {
11497     return Op;
11498   }
11499
11500   unsigned Size = SrcVT.getSizeInBits()/8;
11501   MachineFunction &MF = DAG.getMachineFunction();
11502   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11503   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11504   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11505                                StackSlot,
11506                                MachinePointerInfo::getFixedStack(SSFI),
11507                                false, false, 0);
11508   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11509 }
11510
11511 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11512                                      SDValue StackSlot,
11513                                      SelectionDAG &DAG) const {
11514   // Build the FILD
11515   SDLoc DL(Op);
11516   SDVTList Tys;
11517   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11518   if (useSSE)
11519     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11520   else
11521     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11522
11523   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11524
11525   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11526   MachineMemOperand *MMO;
11527   if (FI) {
11528     int SSFI = FI->getIndex();
11529     MMO =
11530       DAG.getMachineFunction()
11531       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11532                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11533   } else {
11534     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11535     StackSlot = StackSlot.getOperand(1);
11536   }
11537   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11538   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11539                                            X86ISD::FILD, DL,
11540                                            Tys, Ops, SrcVT, MMO);
11541
11542   if (useSSE) {
11543     Chain = Result.getValue(1);
11544     SDValue InFlag = Result.getValue(2);
11545
11546     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11547     // shouldn't be necessary except that RFP cannot be live across
11548     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11549     MachineFunction &MF = DAG.getMachineFunction();
11550     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11551     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11552     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11553     Tys = DAG.getVTList(MVT::Other);
11554     SDValue Ops[] = {
11555       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11556     };
11557     MachineMemOperand *MMO =
11558       DAG.getMachineFunction()
11559       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11560                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11561
11562     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11563                                     Ops, Op.getValueType(), MMO);
11564     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11565                          MachinePointerInfo::getFixedStack(SSFI),
11566                          false, false, false, 0);
11567   }
11568
11569   return Result;
11570 }
11571
11572 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11573 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11574                                                SelectionDAG &DAG) const {
11575   // This algorithm is not obvious. Here it is what we're trying to output:
11576   /*
11577      movq       %rax,  %xmm0
11578      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11579      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11580      #ifdef __SSE3__
11581        haddpd   %xmm0, %xmm0
11582      #else
11583        pshufd   $0x4e, %xmm0, %xmm1
11584        addpd    %xmm1, %xmm0
11585      #endif
11586   */
11587
11588   SDLoc dl(Op);
11589   LLVMContext *Context = DAG.getContext();
11590
11591   // Build some magic constants.
11592   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11593   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11594   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11595
11596   SmallVector<Constant*,2> CV1;
11597   CV1.push_back(
11598     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11599                                       APInt(64, 0x4330000000000000ULL))));
11600   CV1.push_back(
11601     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11602                                       APInt(64, 0x4530000000000000ULL))));
11603   Constant *C1 = ConstantVector::get(CV1);
11604   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11605
11606   // Load the 64-bit value into an XMM register.
11607   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11608                             Op.getOperand(0));
11609   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11610                               MachinePointerInfo::getConstantPool(),
11611                               false, false, false, 16);
11612   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11613                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11614                               CLod0);
11615
11616   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11617                               MachinePointerInfo::getConstantPool(),
11618                               false, false, false, 16);
11619   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11620   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11621   SDValue Result;
11622
11623   if (Subtarget->hasSSE3()) {
11624     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11625     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11626   } else {
11627     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11628     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11629                                            S2F, 0x4E, DAG);
11630     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11631                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11632                          Sub);
11633   }
11634
11635   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11636                      DAG.getIntPtrConstant(0, dl));
11637 }
11638
11639 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11640 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11641                                                SelectionDAG &DAG) const {
11642   SDLoc dl(Op);
11643   // FP constant to bias correct the final result.
11644   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11645                                    MVT::f64);
11646
11647   // Load the 32-bit value into an XMM register.
11648   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11649                              Op.getOperand(0));
11650
11651   // Zero out the upper parts of the register.
11652   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11653
11654   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11655                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11656                      DAG.getIntPtrConstant(0, dl));
11657
11658   // Or the load with the bias.
11659   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11660                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11661                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11662                                                    MVT::v2f64, Load)),
11663                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11664                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11665                                                    MVT::v2f64, Bias)));
11666   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11667                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11668                    DAG.getIntPtrConstant(0, dl));
11669
11670   // Subtract the bias.
11671   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11672
11673   // Handle final rounding.
11674   EVT DestVT = Op.getValueType();
11675
11676   if (DestVT.bitsLT(MVT::f64))
11677     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11678                        DAG.getIntPtrConstant(0, dl));
11679   if (DestVT.bitsGT(MVT::f64))
11680     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11681
11682   // Handle final rounding.
11683   return Sub;
11684 }
11685
11686 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11687                                      const X86Subtarget &Subtarget) {
11688   // The algorithm is the following:
11689   // #ifdef __SSE4_1__
11690   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11691   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11692   //                                 (uint4) 0x53000000, 0xaa);
11693   // #else
11694   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11695   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11696   // #endif
11697   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11698   //     return (float4) lo + fhi;
11699
11700   SDLoc DL(Op);
11701   SDValue V = Op->getOperand(0);
11702   EVT VecIntVT = V.getValueType();
11703   bool Is128 = VecIntVT == MVT::v4i32;
11704   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11705   // If we convert to something else than the supported type, e.g., to v4f64,
11706   // abort early.
11707   if (VecFloatVT != Op->getValueType(0))
11708     return SDValue();
11709
11710   unsigned NumElts = VecIntVT.getVectorNumElements();
11711   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11712          "Unsupported custom type");
11713   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11714
11715   // In the #idef/#else code, we have in common:
11716   // - The vector of constants:
11717   // -- 0x4b000000
11718   // -- 0x53000000
11719   // - A shift:
11720   // -- v >> 16
11721
11722   // Create the splat vector for 0x4b000000.
11723   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11724   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11725                            CstLow, CstLow, CstLow, CstLow};
11726   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11727                                   makeArrayRef(&CstLowArray[0], NumElts));
11728   // Create the splat vector for 0x53000000.
11729   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11730   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11731                             CstHigh, CstHigh, CstHigh, CstHigh};
11732   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11733                                    makeArrayRef(&CstHighArray[0], NumElts));
11734
11735   // Create the right shift.
11736   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11737   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11738                              CstShift, CstShift, CstShift, CstShift};
11739   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11740                                     makeArrayRef(&CstShiftArray[0], NumElts));
11741   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11742
11743   SDValue Low, High;
11744   if (Subtarget.hasSSE41()) {
11745     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11746     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11747     SDValue VecCstLowBitcast =
11748         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11749     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11750     // Low will be bitcasted right away, so do not bother bitcasting back to its
11751     // original type.
11752     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11753                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11754     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11755     //                                 (uint4) 0x53000000, 0xaa);
11756     SDValue VecCstHighBitcast =
11757         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11758     SDValue VecShiftBitcast =
11759         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11760     // High will be bitcasted right away, so do not bother bitcasting back to
11761     // its original type.
11762     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11763                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11764   } else {
11765     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11766     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11767                                      CstMask, CstMask, CstMask);
11768     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11769     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11770     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11771
11772     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11773     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11774   }
11775
11776   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11777   SDValue CstFAdd = DAG.getConstantFP(
11778       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11779   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11780                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11781   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11782                                    makeArrayRef(&CstFAddArray[0], NumElts));
11783
11784   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11785   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11786   SDValue FHigh =
11787       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11788   //     return (float4) lo + fhi;
11789   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11790   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11791 }
11792
11793 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11794                                                SelectionDAG &DAG) const {
11795   SDValue N0 = Op.getOperand(0);
11796   MVT SVT = N0.getSimpleValueType();
11797   SDLoc dl(Op);
11798
11799   switch (SVT.SimpleTy) {
11800   default:
11801     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11802   case MVT::v4i8:
11803   case MVT::v4i16:
11804   case MVT::v8i8:
11805   case MVT::v8i16: {
11806     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11807     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11808                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11809   }
11810   case MVT::v4i32:
11811   case MVT::v8i32:
11812     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11813   case MVT::v16i8:
11814   case MVT::v16i16:
11815     if (Subtarget->hasAVX512())
11816       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11817                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11818   }
11819   llvm_unreachable(nullptr);
11820 }
11821
11822 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11823                                            SelectionDAG &DAG) const {
11824   SDValue N0 = Op.getOperand(0);
11825   SDLoc dl(Op);
11826
11827   if (Op.getValueType().isVector())
11828     return lowerUINT_TO_FP_vec(Op, DAG);
11829
11830   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11831   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11832   // the optimization here.
11833   if (DAG.SignBitIsZero(N0))
11834     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11835
11836   MVT SrcVT = N0.getSimpleValueType();
11837   MVT DstVT = Op.getSimpleValueType();
11838   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11839     return LowerUINT_TO_FP_i64(Op, DAG);
11840   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11841     return LowerUINT_TO_FP_i32(Op, DAG);
11842   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11843     return SDValue();
11844
11845   // Make a 64-bit buffer, and use it to build an FILD.
11846   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11847   if (SrcVT == MVT::i32) {
11848     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11849     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11850                                      getPointerTy(), StackSlot, WordOff);
11851     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11852                                   StackSlot, MachinePointerInfo(),
11853                                   false, false, 0);
11854     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11855                                   OffsetSlot, MachinePointerInfo(),
11856                                   false, false, 0);
11857     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11858     return Fild;
11859   }
11860
11861   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11862   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11863                                StackSlot, MachinePointerInfo(),
11864                                false, false, 0);
11865   // For i64 source, we need to add the appropriate power of 2 if the input
11866   // was negative.  This is the same as the optimization in
11867   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11868   // we must be careful to do the computation in x87 extended precision, not
11869   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11870   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11871   MachineMemOperand *MMO =
11872     DAG.getMachineFunction()
11873     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11874                           MachineMemOperand::MOLoad, 8, 8);
11875
11876   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11877   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11878   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11879                                          MVT::i64, MMO);
11880
11881   APInt FF(32, 0x5F800000ULL);
11882
11883   // Check whether the sign bit is set.
11884   SDValue SignSet = DAG.getSetCC(dl,
11885                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11886                                  Op.getOperand(0),
11887                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11888
11889   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11890   SDValue FudgePtr = DAG.getConstantPool(
11891                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11892                                          getPointerTy());
11893
11894   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11895   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11896   SDValue Four = DAG.getIntPtrConstant(4, dl);
11897   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11898                                Zero, Four);
11899   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11900
11901   // Load the value out, extending it from f32 to f80.
11902   // FIXME: Avoid the extend by constructing the right constant pool?
11903   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11904                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11905                                  MVT::f32, false, false, false, 4);
11906   // Extend everything to 80 bits to force it to be done on x87.
11907   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11908   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11909                      DAG.getIntPtrConstant(0, dl));
11910 }
11911
11912 std::pair<SDValue,SDValue>
11913 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11914                                     bool IsSigned, bool IsReplace) const {
11915   SDLoc DL(Op);
11916
11917   EVT DstTy = Op.getValueType();
11918
11919   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11920     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11921     DstTy = MVT::i64;
11922   }
11923
11924   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11925          DstTy.getSimpleVT() >= MVT::i16 &&
11926          "Unknown FP_TO_INT to lower!");
11927
11928   // These are really Legal.
11929   if (DstTy == MVT::i32 &&
11930       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11931     return std::make_pair(SDValue(), SDValue());
11932   if (Subtarget->is64Bit() &&
11933       DstTy == MVT::i64 &&
11934       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11935     return std::make_pair(SDValue(), SDValue());
11936
11937   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11938   // stack slot, or into the FTOL runtime function.
11939   MachineFunction &MF = DAG.getMachineFunction();
11940   unsigned MemSize = DstTy.getSizeInBits()/8;
11941   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11942   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11943
11944   unsigned Opc;
11945   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11946     Opc = X86ISD::WIN_FTOL;
11947   else
11948     switch (DstTy.getSimpleVT().SimpleTy) {
11949     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11950     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11951     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11952     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11953     }
11954
11955   SDValue Chain = DAG.getEntryNode();
11956   SDValue Value = Op.getOperand(0);
11957   EVT TheVT = Op.getOperand(0).getValueType();
11958   // FIXME This causes a redundant load/store if the SSE-class value is already
11959   // in memory, such as if it is on the callstack.
11960   if (isScalarFPTypeInSSEReg(TheVT)) {
11961     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11962     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11963                          MachinePointerInfo::getFixedStack(SSFI),
11964                          false, false, 0);
11965     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11966     SDValue Ops[] = {
11967       Chain, StackSlot, DAG.getValueType(TheVT)
11968     };
11969
11970     MachineMemOperand *MMO =
11971       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11972                               MachineMemOperand::MOLoad, MemSize, MemSize);
11973     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11974     Chain = Value.getValue(1);
11975     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11976     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11977   }
11978
11979   MachineMemOperand *MMO =
11980     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11981                             MachineMemOperand::MOStore, MemSize, MemSize);
11982
11983   if (Opc != X86ISD::WIN_FTOL) {
11984     // Build the FP_TO_INT*_IN_MEM
11985     SDValue Ops[] = { Chain, Value, StackSlot };
11986     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11987                                            Ops, DstTy, MMO);
11988     return std::make_pair(FIST, StackSlot);
11989   } else {
11990     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11991       DAG.getVTList(MVT::Other, MVT::Glue),
11992       Chain, Value);
11993     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11994       MVT::i32, ftol.getValue(1));
11995     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11996       MVT::i32, eax.getValue(2));
11997     SDValue Ops[] = { eax, edx };
11998     SDValue pair = IsReplace
11999       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12000       : DAG.getMergeValues(Ops, DL);
12001     return std::make_pair(pair, SDValue());
12002   }
12003 }
12004
12005 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12006                               const X86Subtarget *Subtarget) {
12007   MVT VT = Op->getSimpleValueType(0);
12008   SDValue In = Op->getOperand(0);
12009   MVT InVT = In.getSimpleValueType();
12010   SDLoc dl(Op);
12011
12012   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12013     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12014
12015   // Optimize vectors in AVX mode:
12016   //
12017   //   v8i16 -> v8i32
12018   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12019   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12020   //   Concat upper and lower parts.
12021   //
12022   //   v4i32 -> v4i64
12023   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12024   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12025   //   Concat upper and lower parts.
12026   //
12027
12028   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12029       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12030       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12031     return SDValue();
12032
12033   if (Subtarget->hasInt256())
12034     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12035
12036   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12037   SDValue Undef = DAG.getUNDEF(InVT);
12038   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12039   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12040   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12041
12042   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12043                              VT.getVectorNumElements()/2);
12044
12045   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12046   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12047
12048   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12049 }
12050
12051 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12052                                         SelectionDAG &DAG) {
12053   MVT VT = Op->getSimpleValueType(0);
12054   SDValue In = Op->getOperand(0);
12055   MVT InVT = In.getSimpleValueType();
12056   SDLoc DL(Op);
12057   unsigned int NumElts = VT.getVectorNumElements();
12058   if (NumElts != 8 && NumElts != 16)
12059     return SDValue();
12060
12061   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12062     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12063
12064   assert(InVT.getVectorElementType() == MVT::i1);
12065   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12066   SDValue One =
12067    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12068   SDValue Zero =
12069    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12070
12071   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12072   if (VT.is512BitVector())
12073     return V;
12074   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12075 }
12076
12077 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12078                                SelectionDAG &DAG) {
12079   if (Subtarget->hasFp256()) {
12080     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12081     if (Res.getNode())
12082       return Res;
12083   }
12084
12085   return SDValue();
12086 }
12087
12088 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12089                                 SelectionDAG &DAG) {
12090   SDLoc DL(Op);
12091   MVT VT = Op.getSimpleValueType();
12092   SDValue In = Op.getOperand(0);
12093   MVT SVT = In.getSimpleValueType();
12094
12095   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12096     return LowerZERO_EXTEND_AVX512(Op, DAG);
12097
12098   if (Subtarget->hasFp256()) {
12099     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12100     if (Res.getNode())
12101       return Res;
12102   }
12103
12104   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12105          VT.getVectorNumElements() != SVT.getVectorNumElements());
12106   return SDValue();
12107 }
12108
12109 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12110   SDLoc DL(Op);
12111   MVT VT = Op.getSimpleValueType();
12112   SDValue In = Op.getOperand(0);
12113   MVT InVT = In.getSimpleValueType();
12114
12115   if (VT == MVT::i1) {
12116     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12117            "Invalid scalar TRUNCATE operation");
12118     if (InVT.getSizeInBits() >= 32)
12119       return SDValue();
12120     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12121     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12122   }
12123   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12124          "Invalid TRUNCATE operation");
12125
12126   // move vector to mask - truncate solution for SKX
12127   if (VT.getVectorElementType() == MVT::i1) {
12128     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12129         Subtarget->hasBWI())
12130       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12131     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12132         && InVT.getScalarSizeInBits() <= 16 &&
12133         Subtarget->hasBWI() && Subtarget->hasVLX())
12134       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12135     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12136         Subtarget->hasDQI())
12137       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12138     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12139         && InVT.getScalarSizeInBits() >= 32 &&
12140         Subtarget->hasDQI() && Subtarget->hasVLX())
12141       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12142   }
12143   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12144     if (VT.getVectorElementType().getSizeInBits() >=8)
12145       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12146
12147     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12148     unsigned NumElts = InVT.getVectorNumElements();
12149     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12150     if (InVT.getSizeInBits() < 512) {
12151       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12152       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12153       InVT = ExtVT;
12154     }
12155
12156     SDValue OneV =
12157      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12158     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12159     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12160   }
12161
12162   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12163     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12164     if (Subtarget->hasInt256()) {
12165       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12166       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12167       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12168                                 ShufMask);
12169       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12170                          DAG.getIntPtrConstant(0, DL));
12171     }
12172
12173     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12174                                DAG.getIntPtrConstant(0, DL));
12175     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12176                                DAG.getIntPtrConstant(2, DL));
12177     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12178     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12179     static const int ShufMask[] = {0, 2, 4, 6};
12180     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12181   }
12182
12183   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12184     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12185     if (Subtarget->hasInt256()) {
12186       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12187
12188       SmallVector<SDValue,32> pshufbMask;
12189       for (unsigned i = 0; i < 2; ++i) {
12190         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12191         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12192         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12193         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12194         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12195         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12196         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12197         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12198         for (unsigned j = 0; j < 8; ++j)
12199           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12200       }
12201       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12202       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12203       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12204
12205       static const int ShufMask[] = {0,  2,  -1,  -1};
12206       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12207                                 &ShufMask[0]);
12208       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12209                        DAG.getIntPtrConstant(0, DL));
12210       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12211     }
12212
12213     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12214                                DAG.getIntPtrConstant(0, DL));
12215
12216     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12217                                DAG.getIntPtrConstant(4, DL));
12218
12219     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12220     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12221
12222     // The PSHUFB mask:
12223     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12224                                    -1, -1, -1, -1, -1, -1, -1, -1};
12225
12226     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12227     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12228     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12229
12230     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12231     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12232
12233     // The MOVLHPS Mask:
12234     static const int ShufMask2[] = {0, 1, 4, 5};
12235     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12236     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12237   }
12238
12239   // Handle truncation of V256 to V128 using shuffles.
12240   if (!VT.is128BitVector() || !InVT.is256BitVector())
12241     return SDValue();
12242
12243   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12244
12245   unsigned NumElems = VT.getVectorNumElements();
12246   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12247
12248   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12249   // Prepare truncation shuffle mask
12250   for (unsigned i = 0; i != NumElems; ++i)
12251     MaskVec[i] = i * 2;
12252   SDValue V = DAG.getVectorShuffle(NVT, DL,
12253                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12254                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12255   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12256                      DAG.getIntPtrConstant(0, DL));
12257 }
12258
12259 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12260                                            SelectionDAG &DAG) const {
12261   assert(!Op.getSimpleValueType().isVector());
12262
12263   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12264     /*IsSigned=*/ true, /*IsReplace=*/ false);
12265   SDValue FIST = Vals.first, StackSlot = Vals.second;
12266   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12267   if (!FIST.getNode()) return Op;
12268
12269   if (StackSlot.getNode())
12270     // Load the result.
12271     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12272                        FIST, StackSlot, MachinePointerInfo(),
12273                        false, false, false, 0);
12274
12275   // The node is the result.
12276   return FIST;
12277 }
12278
12279 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12280                                            SelectionDAG &DAG) const {
12281   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12282     /*IsSigned=*/ false, /*IsReplace=*/ false);
12283   SDValue FIST = Vals.first, StackSlot = Vals.second;
12284   assert(FIST.getNode() && "Unexpected failure");
12285
12286   if (StackSlot.getNode())
12287     // Load the result.
12288     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12289                        FIST, StackSlot, MachinePointerInfo(),
12290                        false, false, false, 0);
12291
12292   // The node is the result.
12293   return FIST;
12294 }
12295
12296 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12297   SDLoc DL(Op);
12298   MVT VT = Op.getSimpleValueType();
12299   SDValue In = Op.getOperand(0);
12300   MVT SVT = In.getSimpleValueType();
12301
12302   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12303
12304   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12305                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12306                                  In, DAG.getUNDEF(SVT)));
12307 }
12308
12309 /// The only differences between FABS and FNEG are the mask and the logic op.
12310 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12311 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12312   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12313          "Wrong opcode for lowering FABS or FNEG.");
12314
12315   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12316
12317   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12318   // into an FNABS. We'll lower the FABS after that if it is still in use.
12319   if (IsFABS)
12320     for (SDNode *User : Op->uses())
12321       if (User->getOpcode() == ISD::FNEG)
12322         return Op;
12323
12324   SDValue Op0 = Op.getOperand(0);
12325   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12326
12327   SDLoc dl(Op);
12328   MVT VT = Op.getSimpleValueType();
12329   // Assume scalar op for initialization; update for vector if needed.
12330   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12331   // generate a 16-byte vector constant and logic op even for the scalar case.
12332   // Using a 16-byte mask allows folding the load of the mask with
12333   // the logic op, so it can save (~4 bytes) on code size.
12334   MVT EltVT = VT;
12335   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12336   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12337   // decide if we should generate a 16-byte constant mask when we only need 4 or
12338   // 8 bytes for the scalar case.
12339   if (VT.isVector()) {
12340     EltVT = VT.getVectorElementType();
12341     NumElts = VT.getVectorNumElements();
12342   }
12343
12344   unsigned EltBits = EltVT.getSizeInBits();
12345   LLVMContext *Context = DAG.getContext();
12346   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12347   APInt MaskElt =
12348     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12349   Constant *C = ConstantInt::get(*Context, MaskElt);
12350   C = ConstantVector::getSplat(NumElts, C);
12351   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12352   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12353   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12354   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12355                              MachinePointerInfo::getConstantPool(),
12356                              false, false, false, Alignment);
12357
12358   if (VT.isVector()) {
12359     // For a vector, cast operands to a vector type, perform the logic op,
12360     // and cast the result back to the original value type.
12361     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12362     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12363     SDValue Operand = IsFNABS ?
12364       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12365       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12366     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12367     return DAG.getNode(ISD::BITCAST, dl, VT,
12368                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12369   }
12370
12371   // If not vector, then scalar.
12372   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12373   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12374   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12375 }
12376
12377 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12379   LLVMContext *Context = DAG.getContext();
12380   SDValue Op0 = Op.getOperand(0);
12381   SDValue Op1 = Op.getOperand(1);
12382   SDLoc dl(Op);
12383   MVT VT = Op.getSimpleValueType();
12384   MVT SrcVT = Op1.getSimpleValueType();
12385
12386   // If second operand is smaller, extend it first.
12387   if (SrcVT.bitsLT(VT)) {
12388     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12389     SrcVT = VT;
12390   }
12391   // And if it is bigger, shrink it first.
12392   if (SrcVT.bitsGT(VT)) {
12393     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12394     SrcVT = VT;
12395   }
12396
12397   // At this point the operands and the result should have the same
12398   // type, and that won't be f80 since that is not custom lowered.
12399
12400   const fltSemantics &Sem =
12401       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12402   const unsigned SizeInBits = VT.getSizeInBits();
12403
12404   SmallVector<Constant *, 4> CV(
12405       VT == MVT::f64 ? 2 : 4,
12406       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12407
12408   // First, clear all bits but the sign bit from the second operand (sign).
12409   CV[0] = ConstantFP::get(*Context,
12410                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12411   Constant *C = ConstantVector::get(CV);
12412   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12413   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12414                               MachinePointerInfo::getConstantPool(),
12415                               false, false, false, 16);
12416   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12417
12418   // Next, clear the sign bit from the first operand (magnitude).
12419   // If it's a constant, we can clear it here.
12420   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12421     APFloat APF = Op0CN->getValueAPF();
12422     // If the magnitude is a positive zero, the sign bit alone is enough.
12423     if (APF.isPosZero())
12424       return SignBit;
12425     APF.clearSign();
12426     CV[0] = ConstantFP::get(*Context, APF);
12427   } else {
12428     CV[0] = ConstantFP::get(
12429         *Context,
12430         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12431   }
12432   C = ConstantVector::get(CV);
12433   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12434   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12435                             MachinePointerInfo::getConstantPool(),
12436                             false, false, false, 16);
12437   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12438   if (!isa<ConstantFPSDNode>(Op0))
12439     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12440
12441   // OR the magnitude value with the sign bit.
12442   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12443 }
12444
12445 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12446   SDValue N0 = Op.getOperand(0);
12447   SDLoc dl(Op);
12448   MVT VT = Op.getSimpleValueType();
12449
12450   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12451   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12452                                   DAG.getConstant(1, dl, VT));
12453   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12454 }
12455
12456 // Check whether an OR'd tree is PTEST-able.
12457 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12458                                       SelectionDAG &DAG) {
12459   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12460
12461   if (!Subtarget->hasSSE41())
12462     return SDValue();
12463
12464   if (!Op->hasOneUse())
12465     return SDValue();
12466
12467   SDNode *N = Op.getNode();
12468   SDLoc DL(N);
12469
12470   SmallVector<SDValue, 8> Opnds;
12471   DenseMap<SDValue, unsigned> VecInMap;
12472   SmallVector<SDValue, 8> VecIns;
12473   EVT VT = MVT::Other;
12474
12475   // Recognize a special case where a vector is casted into wide integer to
12476   // test all 0s.
12477   Opnds.push_back(N->getOperand(0));
12478   Opnds.push_back(N->getOperand(1));
12479
12480   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12481     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12482     // BFS traverse all OR'd operands.
12483     if (I->getOpcode() == ISD::OR) {
12484       Opnds.push_back(I->getOperand(0));
12485       Opnds.push_back(I->getOperand(1));
12486       // Re-evaluate the number of nodes to be traversed.
12487       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12488       continue;
12489     }
12490
12491     // Quit if a non-EXTRACT_VECTOR_ELT
12492     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12493       return SDValue();
12494
12495     // Quit if without a constant index.
12496     SDValue Idx = I->getOperand(1);
12497     if (!isa<ConstantSDNode>(Idx))
12498       return SDValue();
12499
12500     SDValue ExtractedFromVec = I->getOperand(0);
12501     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12502     if (M == VecInMap.end()) {
12503       VT = ExtractedFromVec.getValueType();
12504       // Quit if not 128/256-bit vector.
12505       if (!VT.is128BitVector() && !VT.is256BitVector())
12506         return SDValue();
12507       // Quit if not the same type.
12508       if (VecInMap.begin() != VecInMap.end() &&
12509           VT != VecInMap.begin()->first.getValueType())
12510         return SDValue();
12511       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12512       VecIns.push_back(ExtractedFromVec);
12513     }
12514     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12515   }
12516
12517   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12518          "Not extracted from 128-/256-bit vector.");
12519
12520   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12521
12522   for (DenseMap<SDValue, unsigned>::const_iterator
12523         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12524     // Quit if not all elements are used.
12525     if (I->second != FullMask)
12526       return SDValue();
12527   }
12528
12529   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12530
12531   // Cast all vectors into TestVT for PTEST.
12532   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12533     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12534
12535   // If more than one full vectors are evaluated, OR them first before PTEST.
12536   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12537     // Each iteration will OR 2 nodes and append the result until there is only
12538     // 1 node left, i.e. the final OR'd value of all vectors.
12539     SDValue LHS = VecIns[Slot];
12540     SDValue RHS = VecIns[Slot + 1];
12541     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12542   }
12543
12544   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12545                      VecIns.back(), VecIns.back());
12546 }
12547
12548 /// \brief return true if \c Op has a use that doesn't just read flags.
12549 static bool hasNonFlagsUse(SDValue Op) {
12550   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12551        ++UI) {
12552     SDNode *User = *UI;
12553     unsigned UOpNo = UI.getOperandNo();
12554     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12555       // Look pass truncate.
12556       UOpNo = User->use_begin().getOperandNo();
12557       User = *User->use_begin();
12558     }
12559
12560     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12561         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12562       return true;
12563   }
12564   return false;
12565 }
12566
12567 /// Emit nodes that will be selected as "test Op0,Op0", or something
12568 /// equivalent.
12569 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12570                                     SelectionDAG &DAG) const {
12571   if (Op.getValueType() == MVT::i1) {
12572     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12573     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12574                        DAG.getConstant(0, dl, MVT::i8));
12575   }
12576   // CF and OF aren't always set the way we want. Determine which
12577   // of these we need.
12578   bool NeedCF = false;
12579   bool NeedOF = false;
12580   switch (X86CC) {
12581   default: break;
12582   case X86::COND_A: case X86::COND_AE:
12583   case X86::COND_B: case X86::COND_BE:
12584     NeedCF = true;
12585     break;
12586   case X86::COND_G: case X86::COND_GE:
12587   case X86::COND_L: case X86::COND_LE:
12588   case X86::COND_O: case X86::COND_NO: {
12589     // Check if we really need to set the
12590     // Overflow flag. If NoSignedWrap is present
12591     // that is not actually needed.
12592     switch (Op->getOpcode()) {
12593     case ISD::ADD:
12594     case ISD::SUB:
12595     case ISD::MUL:
12596     case ISD::SHL: {
12597       const BinaryWithFlagsSDNode *BinNode =
12598           cast<BinaryWithFlagsSDNode>(Op.getNode());
12599       if (BinNode->Flags.hasNoSignedWrap())
12600         break;
12601     }
12602     default:
12603       NeedOF = true;
12604       break;
12605     }
12606     break;
12607   }
12608   }
12609   // See if we can use the EFLAGS value from the operand instead of
12610   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12611   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12612   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12613     // Emit a CMP with 0, which is the TEST pattern.
12614     //if (Op.getValueType() == MVT::i1)
12615     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12616     //                     DAG.getConstant(0, MVT::i1));
12617     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12618                        DAG.getConstant(0, dl, Op.getValueType()));
12619   }
12620   unsigned Opcode = 0;
12621   unsigned NumOperands = 0;
12622
12623   // Truncate operations may prevent the merge of the SETCC instruction
12624   // and the arithmetic instruction before it. Attempt to truncate the operands
12625   // of the arithmetic instruction and use a reduced bit-width instruction.
12626   bool NeedTruncation = false;
12627   SDValue ArithOp = Op;
12628   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12629     SDValue Arith = Op->getOperand(0);
12630     // Both the trunc and the arithmetic op need to have one user each.
12631     if (Arith->hasOneUse())
12632       switch (Arith.getOpcode()) {
12633         default: break;
12634         case ISD::ADD:
12635         case ISD::SUB:
12636         case ISD::AND:
12637         case ISD::OR:
12638         case ISD::XOR: {
12639           NeedTruncation = true;
12640           ArithOp = Arith;
12641         }
12642       }
12643   }
12644
12645   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12646   // which may be the result of a CAST.  We use the variable 'Op', which is the
12647   // non-casted variable when we check for possible users.
12648   switch (ArithOp.getOpcode()) {
12649   case ISD::ADD:
12650     // Due to an isel shortcoming, be conservative if this add is likely to be
12651     // selected as part of a load-modify-store instruction. When the root node
12652     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12653     // uses of other nodes in the match, such as the ADD in this case. This
12654     // leads to the ADD being left around and reselected, with the result being
12655     // two adds in the output.  Alas, even if none our users are stores, that
12656     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12657     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12658     // climbing the DAG back to the root, and it doesn't seem to be worth the
12659     // effort.
12660     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12661          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12662       if (UI->getOpcode() != ISD::CopyToReg &&
12663           UI->getOpcode() != ISD::SETCC &&
12664           UI->getOpcode() != ISD::STORE)
12665         goto default_case;
12666
12667     if (ConstantSDNode *C =
12668         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12669       // An add of one will be selected as an INC.
12670       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12671         Opcode = X86ISD::INC;
12672         NumOperands = 1;
12673         break;
12674       }
12675
12676       // An add of negative one (subtract of one) will be selected as a DEC.
12677       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12678         Opcode = X86ISD::DEC;
12679         NumOperands = 1;
12680         break;
12681       }
12682     }
12683
12684     // Otherwise use a regular EFLAGS-setting add.
12685     Opcode = X86ISD::ADD;
12686     NumOperands = 2;
12687     break;
12688   case ISD::SHL:
12689   case ISD::SRL:
12690     // If we have a constant logical shift that's only used in a comparison
12691     // against zero turn it into an equivalent AND. This allows turning it into
12692     // a TEST instruction later.
12693     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12694         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12695       EVT VT = Op.getValueType();
12696       unsigned BitWidth = VT.getSizeInBits();
12697       unsigned ShAmt = Op->getConstantOperandVal(1);
12698       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12699         break;
12700       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12701                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12702                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12703       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12704         break;
12705       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12706                                 DAG.getConstant(Mask, dl, VT));
12707       DAG.ReplaceAllUsesWith(Op, New);
12708       Op = New;
12709     }
12710     break;
12711
12712   case ISD::AND:
12713     // If the primary and result isn't used, don't bother using X86ISD::AND,
12714     // because a TEST instruction will be better.
12715     if (!hasNonFlagsUse(Op))
12716       break;
12717     // FALL THROUGH
12718   case ISD::SUB:
12719   case ISD::OR:
12720   case ISD::XOR:
12721     // Due to the ISEL shortcoming noted above, be conservative if this op is
12722     // likely to be selected as part of a load-modify-store instruction.
12723     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12724            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12725       if (UI->getOpcode() == ISD::STORE)
12726         goto default_case;
12727
12728     // Otherwise use a regular EFLAGS-setting instruction.
12729     switch (ArithOp.getOpcode()) {
12730     default: llvm_unreachable("unexpected operator!");
12731     case ISD::SUB: Opcode = X86ISD::SUB; break;
12732     case ISD::XOR: Opcode = X86ISD::XOR; break;
12733     case ISD::AND: Opcode = X86ISD::AND; break;
12734     case ISD::OR: {
12735       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12736         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12737         if (EFLAGS.getNode())
12738           return EFLAGS;
12739       }
12740       Opcode = X86ISD::OR;
12741       break;
12742     }
12743     }
12744
12745     NumOperands = 2;
12746     break;
12747   case X86ISD::ADD:
12748   case X86ISD::SUB:
12749   case X86ISD::INC:
12750   case X86ISD::DEC:
12751   case X86ISD::OR:
12752   case X86ISD::XOR:
12753   case X86ISD::AND:
12754     return SDValue(Op.getNode(), 1);
12755   default:
12756   default_case:
12757     break;
12758   }
12759
12760   // If we found that truncation is beneficial, perform the truncation and
12761   // update 'Op'.
12762   if (NeedTruncation) {
12763     EVT VT = Op.getValueType();
12764     SDValue WideVal = Op->getOperand(0);
12765     EVT WideVT = WideVal.getValueType();
12766     unsigned ConvertedOp = 0;
12767     // Use a target machine opcode to prevent further DAGCombine
12768     // optimizations that may separate the arithmetic operations
12769     // from the setcc node.
12770     switch (WideVal.getOpcode()) {
12771       default: break;
12772       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12773       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12774       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12775       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12776       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12777     }
12778
12779     if (ConvertedOp) {
12780       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12781       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12782         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12783         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12784         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12785       }
12786     }
12787   }
12788
12789   if (Opcode == 0)
12790     // Emit a CMP with 0, which is the TEST pattern.
12791     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12792                        DAG.getConstant(0, dl, Op.getValueType()));
12793
12794   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12795   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12796
12797   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12798   DAG.ReplaceAllUsesWith(Op, New);
12799   return SDValue(New.getNode(), 1);
12800 }
12801
12802 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12803 /// equivalent.
12804 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12805                                    SDLoc dl, SelectionDAG &DAG) const {
12806   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12807     if (C->getAPIntValue() == 0)
12808       return EmitTest(Op0, X86CC, dl, DAG);
12809
12810      if (Op0.getValueType() == MVT::i1)
12811        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12812   }
12813
12814   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12815        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12816     // Do the comparison at i32 if it's smaller, besides the Atom case.
12817     // This avoids subregister aliasing issues. Keep the smaller reference
12818     // if we're optimizing for size, however, as that'll allow better folding
12819     // of memory operations.
12820     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12821         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12822             Attribute::MinSize) &&
12823         !Subtarget->isAtom()) {
12824       unsigned ExtendOp =
12825           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12826       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12827       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12828     }
12829     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12830     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12831     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12832                               Op0, Op1);
12833     return SDValue(Sub.getNode(), 1);
12834   }
12835   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12836 }
12837
12838 /// Convert a comparison if required by the subtarget.
12839 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12840                                                  SelectionDAG &DAG) const {
12841   // If the subtarget does not support the FUCOMI instruction, floating-point
12842   // comparisons have to be converted.
12843   if (Subtarget->hasCMov() ||
12844       Cmp.getOpcode() != X86ISD::CMP ||
12845       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12846       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12847     return Cmp;
12848
12849   // The instruction selector will select an FUCOM instruction instead of
12850   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12851   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12852   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12853   SDLoc dl(Cmp);
12854   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12855   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12856   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12857                             DAG.getConstant(8, dl, MVT::i8));
12858   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12859   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12860 }
12861
12862 /// The minimum architected relative accuracy is 2^-12. We need one
12863 /// Newton-Raphson step to have a good float result (24 bits of precision).
12864 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12865                                             DAGCombinerInfo &DCI,
12866                                             unsigned &RefinementSteps,
12867                                             bool &UseOneConstNR) const {
12868   // FIXME: We should use instruction latency models to calculate the cost of
12869   // each potential sequence, but this is very hard to do reliably because
12870   // at least Intel's Core* chips have variable timing based on the number of
12871   // significant digits in the divisor and/or sqrt operand.
12872   if (!Subtarget->useSqrtEst())
12873     return SDValue();
12874
12875   EVT VT = Op.getValueType();
12876
12877   // SSE1 has rsqrtss and rsqrtps.
12878   // TODO: Add support for AVX512 (v16f32).
12879   // It is likely not profitable to do this for f64 because a double-precision
12880   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12881   // instructions: convert to single, rsqrtss, convert back to double, refine
12882   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12883   // along with FMA, this could be a throughput win.
12884   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12885       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12886     RefinementSteps = 1;
12887     UseOneConstNR = false;
12888     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12889   }
12890   return SDValue();
12891 }
12892
12893 /// The minimum architected relative accuracy is 2^-12. We need one
12894 /// Newton-Raphson step to have a good float result (24 bits of precision).
12895 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12896                                             DAGCombinerInfo &DCI,
12897                                             unsigned &RefinementSteps) const {
12898   // FIXME: We should use instruction latency models to calculate the cost of
12899   // each potential sequence, but this is very hard to do reliably because
12900   // at least Intel's Core* chips have variable timing based on the number of
12901   // significant digits in the divisor.
12902   if (!Subtarget->useReciprocalEst())
12903     return SDValue();
12904
12905   EVT VT = Op.getValueType();
12906
12907   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12908   // TODO: Add support for AVX512 (v16f32).
12909   // It is likely not profitable to do this for f64 because a double-precision
12910   // reciprocal estimate with refinement on x86 prior to FMA requires
12911   // 15 instructions: convert to single, rcpss, convert back to double, refine
12912   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12913   // along with FMA, this could be a throughput win.
12914   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12915       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12916     RefinementSteps = ReciprocalEstimateRefinementSteps;
12917     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12918   }
12919   return SDValue();
12920 }
12921
12922 /// If we have at least two divisions that use the same divisor, convert to
12923 /// multplication by a reciprocal. This may need to be adjusted for a given
12924 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12925 /// This is because we still need one division to calculate the reciprocal and
12926 /// then we need two multiplies by that reciprocal as replacements for the
12927 /// original divisions.
12928 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12929   return NumUsers > 1;
12930 }
12931
12932 static bool isAllOnes(SDValue V) {
12933   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12934   return C && C->isAllOnesValue();
12935 }
12936
12937 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12938 /// if it's possible.
12939 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12940                                      SDLoc dl, SelectionDAG &DAG) const {
12941   SDValue Op0 = And.getOperand(0);
12942   SDValue Op1 = And.getOperand(1);
12943   if (Op0.getOpcode() == ISD::TRUNCATE)
12944     Op0 = Op0.getOperand(0);
12945   if (Op1.getOpcode() == ISD::TRUNCATE)
12946     Op1 = Op1.getOperand(0);
12947
12948   SDValue LHS, RHS;
12949   if (Op1.getOpcode() == ISD::SHL)
12950     std::swap(Op0, Op1);
12951   if (Op0.getOpcode() == ISD::SHL) {
12952     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12953       if (And00C->getZExtValue() == 1) {
12954         // If we looked past a truncate, check that it's only truncating away
12955         // known zeros.
12956         unsigned BitWidth = Op0.getValueSizeInBits();
12957         unsigned AndBitWidth = And.getValueSizeInBits();
12958         if (BitWidth > AndBitWidth) {
12959           APInt Zeros, Ones;
12960           DAG.computeKnownBits(Op0, Zeros, Ones);
12961           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12962             return SDValue();
12963         }
12964         LHS = Op1;
12965         RHS = Op0.getOperand(1);
12966       }
12967   } else if (Op1.getOpcode() == ISD::Constant) {
12968     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12969     uint64_t AndRHSVal = AndRHS->getZExtValue();
12970     SDValue AndLHS = Op0;
12971
12972     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12973       LHS = AndLHS.getOperand(0);
12974       RHS = AndLHS.getOperand(1);
12975     }
12976
12977     // Use BT if the immediate can't be encoded in a TEST instruction.
12978     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12979       LHS = AndLHS;
12980       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12981     }
12982   }
12983
12984   if (LHS.getNode()) {
12985     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12986     // instruction.  Since the shift amount is in-range-or-undefined, we know
12987     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12988     // the encoding for the i16 version is larger than the i32 version.
12989     // Also promote i16 to i32 for performance / code size reason.
12990     if (LHS.getValueType() == MVT::i8 ||
12991         LHS.getValueType() == MVT::i16)
12992       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12993
12994     // If the operand types disagree, extend the shift amount to match.  Since
12995     // BT ignores high bits (like shifts) we can use anyextend.
12996     if (LHS.getValueType() != RHS.getValueType())
12997       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12998
12999     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13000     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13001     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13002                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13003   }
13004
13005   return SDValue();
13006 }
13007
13008 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13009 /// mask CMPs.
13010 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13011                               SDValue &Op1) {
13012   unsigned SSECC;
13013   bool Swap = false;
13014
13015   // SSE Condition code mapping:
13016   //  0 - EQ
13017   //  1 - LT
13018   //  2 - LE
13019   //  3 - UNORD
13020   //  4 - NEQ
13021   //  5 - NLT
13022   //  6 - NLE
13023   //  7 - ORD
13024   switch (SetCCOpcode) {
13025   default: llvm_unreachable("Unexpected SETCC condition");
13026   case ISD::SETOEQ:
13027   case ISD::SETEQ:  SSECC = 0; break;
13028   case ISD::SETOGT:
13029   case ISD::SETGT:  Swap = true; // Fallthrough
13030   case ISD::SETLT:
13031   case ISD::SETOLT: SSECC = 1; break;
13032   case ISD::SETOGE:
13033   case ISD::SETGE:  Swap = true; // Fallthrough
13034   case ISD::SETLE:
13035   case ISD::SETOLE: SSECC = 2; break;
13036   case ISD::SETUO:  SSECC = 3; break;
13037   case ISD::SETUNE:
13038   case ISD::SETNE:  SSECC = 4; break;
13039   case ISD::SETULE: Swap = true; // Fallthrough
13040   case ISD::SETUGE: SSECC = 5; break;
13041   case ISD::SETULT: Swap = true; // Fallthrough
13042   case ISD::SETUGT: SSECC = 6; break;
13043   case ISD::SETO:   SSECC = 7; break;
13044   case ISD::SETUEQ:
13045   case ISD::SETONE: SSECC = 8; break;
13046   }
13047   if (Swap)
13048     std::swap(Op0, Op1);
13049
13050   return SSECC;
13051 }
13052
13053 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13054 // ones, and then concatenate the result back.
13055 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13056   MVT VT = Op.getSimpleValueType();
13057
13058   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13059          "Unsupported value type for operation");
13060
13061   unsigned NumElems = VT.getVectorNumElements();
13062   SDLoc dl(Op);
13063   SDValue CC = Op.getOperand(2);
13064
13065   // Extract the LHS vectors
13066   SDValue LHS = Op.getOperand(0);
13067   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13068   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13069
13070   // Extract the RHS vectors
13071   SDValue RHS = Op.getOperand(1);
13072   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13073   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13074
13075   // Issue the operation on the smaller types and concatenate the result back
13076   MVT EltVT = VT.getVectorElementType();
13077   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13078   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13079                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13080                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13081 }
13082
13083 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13084   SDValue Op0 = Op.getOperand(0);
13085   SDValue Op1 = Op.getOperand(1);
13086   SDValue CC = Op.getOperand(2);
13087   MVT VT = Op.getSimpleValueType();
13088   SDLoc dl(Op);
13089
13090   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13091          "Unexpected type for boolean compare operation");
13092   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13093   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13094                                DAG.getConstant(-1, dl, VT));
13095   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13096                                DAG.getConstant(-1, dl, VT));
13097   switch (SetCCOpcode) {
13098   default: llvm_unreachable("Unexpected SETCC condition");
13099   case ISD::SETNE:
13100     // (x != y) -> ~(x ^ y)
13101     return DAG.getNode(ISD::XOR, dl, VT,
13102                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13103                        DAG.getConstant(-1, dl, VT));
13104   case ISD::SETEQ:
13105     // (x == y) -> (x ^ y)
13106     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13107   case ISD::SETUGT:
13108   case ISD::SETGT:
13109     // (x > y) -> (x & ~y)
13110     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13111   case ISD::SETULT:
13112   case ISD::SETLT:
13113     // (x < y) -> (~x & y)
13114     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13115   case ISD::SETULE:
13116   case ISD::SETLE:
13117     // (x <= y) -> (~x | y)
13118     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13119   case ISD::SETUGE:
13120   case ISD::SETGE:
13121     // (x >=y) -> (x | ~y)
13122     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13123   }
13124 }
13125
13126 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13127                                      const X86Subtarget *Subtarget) {
13128   SDValue Op0 = Op.getOperand(0);
13129   SDValue Op1 = Op.getOperand(1);
13130   SDValue CC = Op.getOperand(2);
13131   MVT VT = Op.getSimpleValueType();
13132   SDLoc dl(Op);
13133
13134   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13135          Op.getValueType().getScalarType() == MVT::i1 &&
13136          "Cannot set masked compare for this operation");
13137
13138   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13139   unsigned  Opc = 0;
13140   bool Unsigned = false;
13141   bool Swap = false;
13142   unsigned SSECC;
13143   switch (SetCCOpcode) {
13144   default: llvm_unreachable("Unexpected SETCC condition");
13145   case ISD::SETNE:  SSECC = 4; break;
13146   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13147   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13148   case ISD::SETLT:  Swap = true; //fall-through
13149   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13150   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13151   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13152   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13153   case ISD::SETULE: Unsigned = true; //fall-through
13154   case ISD::SETLE:  SSECC = 2; break;
13155   }
13156
13157   if (Swap)
13158     std::swap(Op0, Op1);
13159   if (Opc)
13160     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13161   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13162   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13163                      DAG.getConstant(SSECC, dl, MVT::i8));
13164 }
13165
13166 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13167 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13168 /// return an empty value.
13169 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13170 {
13171   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13172   if (!BV)
13173     return SDValue();
13174
13175   MVT VT = Op1.getSimpleValueType();
13176   MVT EVT = VT.getVectorElementType();
13177   unsigned n = VT.getVectorNumElements();
13178   SmallVector<SDValue, 8> ULTOp1;
13179
13180   for (unsigned i = 0; i < n; ++i) {
13181     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13182     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13183       return SDValue();
13184
13185     // Avoid underflow.
13186     APInt Val = Elt->getAPIntValue();
13187     if (Val == 0)
13188       return SDValue();
13189
13190     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13191   }
13192
13193   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13194 }
13195
13196 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13197                            SelectionDAG &DAG) {
13198   SDValue Op0 = Op.getOperand(0);
13199   SDValue Op1 = Op.getOperand(1);
13200   SDValue CC = Op.getOperand(2);
13201   MVT VT = Op.getSimpleValueType();
13202   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13203   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13204   SDLoc dl(Op);
13205
13206   if (isFP) {
13207 #ifndef NDEBUG
13208     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13209     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13210 #endif
13211
13212     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13213     unsigned Opc = X86ISD::CMPP;
13214     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13215       assert(VT.getVectorNumElements() <= 16);
13216       Opc = X86ISD::CMPM;
13217     }
13218     // In the two special cases we can't handle, emit two comparisons.
13219     if (SSECC == 8) {
13220       unsigned CC0, CC1;
13221       unsigned CombineOpc;
13222       if (SetCCOpcode == ISD::SETUEQ) {
13223         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13224       } else {
13225         assert(SetCCOpcode == ISD::SETONE);
13226         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13227       }
13228
13229       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13230                                  DAG.getConstant(CC0, dl, MVT::i8));
13231       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13232                                  DAG.getConstant(CC1, dl, MVT::i8));
13233       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13234     }
13235     // Handle all other FP comparisons here.
13236     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13237                        DAG.getConstant(SSECC, dl, MVT::i8));
13238   }
13239
13240   // Break 256-bit integer vector compare into smaller ones.
13241   if (VT.is256BitVector() && !Subtarget->hasInt256())
13242     return Lower256IntVSETCC(Op, DAG);
13243
13244   EVT OpVT = Op1.getValueType();
13245   if (OpVT.getVectorElementType() == MVT::i1)
13246     return LowerBoolVSETCC_AVX512(Op, DAG);
13247
13248   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13249   if (Subtarget->hasAVX512()) {
13250     if (Op1.getValueType().is512BitVector() ||
13251         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13252         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13253       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13254
13255     // In AVX-512 architecture setcc returns mask with i1 elements,
13256     // But there is no compare instruction for i8 and i16 elements in KNL.
13257     // We are not talking about 512-bit operands in this case, these
13258     // types are illegal.
13259     if (MaskResult &&
13260         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13261          OpVT.getVectorElementType().getSizeInBits() >= 8))
13262       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13263                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13264   }
13265
13266   // We are handling one of the integer comparisons here.  Since SSE only has
13267   // GT and EQ comparisons for integer, swapping operands and multiple
13268   // operations may be required for some comparisons.
13269   unsigned Opc;
13270   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13271   bool Subus = false;
13272
13273   switch (SetCCOpcode) {
13274   default: llvm_unreachable("Unexpected SETCC condition");
13275   case ISD::SETNE:  Invert = true;
13276   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13277   case ISD::SETLT:  Swap = true;
13278   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13279   case ISD::SETGE:  Swap = true;
13280   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13281                     Invert = true; break;
13282   case ISD::SETULT: Swap = true;
13283   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13284                     FlipSigns = true; break;
13285   case ISD::SETUGE: Swap = true;
13286   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13287                     FlipSigns = true; Invert = true; break;
13288   }
13289
13290   // Special case: Use min/max operations for SETULE/SETUGE
13291   MVT VET = VT.getVectorElementType();
13292   bool hasMinMax =
13293        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13294     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13295
13296   if (hasMinMax) {
13297     switch (SetCCOpcode) {
13298     default: break;
13299     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13300     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13301     }
13302
13303     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13304   }
13305
13306   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13307   if (!MinMax && hasSubus) {
13308     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13309     // Op0 u<= Op1:
13310     //   t = psubus Op0, Op1
13311     //   pcmpeq t, <0..0>
13312     switch (SetCCOpcode) {
13313     default: break;
13314     case ISD::SETULT: {
13315       // If the comparison is against a constant we can turn this into a
13316       // setule.  With psubus, setule does not require a swap.  This is
13317       // beneficial because the constant in the register is no longer
13318       // destructed as the destination so it can be hoisted out of a loop.
13319       // Only do this pre-AVX since vpcmp* is no longer destructive.
13320       if (Subtarget->hasAVX())
13321         break;
13322       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13323       if (ULEOp1.getNode()) {
13324         Op1 = ULEOp1;
13325         Subus = true; Invert = false; Swap = false;
13326       }
13327       break;
13328     }
13329     // Psubus is better than flip-sign because it requires no inversion.
13330     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13331     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13332     }
13333
13334     if (Subus) {
13335       Opc = X86ISD::SUBUS;
13336       FlipSigns = false;
13337     }
13338   }
13339
13340   if (Swap)
13341     std::swap(Op0, Op1);
13342
13343   // Check that the operation in question is available (most are plain SSE2,
13344   // but PCMPGTQ and PCMPEQQ have different requirements).
13345   if (VT == MVT::v2i64) {
13346     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13347       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13348
13349       // First cast everything to the right type.
13350       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13351       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13352
13353       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13354       // bits of the inputs before performing those operations. The lower
13355       // compare is always unsigned.
13356       SDValue SB;
13357       if (FlipSigns) {
13358         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13359       } else {
13360         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13361         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13362         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13363                          Sign, Zero, Sign, Zero);
13364       }
13365       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13366       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13367
13368       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13369       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13370       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13371
13372       // Create masks for only the low parts/high parts of the 64 bit integers.
13373       static const int MaskHi[] = { 1, 1, 3, 3 };
13374       static const int MaskLo[] = { 0, 0, 2, 2 };
13375       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13376       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13377       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13378
13379       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13380       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13381
13382       if (Invert)
13383         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13384
13385       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13386     }
13387
13388     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13389       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13390       // pcmpeqd + pshufd + pand.
13391       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13392
13393       // First cast everything to the right type.
13394       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13395       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13396
13397       // Do the compare.
13398       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13399
13400       // Make sure the lower and upper halves are both all-ones.
13401       static const int Mask[] = { 1, 0, 3, 2 };
13402       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13403       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13404
13405       if (Invert)
13406         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13407
13408       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13409     }
13410   }
13411
13412   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13413   // bits of the inputs before performing those operations.
13414   if (FlipSigns) {
13415     EVT EltVT = VT.getVectorElementType();
13416     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13417                                  VT);
13418     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13419     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13420   }
13421
13422   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13423
13424   // If the logical-not of the result is required, perform that now.
13425   if (Invert)
13426     Result = DAG.getNOT(dl, Result, VT);
13427
13428   if (MinMax)
13429     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13430
13431   if (Subus)
13432     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13433                          getZeroVector(VT, Subtarget, DAG, dl));
13434
13435   return Result;
13436 }
13437
13438 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13439
13440   MVT VT = Op.getSimpleValueType();
13441
13442   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13443
13444   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13445          && "SetCC type must be 8-bit or 1-bit integer");
13446   SDValue Op0 = Op.getOperand(0);
13447   SDValue Op1 = Op.getOperand(1);
13448   SDLoc dl(Op);
13449   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13450
13451   // Optimize to BT if possible.
13452   // Lower (X & (1 << N)) == 0 to BT(X, N).
13453   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13454   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13455   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13456       Op1.getOpcode() == ISD::Constant &&
13457       cast<ConstantSDNode>(Op1)->isNullValue() &&
13458       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13459     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13460     if (NewSetCC.getNode()) {
13461       if (VT == MVT::i1)
13462         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13463       return NewSetCC;
13464     }
13465   }
13466
13467   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13468   // these.
13469   if (Op1.getOpcode() == ISD::Constant &&
13470       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13471        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13472       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13473
13474     // If the input is a setcc, then reuse the input setcc or use a new one with
13475     // the inverted condition.
13476     if (Op0.getOpcode() == X86ISD::SETCC) {
13477       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13478       bool Invert = (CC == ISD::SETNE) ^
13479         cast<ConstantSDNode>(Op1)->isNullValue();
13480       if (!Invert)
13481         return Op0;
13482
13483       CCode = X86::GetOppositeBranchCondition(CCode);
13484       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13485                                   DAG.getConstant(CCode, dl, MVT::i8),
13486                                   Op0.getOperand(1));
13487       if (VT == MVT::i1)
13488         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13489       return SetCC;
13490     }
13491   }
13492   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13493       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13494       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13495
13496     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13497     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13498   }
13499
13500   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13501   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13502   if (X86CC == X86::COND_INVALID)
13503     return SDValue();
13504
13505   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13506   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13507   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13508                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13509   if (VT == MVT::i1)
13510     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13511   return SetCC;
13512 }
13513
13514 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13515 static bool isX86LogicalCmp(SDValue Op) {
13516   unsigned Opc = Op.getNode()->getOpcode();
13517   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13518       Opc == X86ISD::SAHF)
13519     return true;
13520   if (Op.getResNo() == 1 &&
13521       (Opc == X86ISD::ADD ||
13522        Opc == X86ISD::SUB ||
13523        Opc == X86ISD::ADC ||
13524        Opc == X86ISD::SBB ||
13525        Opc == X86ISD::SMUL ||
13526        Opc == X86ISD::UMUL ||
13527        Opc == X86ISD::INC ||
13528        Opc == X86ISD::DEC ||
13529        Opc == X86ISD::OR ||
13530        Opc == X86ISD::XOR ||
13531        Opc == X86ISD::AND))
13532     return true;
13533
13534   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13535     return true;
13536
13537   return false;
13538 }
13539
13540 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13541   if (V.getOpcode() != ISD::TRUNCATE)
13542     return false;
13543
13544   SDValue VOp0 = V.getOperand(0);
13545   unsigned InBits = VOp0.getValueSizeInBits();
13546   unsigned Bits = V.getValueSizeInBits();
13547   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13548 }
13549
13550 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13551   bool addTest = true;
13552   SDValue Cond  = Op.getOperand(0);
13553   SDValue Op1 = Op.getOperand(1);
13554   SDValue Op2 = Op.getOperand(2);
13555   SDLoc DL(Op);
13556   EVT VT = Op1.getValueType();
13557   SDValue CC;
13558
13559   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13560   // are available or VBLENDV if AVX is available.
13561   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13562   if (Cond.getOpcode() == ISD::SETCC &&
13563       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13564        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13565       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13566     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13567     int SSECC = translateX86FSETCC(
13568         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13569
13570     if (SSECC != 8) {
13571       if (Subtarget->hasAVX512()) {
13572         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13573                                   DAG.getConstant(SSECC, DL, MVT::i8));
13574         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13575       }
13576
13577       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13578                                 DAG.getConstant(SSECC, DL, MVT::i8));
13579
13580       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13581       // of 3 logic instructions for size savings and potentially speed.
13582       // Unfortunately, there is no scalar form of VBLENDV.
13583
13584       // If either operand is a constant, don't try this. We can expect to
13585       // optimize away at least one of the logic instructions later in that
13586       // case, so that sequence would be faster than a variable blend.
13587
13588       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13589       // uses XMM0 as the selection register. That may need just as many
13590       // instructions as the AND/ANDN/OR sequence due to register moves, so
13591       // don't bother.
13592
13593       if (Subtarget->hasAVX() &&
13594           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13595
13596         // Convert to vectors, do a VSELECT, and convert back to scalar.
13597         // All of the conversions should be optimized away.
13598
13599         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13600         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13601         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13602         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13603
13604         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13605         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13606
13607         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13608
13609         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13610                            VSel, DAG.getIntPtrConstant(0, DL));
13611       }
13612       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13613       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13614       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13615     }
13616   }
13617
13618   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13619     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13620     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13621                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13622     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13623                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13624     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13625                                     Cond, Op1, Op2);
13626     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13627   }
13628
13629   if (Cond.getOpcode() == ISD::SETCC) {
13630     SDValue NewCond = LowerSETCC(Cond, DAG);
13631     if (NewCond.getNode())
13632       Cond = NewCond;
13633   }
13634
13635   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13636   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13637   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13638   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13639   if (Cond.getOpcode() == X86ISD::SETCC &&
13640       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13641       isZero(Cond.getOperand(1).getOperand(1))) {
13642     SDValue Cmp = Cond.getOperand(1);
13643
13644     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13645
13646     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13647         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13648       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13649
13650       SDValue CmpOp0 = Cmp.getOperand(0);
13651       // Apply further optimizations for special cases
13652       // (select (x != 0), -1, 0) -> neg & sbb
13653       // (select (x == 0), 0, -1) -> neg & sbb
13654       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13655         if (YC->isNullValue() &&
13656             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13657           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13658           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13659                                     DAG.getConstant(0, DL,
13660                                                     CmpOp0.getValueType()),
13661                                     CmpOp0);
13662           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13663                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13664                                     SDValue(Neg.getNode(), 1));
13665           return Res;
13666         }
13667
13668       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13669                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13670       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13671
13672       SDValue Res =   // Res = 0 or -1.
13673         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13674                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13675
13676       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13677         Res = DAG.getNOT(DL, Res, Res.getValueType());
13678
13679       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13680       if (!N2C || !N2C->isNullValue())
13681         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13682       return Res;
13683     }
13684   }
13685
13686   // Look past (and (setcc_carry (cmp ...)), 1).
13687   if (Cond.getOpcode() == ISD::AND &&
13688       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13689     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13690     if (C && C->getAPIntValue() == 1)
13691       Cond = Cond.getOperand(0);
13692   }
13693
13694   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13695   // setting operand in place of the X86ISD::SETCC.
13696   unsigned CondOpcode = Cond.getOpcode();
13697   if (CondOpcode == X86ISD::SETCC ||
13698       CondOpcode == X86ISD::SETCC_CARRY) {
13699     CC = Cond.getOperand(0);
13700
13701     SDValue Cmp = Cond.getOperand(1);
13702     unsigned Opc = Cmp.getOpcode();
13703     MVT VT = Op.getSimpleValueType();
13704
13705     bool IllegalFPCMov = false;
13706     if (VT.isFloatingPoint() && !VT.isVector() &&
13707         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13708       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13709
13710     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13711         Opc == X86ISD::BT) { // FIXME
13712       Cond = Cmp;
13713       addTest = false;
13714     }
13715   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13716              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13717              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13718               Cond.getOperand(0).getValueType() != MVT::i8)) {
13719     SDValue LHS = Cond.getOperand(0);
13720     SDValue RHS = Cond.getOperand(1);
13721     unsigned X86Opcode;
13722     unsigned X86Cond;
13723     SDVTList VTs;
13724     switch (CondOpcode) {
13725     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13726     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13727     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13728     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13729     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13730     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13731     default: llvm_unreachable("unexpected overflowing operator");
13732     }
13733     if (CondOpcode == ISD::UMULO)
13734       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13735                           MVT::i32);
13736     else
13737       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13738
13739     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13740
13741     if (CondOpcode == ISD::UMULO)
13742       Cond = X86Op.getValue(2);
13743     else
13744       Cond = X86Op.getValue(1);
13745
13746     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13747     addTest = false;
13748   }
13749
13750   if (addTest) {
13751     // Look pass the truncate if the high bits are known zero.
13752     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13753         Cond = Cond.getOperand(0);
13754
13755     // We know the result of AND is compared against zero. Try to match
13756     // it to BT.
13757     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13758       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13759       if (NewSetCC.getNode()) {
13760         CC = NewSetCC.getOperand(0);
13761         Cond = NewSetCC.getOperand(1);
13762         addTest = false;
13763       }
13764     }
13765   }
13766
13767   if (addTest) {
13768     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13769     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13770   }
13771
13772   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13773   // a <  b ?  0 : -1 -> RES = setcc_carry
13774   // a >= b ? -1 :  0 -> RES = setcc_carry
13775   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13776   if (Cond.getOpcode() == X86ISD::SUB) {
13777     Cond = ConvertCmpIfNecessary(Cond, DAG);
13778     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13779
13780     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13781         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13782       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13783                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13784                                 Cond);
13785       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13786         return DAG.getNOT(DL, Res, Res.getValueType());
13787       return Res;
13788     }
13789   }
13790
13791   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13792   // widen the cmov and push the truncate through. This avoids introducing a new
13793   // branch during isel and doesn't add any extensions.
13794   if (Op.getValueType() == MVT::i8 &&
13795       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13796     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13797     if (T1.getValueType() == T2.getValueType() &&
13798         // Blacklist CopyFromReg to avoid partial register stalls.
13799         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13800       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13801       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13802       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13803     }
13804   }
13805
13806   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13807   // condition is true.
13808   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13809   SDValue Ops[] = { Op2, Op1, CC, Cond };
13810   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13811 }
13812
13813 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13814                                        SelectionDAG &DAG) {
13815   MVT VT = Op->getSimpleValueType(0);
13816   SDValue In = Op->getOperand(0);
13817   MVT InVT = In.getSimpleValueType();
13818   MVT VTElt = VT.getVectorElementType();
13819   MVT InVTElt = InVT.getVectorElementType();
13820   SDLoc dl(Op);
13821
13822   // SKX processor
13823   if ((InVTElt == MVT::i1) &&
13824       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13825         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13826
13827        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13828         VTElt.getSizeInBits() <= 16)) ||
13829
13830        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13831         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13832
13833        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13834         VTElt.getSizeInBits() >= 32))))
13835     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13836
13837   unsigned int NumElts = VT.getVectorNumElements();
13838
13839   if (NumElts != 8 && NumElts != 16)
13840     return SDValue();
13841
13842   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13843     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13844       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13845     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13846   }
13847
13848   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13849   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13850   SDValue NegOne =
13851    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13852                    ExtVT);
13853   SDValue Zero =
13854    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13855
13856   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13857   if (VT.is512BitVector())
13858     return V;
13859   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13860 }
13861
13862 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13863                                 SelectionDAG &DAG) {
13864   MVT VT = Op->getSimpleValueType(0);
13865   SDValue In = Op->getOperand(0);
13866   MVT InVT = In.getSimpleValueType();
13867   SDLoc dl(Op);
13868
13869   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13870     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13871
13872   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13873       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13874       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13875     return SDValue();
13876
13877   if (Subtarget->hasInt256())
13878     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13879
13880   // Optimize vectors in AVX mode
13881   // Sign extend  v8i16 to v8i32 and
13882   //              v4i32 to v4i64
13883   //
13884   // Divide input vector into two parts
13885   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13886   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13887   // concat the vectors to original VT
13888
13889   unsigned NumElems = InVT.getVectorNumElements();
13890   SDValue Undef = DAG.getUNDEF(InVT);
13891
13892   SmallVector<int,8> ShufMask1(NumElems, -1);
13893   for (unsigned i = 0; i != NumElems/2; ++i)
13894     ShufMask1[i] = i;
13895
13896   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13897
13898   SmallVector<int,8> ShufMask2(NumElems, -1);
13899   for (unsigned i = 0; i != NumElems/2; ++i)
13900     ShufMask2[i] = i + NumElems/2;
13901
13902   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13903
13904   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13905                                 VT.getVectorNumElements()/2);
13906
13907   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13908   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13909
13910   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13911 }
13912
13913 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13914 // may emit an illegal shuffle but the expansion is still better than scalar
13915 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13916 // we'll emit a shuffle and a arithmetic shift.
13917 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13918 // TODO: It is possible to support ZExt by zeroing the undef values during
13919 // the shuffle phase or after the shuffle.
13920 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13921                                  SelectionDAG &DAG) {
13922   MVT RegVT = Op.getSimpleValueType();
13923   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13924   assert(RegVT.isInteger() &&
13925          "We only custom lower integer vector sext loads.");
13926
13927   // Nothing useful we can do without SSE2 shuffles.
13928   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13929
13930   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13931   SDLoc dl(Ld);
13932   EVT MemVT = Ld->getMemoryVT();
13933   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13934   unsigned RegSz = RegVT.getSizeInBits();
13935
13936   ISD::LoadExtType Ext = Ld->getExtensionType();
13937
13938   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13939          && "Only anyext and sext are currently implemented.");
13940   assert(MemVT != RegVT && "Cannot extend to the same type");
13941   assert(MemVT.isVector() && "Must load a vector from memory");
13942
13943   unsigned NumElems = RegVT.getVectorNumElements();
13944   unsigned MemSz = MemVT.getSizeInBits();
13945   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13946
13947   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13948     // The only way in which we have a legal 256-bit vector result but not the
13949     // integer 256-bit operations needed to directly lower a sextload is if we
13950     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13951     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13952     // correctly legalized. We do this late to allow the canonical form of
13953     // sextload to persist throughout the rest of the DAG combiner -- it wants
13954     // to fold together any extensions it can, and so will fuse a sign_extend
13955     // of an sextload into a sextload targeting a wider value.
13956     SDValue Load;
13957     if (MemSz == 128) {
13958       // Just switch this to a normal load.
13959       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13960                                        "it must be a legal 128-bit vector "
13961                                        "type!");
13962       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13963                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13964                   Ld->isInvariant(), Ld->getAlignment());
13965     } else {
13966       assert(MemSz < 128 &&
13967              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13968       // Do an sext load to a 128-bit vector type. We want to use the same
13969       // number of elements, but elements half as wide. This will end up being
13970       // recursively lowered by this routine, but will succeed as we definitely
13971       // have all the necessary features if we're using AVX1.
13972       EVT HalfEltVT =
13973           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13974       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13975       Load =
13976           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13977                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13978                          Ld->isNonTemporal(), Ld->isInvariant(),
13979                          Ld->getAlignment());
13980     }
13981
13982     // Replace chain users with the new chain.
13983     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13984     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13985
13986     // Finally, do a normal sign-extend to the desired register.
13987     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13988   }
13989
13990   // All sizes must be a power of two.
13991   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13992          "Non-power-of-two elements are not custom lowered!");
13993
13994   // Attempt to load the original value using scalar loads.
13995   // Find the largest scalar type that divides the total loaded size.
13996   MVT SclrLoadTy = MVT::i8;
13997   for (MVT Tp : MVT::integer_valuetypes()) {
13998     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13999       SclrLoadTy = Tp;
14000     }
14001   }
14002
14003   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14004   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14005       (64 <= MemSz))
14006     SclrLoadTy = MVT::f64;
14007
14008   // Calculate the number of scalar loads that we need to perform
14009   // in order to load our vector from memory.
14010   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14011
14012   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14013          "Can only lower sext loads with a single scalar load!");
14014
14015   unsigned loadRegZize = RegSz;
14016   if (Ext == ISD::SEXTLOAD && RegSz == 256)
14017     loadRegZize /= 2;
14018
14019   // Represent our vector as a sequence of elements which are the
14020   // largest scalar that we can load.
14021   EVT LoadUnitVecVT = EVT::getVectorVT(
14022       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14023
14024   // Represent the data using the same element type that is stored in
14025   // memory. In practice, we ''widen'' MemVT.
14026   EVT WideVecVT =
14027       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14028                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14029
14030   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14031          "Invalid vector type");
14032
14033   // We can't shuffle using an illegal type.
14034   assert(TLI.isTypeLegal(WideVecVT) &&
14035          "We only lower types that form legal widened vector types");
14036
14037   SmallVector<SDValue, 8> Chains;
14038   SDValue Ptr = Ld->getBasePtr();
14039   SDValue Increment =
14040       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14041   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14042
14043   for (unsigned i = 0; i < NumLoads; ++i) {
14044     // Perform a single load.
14045     SDValue ScalarLoad =
14046         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14047                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14048                     Ld->getAlignment());
14049     Chains.push_back(ScalarLoad.getValue(1));
14050     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14051     // another round of DAGCombining.
14052     if (i == 0)
14053       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14054     else
14055       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14056                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14057
14058     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14059   }
14060
14061   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14062
14063   // Bitcast the loaded value to a vector of the original element type, in
14064   // the size of the target vector type.
14065   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14066   unsigned SizeRatio = RegSz / MemSz;
14067
14068   if (Ext == ISD::SEXTLOAD) {
14069     // If we have SSE4.1, we can directly emit a VSEXT node.
14070     if (Subtarget->hasSSE41()) {
14071       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14072       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14073       return Sext;
14074     }
14075
14076     // Otherwise we'll shuffle the small elements in the high bits of the
14077     // larger type and perform an arithmetic shift. If the shift is not legal
14078     // it's better to scalarize.
14079     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14080            "We can't implement a sext load without an arithmetic right shift!");
14081
14082     // Redistribute the loaded elements into the different locations.
14083     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14084     for (unsigned i = 0; i != NumElems; ++i)
14085       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14086
14087     SDValue Shuff = DAG.getVectorShuffle(
14088         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14089
14090     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14091
14092     // Build the arithmetic shift.
14093     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14094                    MemVT.getVectorElementType().getSizeInBits();
14095     Shuff =
14096         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14097                     DAG.getConstant(Amt, dl, RegVT));
14098
14099     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14100     return Shuff;
14101   }
14102
14103   // Redistribute the loaded elements into the different locations.
14104   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14105   for (unsigned i = 0; i != NumElems; ++i)
14106     ShuffleVec[i * SizeRatio] = i;
14107
14108   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14109                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14110
14111   // Bitcast to the requested type.
14112   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14113   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14114   return Shuff;
14115 }
14116
14117 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14118 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14119 // from the AND / OR.
14120 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14121   Opc = Op.getOpcode();
14122   if (Opc != ISD::OR && Opc != ISD::AND)
14123     return false;
14124   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14125           Op.getOperand(0).hasOneUse() &&
14126           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14127           Op.getOperand(1).hasOneUse());
14128 }
14129
14130 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14131 // 1 and that the SETCC node has a single use.
14132 static bool isXor1OfSetCC(SDValue Op) {
14133   if (Op.getOpcode() != ISD::XOR)
14134     return false;
14135   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14136   if (N1C && N1C->getAPIntValue() == 1) {
14137     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14138       Op.getOperand(0).hasOneUse();
14139   }
14140   return false;
14141 }
14142
14143 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14144   bool addTest = true;
14145   SDValue Chain = Op.getOperand(0);
14146   SDValue Cond  = Op.getOperand(1);
14147   SDValue Dest  = Op.getOperand(2);
14148   SDLoc dl(Op);
14149   SDValue CC;
14150   bool Inverted = false;
14151
14152   if (Cond.getOpcode() == ISD::SETCC) {
14153     // Check for setcc([su]{add,sub,mul}o == 0).
14154     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14155         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14156         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14157         Cond.getOperand(0).getResNo() == 1 &&
14158         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14159          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14160          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14161          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14162          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14163          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14164       Inverted = true;
14165       Cond = Cond.getOperand(0);
14166     } else {
14167       SDValue NewCond = LowerSETCC(Cond, DAG);
14168       if (NewCond.getNode())
14169         Cond = NewCond;
14170     }
14171   }
14172 #if 0
14173   // FIXME: LowerXALUO doesn't handle these!!
14174   else if (Cond.getOpcode() == X86ISD::ADD  ||
14175            Cond.getOpcode() == X86ISD::SUB  ||
14176            Cond.getOpcode() == X86ISD::SMUL ||
14177            Cond.getOpcode() == X86ISD::UMUL)
14178     Cond = LowerXALUO(Cond, DAG);
14179 #endif
14180
14181   // Look pass (and (setcc_carry (cmp ...)), 1).
14182   if (Cond.getOpcode() == ISD::AND &&
14183       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14184     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14185     if (C && C->getAPIntValue() == 1)
14186       Cond = Cond.getOperand(0);
14187   }
14188
14189   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14190   // setting operand in place of the X86ISD::SETCC.
14191   unsigned CondOpcode = Cond.getOpcode();
14192   if (CondOpcode == X86ISD::SETCC ||
14193       CondOpcode == X86ISD::SETCC_CARRY) {
14194     CC = Cond.getOperand(0);
14195
14196     SDValue Cmp = Cond.getOperand(1);
14197     unsigned Opc = Cmp.getOpcode();
14198     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14199     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14200       Cond = Cmp;
14201       addTest = false;
14202     } else {
14203       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14204       default: break;
14205       case X86::COND_O:
14206       case X86::COND_B:
14207         // These can only come from an arithmetic instruction with overflow,
14208         // e.g. SADDO, UADDO.
14209         Cond = Cond.getNode()->getOperand(1);
14210         addTest = false;
14211         break;
14212       }
14213     }
14214   }
14215   CondOpcode = Cond.getOpcode();
14216   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14217       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14218       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14219        Cond.getOperand(0).getValueType() != MVT::i8)) {
14220     SDValue LHS = Cond.getOperand(0);
14221     SDValue RHS = Cond.getOperand(1);
14222     unsigned X86Opcode;
14223     unsigned X86Cond;
14224     SDVTList VTs;
14225     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14226     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14227     // X86ISD::INC).
14228     switch (CondOpcode) {
14229     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14230     case ISD::SADDO:
14231       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14232         if (C->isOne()) {
14233           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14234           break;
14235         }
14236       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14237     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14238     case ISD::SSUBO:
14239       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14240         if (C->isOne()) {
14241           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14242           break;
14243         }
14244       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14245     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14246     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14247     default: llvm_unreachable("unexpected overflowing operator");
14248     }
14249     if (Inverted)
14250       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14251     if (CondOpcode == ISD::UMULO)
14252       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14253                           MVT::i32);
14254     else
14255       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14256
14257     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14258
14259     if (CondOpcode == ISD::UMULO)
14260       Cond = X86Op.getValue(2);
14261     else
14262       Cond = X86Op.getValue(1);
14263
14264     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14265     addTest = false;
14266   } else {
14267     unsigned CondOpc;
14268     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14269       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14270       if (CondOpc == ISD::OR) {
14271         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14272         // two branches instead of an explicit OR instruction with a
14273         // separate test.
14274         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14275             isX86LogicalCmp(Cmp)) {
14276           CC = Cond.getOperand(0).getOperand(0);
14277           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14278                               Chain, Dest, CC, Cmp);
14279           CC = Cond.getOperand(1).getOperand(0);
14280           Cond = Cmp;
14281           addTest = false;
14282         }
14283       } else { // ISD::AND
14284         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14285         // two branches instead of an explicit AND instruction with a
14286         // separate test. However, we only do this if this block doesn't
14287         // have a fall-through edge, because this requires an explicit
14288         // jmp when the condition is false.
14289         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14290             isX86LogicalCmp(Cmp) &&
14291             Op.getNode()->hasOneUse()) {
14292           X86::CondCode CCode =
14293             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14294           CCode = X86::GetOppositeBranchCondition(CCode);
14295           CC = DAG.getConstant(CCode, dl, MVT::i8);
14296           SDNode *User = *Op.getNode()->use_begin();
14297           // Look for an unconditional branch following this conditional branch.
14298           // We need this because we need to reverse the successors in order
14299           // to implement FCMP_OEQ.
14300           if (User->getOpcode() == ISD::BR) {
14301             SDValue FalseBB = User->getOperand(1);
14302             SDNode *NewBR =
14303               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14304             assert(NewBR == User);
14305             (void)NewBR;
14306             Dest = FalseBB;
14307
14308             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14309                                 Chain, Dest, CC, Cmp);
14310             X86::CondCode CCode =
14311               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14312             CCode = X86::GetOppositeBranchCondition(CCode);
14313             CC = DAG.getConstant(CCode, dl, MVT::i8);
14314             Cond = Cmp;
14315             addTest = false;
14316           }
14317         }
14318       }
14319     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14320       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14321       // It should be transformed during dag combiner except when the condition
14322       // is set by a arithmetics with overflow node.
14323       X86::CondCode CCode =
14324         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14325       CCode = X86::GetOppositeBranchCondition(CCode);
14326       CC = DAG.getConstant(CCode, dl, MVT::i8);
14327       Cond = Cond.getOperand(0).getOperand(1);
14328       addTest = false;
14329     } else if (Cond.getOpcode() == ISD::SETCC &&
14330                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14331       // For FCMP_OEQ, we can emit
14332       // two branches instead of an explicit AND instruction with a
14333       // separate test. However, we only do this if this block doesn't
14334       // have a fall-through edge, because this requires an explicit
14335       // jmp when the condition is false.
14336       if (Op.getNode()->hasOneUse()) {
14337         SDNode *User = *Op.getNode()->use_begin();
14338         // Look for an unconditional branch following this conditional branch.
14339         // We need this because we need to reverse the successors in order
14340         // to implement FCMP_OEQ.
14341         if (User->getOpcode() == ISD::BR) {
14342           SDValue FalseBB = User->getOperand(1);
14343           SDNode *NewBR =
14344             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14345           assert(NewBR == User);
14346           (void)NewBR;
14347           Dest = FalseBB;
14348
14349           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14350                                     Cond.getOperand(0), Cond.getOperand(1));
14351           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14352           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14353           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14354                               Chain, Dest, CC, Cmp);
14355           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14356           Cond = Cmp;
14357           addTest = false;
14358         }
14359       }
14360     } else if (Cond.getOpcode() == ISD::SETCC &&
14361                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14362       // For FCMP_UNE, we can emit
14363       // two branches instead of an explicit AND instruction with a
14364       // separate test. However, we only do this if this block doesn't
14365       // have a fall-through edge, because this requires an explicit
14366       // jmp when the condition is false.
14367       if (Op.getNode()->hasOneUse()) {
14368         SDNode *User = *Op.getNode()->use_begin();
14369         // Look for an unconditional branch following this conditional branch.
14370         // We need this because we need to reverse the successors in order
14371         // to implement FCMP_UNE.
14372         if (User->getOpcode() == ISD::BR) {
14373           SDValue FalseBB = User->getOperand(1);
14374           SDNode *NewBR =
14375             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14376           assert(NewBR == User);
14377           (void)NewBR;
14378
14379           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14380                                     Cond.getOperand(0), Cond.getOperand(1));
14381           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14382           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14383           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14384                               Chain, Dest, CC, Cmp);
14385           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14386           Cond = Cmp;
14387           addTest = false;
14388           Dest = FalseBB;
14389         }
14390       }
14391     }
14392   }
14393
14394   if (addTest) {
14395     // Look pass the truncate if the high bits are known zero.
14396     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14397         Cond = Cond.getOperand(0);
14398
14399     // We know the result of AND is compared against zero. Try to match
14400     // it to BT.
14401     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14402       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14403       if (NewSetCC.getNode()) {
14404         CC = NewSetCC.getOperand(0);
14405         Cond = NewSetCC.getOperand(1);
14406         addTest = false;
14407       }
14408     }
14409   }
14410
14411   if (addTest) {
14412     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14413     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14414     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14415   }
14416   Cond = ConvertCmpIfNecessary(Cond, DAG);
14417   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14418                      Chain, Dest, CC, Cond);
14419 }
14420
14421 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14422 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14423 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14424 // that the guard pages used by the OS virtual memory manager are allocated in
14425 // correct sequence.
14426 SDValue
14427 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14428                                            SelectionDAG &DAG) const {
14429   MachineFunction &MF = DAG.getMachineFunction();
14430   bool SplitStack = MF.shouldSplitStack();
14431   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14432                SplitStack;
14433   SDLoc dl(Op);
14434
14435   if (!Lower) {
14436     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14437     SDNode* Node = Op.getNode();
14438
14439     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14440     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14441         " not tell us which reg is the stack pointer!");
14442     EVT VT = Node->getValueType(0);
14443     SDValue Tmp1 = SDValue(Node, 0);
14444     SDValue Tmp2 = SDValue(Node, 1);
14445     SDValue Tmp3 = Node->getOperand(2);
14446     SDValue Chain = Tmp1.getOperand(0);
14447
14448     // Chain the dynamic stack allocation so that it doesn't modify the stack
14449     // pointer when other instructions are using the stack.
14450     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14451         SDLoc(Node));
14452
14453     SDValue Size = Tmp2.getOperand(1);
14454     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14455     Chain = SP.getValue(1);
14456     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14457     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14458     unsigned StackAlign = TFI.getStackAlignment();
14459     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14460     if (Align > StackAlign)
14461       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14462           DAG.getConstant(-(uint64_t)Align, dl, VT));
14463     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14464
14465     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14466         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14467         SDLoc(Node));
14468
14469     SDValue Ops[2] = { Tmp1, Tmp2 };
14470     return DAG.getMergeValues(Ops, dl);
14471   }
14472
14473   // Get the inputs.
14474   SDValue Chain = Op.getOperand(0);
14475   SDValue Size  = Op.getOperand(1);
14476   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14477   EVT VT = Op.getNode()->getValueType(0);
14478
14479   bool Is64Bit = Subtarget->is64Bit();
14480   EVT SPTy = getPointerTy();
14481
14482   if (SplitStack) {
14483     MachineRegisterInfo &MRI = MF.getRegInfo();
14484
14485     if (Is64Bit) {
14486       // The 64 bit implementation of segmented stacks needs to clobber both r10
14487       // r11. This makes it impossible to use it along with nested parameters.
14488       const Function *F = MF.getFunction();
14489
14490       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14491            I != E; ++I)
14492         if (I->hasNestAttr())
14493           report_fatal_error("Cannot use segmented stacks with functions that "
14494                              "have nested arguments.");
14495     }
14496
14497     const TargetRegisterClass *AddrRegClass =
14498       getRegClassFor(getPointerTy());
14499     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14500     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14501     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14502                                 DAG.getRegister(Vreg, SPTy));
14503     SDValue Ops1[2] = { Value, Chain };
14504     return DAG.getMergeValues(Ops1, dl);
14505   } else {
14506     SDValue Flag;
14507     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14508
14509     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14510     Flag = Chain.getValue(1);
14511     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14512
14513     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14514
14515     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14516     unsigned SPReg = RegInfo->getStackRegister();
14517     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14518     Chain = SP.getValue(1);
14519
14520     if (Align) {
14521       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14522                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14523       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14524     }
14525
14526     SDValue Ops1[2] = { SP, Chain };
14527     return DAG.getMergeValues(Ops1, dl);
14528   }
14529 }
14530
14531 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14532   MachineFunction &MF = DAG.getMachineFunction();
14533   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14534
14535   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14536   SDLoc DL(Op);
14537
14538   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14539     // vastart just stores the address of the VarArgsFrameIndex slot into the
14540     // memory location argument.
14541     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14542                                    getPointerTy());
14543     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14544                         MachinePointerInfo(SV), false, false, 0);
14545   }
14546
14547   // __va_list_tag:
14548   //   gp_offset         (0 - 6 * 8)
14549   //   fp_offset         (48 - 48 + 8 * 16)
14550   //   overflow_arg_area (point to parameters coming in memory).
14551   //   reg_save_area
14552   SmallVector<SDValue, 8> MemOps;
14553   SDValue FIN = Op.getOperand(1);
14554   // Store gp_offset
14555   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14556                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14557                                                DL, MVT::i32),
14558                                FIN, MachinePointerInfo(SV), false, false, 0);
14559   MemOps.push_back(Store);
14560
14561   // Store fp_offset
14562   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14563                     FIN, DAG.getIntPtrConstant(4, DL));
14564   Store = DAG.getStore(Op.getOperand(0), DL,
14565                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14566                                        MVT::i32),
14567                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14568   MemOps.push_back(Store);
14569
14570   // Store ptr to overflow_arg_area
14571   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14572                     FIN, DAG.getIntPtrConstant(4, DL));
14573   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14574                                     getPointerTy());
14575   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14576                        MachinePointerInfo(SV, 8),
14577                        false, false, 0);
14578   MemOps.push_back(Store);
14579
14580   // Store ptr to reg_save_area.
14581   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14582                     FIN, DAG.getIntPtrConstant(8, DL));
14583   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14584                                     getPointerTy());
14585   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14586                        MachinePointerInfo(SV, 16), false, false, 0);
14587   MemOps.push_back(Store);
14588   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14589 }
14590
14591 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14592   assert(Subtarget->is64Bit() &&
14593          "LowerVAARG only handles 64-bit va_arg!");
14594   assert((Subtarget->isTargetLinux() ||
14595           Subtarget->isTargetDarwin()) &&
14596           "Unhandled target in LowerVAARG");
14597   assert(Op.getNode()->getNumOperands() == 4);
14598   SDValue Chain = Op.getOperand(0);
14599   SDValue SrcPtr = Op.getOperand(1);
14600   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14601   unsigned Align = Op.getConstantOperandVal(3);
14602   SDLoc dl(Op);
14603
14604   EVT ArgVT = Op.getNode()->getValueType(0);
14605   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14606   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14607   uint8_t ArgMode;
14608
14609   // Decide which area this value should be read from.
14610   // TODO: Implement the AMD64 ABI in its entirety. This simple
14611   // selection mechanism works only for the basic types.
14612   if (ArgVT == MVT::f80) {
14613     llvm_unreachable("va_arg for f80 not yet implemented");
14614   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14615     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14616   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14617     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14618   } else {
14619     llvm_unreachable("Unhandled argument type in LowerVAARG");
14620   }
14621
14622   if (ArgMode == 2) {
14623     // Sanity Check: Make sure using fp_offset makes sense.
14624     assert(!Subtarget->useSoftFloat() &&
14625            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14626                Attribute::NoImplicitFloat)) &&
14627            Subtarget->hasSSE1());
14628   }
14629
14630   // Insert VAARG_64 node into the DAG
14631   // VAARG_64 returns two values: Variable Argument Address, Chain
14632   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14633                        DAG.getConstant(ArgMode, dl, MVT::i8),
14634                        DAG.getConstant(Align, dl, MVT::i32)};
14635   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14636   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14637                                           VTs, InstOps, MVT::i64,
14638                                           MachinePointerInfo(SV),
14639                                           /*Align=*/0,
14640                                           /*Volatile=*/false,
14641                                           /*ReadMem=*/true,
14642                                           /*WriteMem=*/true);
14643   Chain = VAARG.getValue(1);
14644
14645   // Load the next argument and return it
14646   return DAG.getLoad(ArgVT, dl,
14647                      Chain,
14648                      VAARG,
14649                      MachinePointerInfo(),
14650                      false, false, false, 0);
14651 }
14652
14653 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14654                            SelectionDAG &DAG) {
14655   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14656   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14657   SDValue Chain = Op.getOperand(0);
14658   SDValue DstPtr = Op.getOperand(1);
14659   SDValue SrcPtr = Op.getOperand(2);
14660   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14661   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14662   SDLoc DL(Op);
14663
14664   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14665                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14666                        false, false,
14667                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14668 }
14669
14670 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14671 // amount is a constant. Takes immediate version of shift as input.
14672 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14673                                           SDValue SrcOp, uint64_t ShiftAmt,
14674                                           SelectionDAG &DAG) {
14675   MVT ElementType = VT.getVectorElementType();
14676
14677   // Fold this packed shift into its first operand if ShiftAmt is 0.
14678   if (ShiftAmt == 0)
14679     return SrcOp;
14680
14681   // Check for ShiftAmt >= element width
14682   if (ShiftAmt >= ElementType.getSizeInBits()) {
14683     if (Opc == X86ISD::VSRAI)
14684       ShiftAmt = ElementType.getSizeInBits() - 1;
14685     else
14686       return DAG.getConstant(0, dl, VT);
14687   }
14688
14689   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14690          && "Unknown target vector shift-by-constant node");
14691
14692   // Fold this packed vector shift into a build vector if SrcOp is a
14693   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14694   if (VT == SrcOp.getSimpleValueType() &&
14695       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14696     SmallVector<SDValue, 8> Elts;
14697     unsigned NumElts = SrcOp->getNumOperands();
14698     ConstantSDNode *ND;
14699
14700     switch(Opc) {
14701     default: llvm_unreachable(nullptr);
14702     case X86ISD::VSHLI:
14703       for (unsigned i=0; i!=NumElts; ++i) {
14704         SDValue CurrentOp = SrcOp->getOperand(i);
14705         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14706           Elts.push_back(CurrentOp);
14707           continue;
14708         }
14709         ND = cast<ConstantSDNode>(CurrentOp);
14710         const APInt &C = ND->getAPIntValue();
14711         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14712       }
14713       break;
14714     case X86ISD::VSRLI:
14715       for (unsigned i=0; i!=NumElts; ++i) {
14716         SDValue CurrentOp = SrcOp->getOperand(i);
14717         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14718           Elts.push_back(CurrentOp);
14719           continue;
14720         }
14721         ND = cast<ConstantSDNode>(CurrentOp);
14722         const APInt &C = ND->getAPIntValue();
14723         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14724       }
14725       break;
14726     case X86ISD::VSRAI:
14727       for (unsigned i=0; i!=NumElts; ++i) {
14728         SDValue CurrentOp = SrcOp->getOperand(i);
14729         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14730           Elts.push_back(CurrentOp);
14731           continue;
14732         }
14733         ND = cast<ConstantSDNode>(CurrentOp);
14734         const APInt &C = ND->getAPIntValue();
14735         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14736       }
14737       break;
14738     }
14739
14740     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14741   }
14742
14743   return DAG.getNode(Opc, dl, VT, SrcOp,
14744                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14745 }
14746
14747 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14748 // may or may not be a constant. Takes immediate version of shift as input.
14749 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14750                                    SDValue SrcOp, SDValue ShAmt,
14751                                    SelectionDAG &DAG) {
14752   MVT SVT = ShAmt.getSimpleValueType();
14753   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14754
14755   // Catch shift-by-constant.
14756   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14757     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14758                                       CShAmt->getZExtValue(), DAG);
14759
14760   // Change opcode to non-immediate version
14761   switch (Opc) {
14762     default: llvm_unreachable("Unknown target vector shift node");
14763     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14764     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14765     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14766   }
14767
14768   const X86Subtarget &Subtarget =
14769       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14770   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14771       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14772     // Let the shuffle legalizer expand this shift amount node.
14773     SDValue Op0 = ShAmt.getOperand(0);
14774     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14775     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14776   } else {
14777     // Need to build a vector containing shift amount.
14778     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14779     SmallVector<SDValue, 4> ShOps;
14780     ShOps.push_back(ShAmt);
14781     if (SVT == MVT::i32) {
14782       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14783       ShOps.push_back(DAG.getUNDEF(SVT));
14784     }
14785     ShOps.push_back(DAG.getUNDEF(SVT));
14786
14787     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14788     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14789   }
14790
14791   // The return type has to be a 128-bit type with the same element
14792   // type as the input type.
14793   MVT EltVT = VT.getVectorElementType();
14794   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14795
14796   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14797   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14798 }
14799
14800 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14801 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14802 /// necessary casting for \p Mask when lowering masking intrinsics.
14803 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14804                                     SDValue PreservedSrc,
14805                                     const X86Subtarget *Subtarget,
14806                                     SelectionDAG &DAG) {
14807     EVT VT = Op.getValueType();
14808     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14809                                   MVT::i1, VT.getVectorNumElements());
14810     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14811                                      Mask.getValueType().getSizeInBits());
14812     SDLoc dl(Op);
14813
14814     assert(MaskVT.isSimple() && "invalid mask type");
14815
14816     if (isAllOnes(Mask))
14817       return Op;
14818
14819     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14820     // are extracted by EXTRACT_SUBVECTOR.
14821     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14822                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14823                               DAG.getIntPtrConstant(0, dl));
14824
14825     switch (Op.getOpcode()) {
14826       default: break;
14827       case X86ISD::PCMPEQM:
14828       case X86ISD::PCMPGTM:
14829       case X86ISD::CMPM:
14830       case X86ISD::CMPMU:
14831         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14832     }
14833     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14834       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14835     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14836 }
14837
14838 /// \brief Creates an SDNode for a predicated scalar operation.
14839 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14840 /// The mask is comming as MVT::i8 and it should be truncated
14841 /// to MVT::i1 while lowering masking intrinsics.
14842 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14843 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14844 /// a scalar instruction.
14845 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14846                                     SDValue PreservedSrc,
14847                                     const X86Subtarget *Subtarget,
14848                                     SelectionDAG &DAG) {
14849     if (isAllOnes(Mask))
14850       return Op;
14851
14852     EVT VT = Op.getValueType();
14853     SDLoc dl(Op);
14854     // The mask should be of type MVT::i1
14855     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14856
14857     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14858       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14859     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14860 }
14861
14862 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14863                                        SelectionDAG &DAG) {
14864   SDLoc dl(Op);
14865   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14866   EVT VT = Op.getValueType();
14867   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14868   if (IntrData) {
14869     switch(IntrData->Type) {
14870     case INTR_TYPE_1OP:
14871       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14872     case INTR_TYPE_2OP:
14873       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14874         Op.getOperand(2));
14875     case INTR_TYPE_3OP:
14876       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14877         Op.getOperand(2), Op.getOperand(3));
14878     case INTR_TYPE_1OP_MASK_RM: {
14879       SDValue Src = Op.getOperand(1);
14880       SDValue Src0 = Op.getOperand(2);
14881       SDValue Mask = Op.getOperand(3);
14882       SDValue RoundingMode = Op.getOperand(4);
14883       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14884                                               RoundingMode),
14885                                   Mask, Src0, Subtarget, DAG);
14886     }
14887     case INTR_TYPE_SCALAR_MASK_RM: {
14888       SDValue Src1 = Op.getOperand(1);
14889       SDValue Src2 = Op.getOperand(2);
14890       SDValue Src0 = Op.getOperand(3);
14891       SDValue Mask = Op.getOperand(4);
14892       // There are 2 kinds of intrinsics in this group:
14893       // (1) With supress-all-exceptions (sae) - 6 operands
14894       // (2) With rounding mode and sae - 7 operands.
14895       if (Op.getNumOperands() == 6) {
14896         SDValue Sae  = Op.getOperand(5);
14897         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14898                                                 Sae),
14899                                     Mask, Src0, Subtarget, DAG);
14900       }
14901       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14902       SDValue RoundingMode  = Op.getOperand(5);
14903       SDValue Sae  = Op.getOperand(6);
14904       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14905                                               RoundingMode, Sae),
14906                                   Mask, Src0, Subtarget, DAG);
14907     }
14908     case INTR_TYPE_2OP_MASK: {
14909       SDValue Src1 = Op.getOperand(1);
14910       SDValue Src2 = Op.getOperand(2);
14911       SDValue PassThru = Op.getOperand(3);
14912       SDValue Mask = Op.getOperand(4);
14913       // We specify 2 possible opcodes for intrinsics with rounding modes.
14914       // First, we check if the intrinsic may have non-default rounding mode,
14915       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14916       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14917       if (IntrWithRoundingModeOpcode != 0) {
14918         SDValue Rnd = Op.getOperand(5);
14919         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14920         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14921           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14922                                       dl, Op.getValueType(),
14923                                       Src1, Src2, Rnd),
14924                                       Mask, PassThru, Subtarget, DAG);
14925         }
14926       }
14927       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14928                                               Src1,Src2),
14929                                   Mask, PassThru, Subtarget, DAG);
14930     }
14931     case FMA_OP_MASK: {
14932       SDValue Src1 = Op.getOperand(1);
14933       SDValue Src2 = Op.getOperand(2);
14934       SDValue Src3 = Op.getOperand(3);
14935       SDValue Mask = Op.getOperand(4);
14936       // We specify 2 possible opcodes for intrinsics with rounding modes.
14937       // First, we check if the intrinsic may have non-default rounding mode,
14938       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14939       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14940       if (IntrWithRoundingModeOpcode != 0) {
14941         SDValue Rnd = Op.getOperand(5);
14942         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14943             X86::STATIC_ROUNDING::CUR_DIRECTION)
14944           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14945                                                   dl, Op.getValueType(),
14946                                                   Src1, Src2, Src3, Rnd),
14947                                       Mask, Src1, Subtarget, DAG);
14948       }
14949       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14950                                               dl, Op.getValueType(),
14951                                               Src1, Src2, Src3),
14952                                   Mask, Src1, Subtarget, DAG);
14953     }
14954     case CMP_MASK:
14955     case CMP_MASK_CC: {
14956       // Comparison intrinsics with masks.
14957       // Example of transformation:
14958       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14959       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14960       // (i8 (bitcast
14961       //   (v8i1 (insert_subvector undef,
14962       //           (v2i1 (and (PCMPEQM %a, %b),
14963       //                      (extract_subvector
14964       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14965       EVT VT = Op.getOperand(1).getValueType();
14966       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14967                                     VT.getVectorNumElements());
14968       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14969       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14970                                        Mask.getValueType().getSizeInBits());
14971       SDValue Cmp;
14972       if (IntrData->Type == CMP_MASK_CC) {
14973         SDValue CC = Op.getOperand(3);
14974         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14975         // We specify 2 possible opcodes for intrinsics with rounding modes.
14976         // First, we check if the intrinsic may have non-default rounding mode,
14977         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14978         if (IntrData->Opc1 != 0) {
14979           SDValue Rnd = Op.getOperand(5);
14980           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14981               X86::STATIC_ROUNDING::CUR_DIRECTION)
14982             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14983                               Op.getOperand(2), CC, Rnd);
14984         }
14985         //default rounding mode
14986         if(!Cmp.getNode())
14987             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14988                               Op.getOperand(2), CC);
14989
14990       } else {
14991         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14992         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14993                           Op.getOperand(2));
14994       }
14995       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14996                                              DAG.getTargetConstant(0, dl,
14997                                                                    MaskVT),
14998                                              Subtarget, DAG);
14999       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15000                                 DAG.getUNDEF(BitcastVT), CmpMask,
15001                                 DAG.getIntPtrConstant(0, dl));
15002       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15003     }
15004     case COMI: { // Comparison intrinsics
15005       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15006       SDValue LHS = Op.getOperand(1);
15007       SDValue RHS = Op.getOperand(2);
15008       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15009       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15010       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15011       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15012                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15013       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15014     }
15015     case VSHIFT:
15016       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15017                                  Op.getOperand(1), Op.getOperand(2), DAG);
15018     case VSHIFT_MASK:
15019       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15020                                                       Op.getSimpleValueType(),
15021                                                       Op.getOperand(1),
15022                                                       Op.getOperand(2), DAG),
15023                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15024                                   DAG);
15025     case COMPRESS_EXPAND_IN_REG: {
15026       SDValue Mask = Op.getOperand(3);
15027       SDValue DataToCompress = Op.getOperand(1);
15028       SDValue PassThru = Op.getOperand(2);
15029       if (isAllOnes(Mask)) // return data as is
15030         return Op.getOperand(1);
15031       EVT VT = Op.getValueType();
15032       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15033                                     VT.getVectorNumElements());
15034       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15035                                        Mask.getValueType().getSizeInBits());
15036       SDLoc dl(Op);
15037       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15038                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15039                                   DAG.getIntPtrConstant(0, dl));
15040
15041       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15042                          PassThru);
15043     }
15044     case BLEND: {
15045       SDValue Mask = Op.getOperand(3);
15046       EVT VT = Op.getValueType();
15047       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15048                                     VT.getVectorNumElements());
15049       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15050                                        Mask.getValueType().getSizeInBits());
15051       SDLoc dl(Op);
15052       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15053                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15054                                   DAG.getIntPtrConstant(0, dl));
15055       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15056                          Op.getOperand(2));
15057     }
15058     default:
15059       break;
15060     }
15061   }
15062
15063   switch (IntNo) {
15064   default: return SDValue();    // Don't custom lower most intrinsics.
15065
15066   case Intrinsic::x86_avx2_permd:
15067   case Intrinsic::x86_avx2_permps:
15068     // Operands intentionally swapped. Mask is last operand to intrinsic,
15069     // but second operand for node/instruction.
15070     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15071                        Op.getOperand(2), Op.getOperand(1));
15072
15073   case Intrinsic::x86_avx512_mask_valign_q_512:
15074   case Intrinsic::x86_avx512_mask_valign_d_512:
15075     // Vector source operands are swapped.
15076     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15077                                             Op.getValueType(), Op.getOperand(2),
15078                                             Op.getOperand(1),
15079                                             Op.getOperand(3)),
15080                                 Op.getOperand(5), Op.getOperand(4),
15081                                 Subtarget, DAG);
15082
15083   // ptest and testp intrinsics. The intrinsic these come from are designed to
15084   // return an integer value, not just an instruction so lower it to the ptest
15085   // or testp pattern and a setcc for the result.
15086   case Intrinsic::x86_sse41_ptestz:
15087   case Intrinsic::x86_sse41_ptestc:
15088   case Intrinsic::x86_sse41_ptestnzc:
15089   case Intrinsic::x86_avx_ptestz_256:
15090   case Intrinsic::x86_avx_ptestc_256:
15091   case Intrinsic::x86_avx_ptestnzc_256:
15092   case Intrinsic::x86_avx_vtestz_ps:
15093   case Intrinsic::x86_avx_vtestc_ps:
15094   case Intrinsic::x86_avx_vtestnzc_ps:
15095   case Intrinsic::x86_avx_vtestz_pd:
15096   case Intrinsic::x86_avx_vtestc_pd:
15097   case Intrinsic::x86_avx_vtestnzc_pd:
15098   case Intrinsic::x86_avx_vtestz_ps_256:
15099   case Intrinsic::x86_avx_vtestc_ps_256:
15100   case Intrinsic::x86_avx_vtestnzc_ps_256:
15101   case Intrinsic::x86_avx_vtestz_pd_256:
15102   case Intrinsic::x86_avx_vtestc_pd_256:
15103   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15104     bool IsTestPacked = false;
15105     unsigned X86CC;
15106     switch (IntNo) {
15107     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15108     case Intrinsic::x86_avx_vtestz_ps:
15109     case Intrinsic::x86_avx_vtestz_pd:
15110     case Intrinsic::x86_avx_vtestz_ps_256:
15111     case Intrinsic::x86_avx_vtestz_pd_256:
15112       IsTestPacked = true; // Fallthrough
15113     case Intrinsic::x86_sse41_ptestz:
15114     case Intrinsic::x86_avx_ptestz_256:
15115       // ZF = 1
15116       X86CC = X86::COND_E;
15117       break;
15118     case Intrinsic::x86_avx_vtestc_ps:
15119     case Intrinsic::x86_avx_vtestc_pd:
15120     case Intrinsic::x86_avx_vtestc_ps_256:
15121     case Intrinsic::x86_avx_vtestc_pd_256:
15122       IsTestPacked = true; // Fallthrough
15123     case Intrinsic::x86_sse41_ptestc:
15124     case Intrinsic::x86_avx_ptestc_256:
15125       // CF = 1
15126       X86CC = X86::COND_B;
15127       break;
15128     case Intrinsic::x86_avx_vtestnzc_ps:
15129     case Intrinsic::x86_avx_vtestnzc_pd:
15130     case Intrinsic::x86_avx_vtestnzc_ps_256:
15131     case Intrinsic::x86_avx_vtestnzc_pd_256:
15132       IsTestPacked = true; // Fallthrough
15133     case Intrinsic::x86_sse41_ptestnzc:
15134     case Intrinsic::x86_avx_ptestnzc_256:
15135       // ZF and CF = 0
15136       X86CC = X86::COND_A;
15137       break;
15138     }
15139
15140     SDValue LHS = Op.getOperand(1);
15141     SDValue RHS = Op.getOperand(2);
15142     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15143     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15144     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15145     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15146     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15147   }
15148   case Intrinsic::x86_avx512_kortestz_w:
15149   case Intrinsic::x86_avx512_kortestc_w: {
15150     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15151     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15152     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15153     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15154     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15155     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15156     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15157   }
15158
15159   case Intrinsic::x86_sse42_pcmpistria128:
15160   case Intrinsic::x86_sse42_pcmpestria128:
15161   case Intrinsic::x86_sse42_pcmpistric128:
15162   case Intrinsic::x86_sse42_pcmpestric128:
15163   case Intrinsic::x86_sse42_pcmpistrio128:
15164   case Intrinsic::x86_sse42_pcmpestrio128:
15165   case Intrinsic::x86_sse42_pcmpistris128:
15166   case Intrinsic::x86_sse42_pcmpestris128:
15167   case Intrinsic::x86_sse42_pcmpistriz128:
15168   case Intrinsic::x86_sse42_pcmpestriz128: {
15169     unsigned Opcode;
15170     unsigned X86CC;
15171     switch (IntNo) {
15172     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15173     case Intrinsic::x86_sse42_pcmpistria128:
15174       Opcode = X86ISD::PCMPISTRI;
15175       X86CC = X86::COND_A;
15176       break;
15177     case Intrinsic::x86_sse42_pcmpestria128:
15178       Opcode = X86ISD::PCMPESTRI;
15179       X86CC = X86::COND_A;
15180       break;
15181     case Intrinsic::x86_sse42_pcmpistric128:
15182       Opcode = X86ISD::PCMPISTRI;
15183       X86CC = X86::COND_B;
15184       break;
15185     case Intrinsic::x86_sse42_pcmpestric128:
15186       Opcode = X86ISD::PCMPESTRI;
15187       X86CC = X86::COND_B;
15188       break;
15189     case Intrinsic::x86_sse42_pcmpistrio128:
15190       Opcode = X86ISD::PCMPISTRI;
15191       X86CC = X86::COND_O;
15192       break;
15193     case Intrinsic::x86_sse42_pcmpestrio128:
15194       Opcode = X86ISD::PCMPESTRI;
15195       X86CC = X86::COND_O;
15196       break;
15197     case Intrinsic::x86_sse42_pcmpistris128:
15198       Opcode = X86ISD::PCMPISTRI;
15199       X86CC = X86::COND_S;
15200       break;
15201     case Intrinsic::x86_sse42_pcmpestris128:
15202       Opcode = X86ISD::PCMPESTRI;
15203       X86CC = X86::COND_S;
15204       break;
15205     case Intrinsic::x86_sse42_pcmpistriz128:
15206       Opcode = X86ISD::PCMPISTRI;
15207       X86CC = X86::COND_E;
15208       break;
15209     case Intrinsic::x86_sse42_pcmpestriz128:
15210       Opcode = X86ISD::PCMPESTRI;
15211       X86CC = X86::COND_E;
15212       break;
15213     }
15214     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15215     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15216     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15217     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15218                                 DAG.getConstant(X86CC, dl, MVT::i8),
15219                                 SDValue(PCMP.getNode(), 1));
15220     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15221   }
15222
15223   case Intrinsic::x86_sse42_pcmpistri128:
15224   case Intrinsic::x86_sse42_pcmpestri128: {
15225     unsigned Opcode;
15226     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15227       Opcode = X86ISD::PCMPISTRI;
15228     else
15229       Opcode = X86ISD::PCMPESTRI;
15230
15231     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15232     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15233     return DAG.getNode(Opcode, dl, VTs, NewOps);
15234   }
15235   }
15236 }
15237
15238 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15239                               SDValue Src, SDValue Mask, SDValue Base,
15240                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15241                               const X86Subtarget * Subtarget) {
15242   SDLoc dl(Op);
15243   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15244   assert(C && "Invalid scale type");
15245   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15246   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15247                              Index.getSimpleValueType().getVectorNumElements());
15248   SDValue MaskInReg;
15249   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15250   if (MaskC)
15251     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15252   else
15253     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15254   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15255   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15256   SDValue Segment = DAG.getRegister(0, MVT::i32);
15257   if (Src.getOpcode() == ISD::UNDEF)
15258     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15259   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15260   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15261   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15262   return DAG.getMergeValues(RetOps, dl);
15263 }
15264
15265 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15266                                SDValue Src, SDValue Mask, SDValue Base,
15267                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15268   SDLoc dl(Op);
15269   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15270   assert(C && "Invalid scale type");
15271   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15272   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15273   SDValue Segment = DAG.getRegister(0, MVT::i32);
15274   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15275                              Index.getSimpleValueType().getVectorNumElements());
15276   SDValue MaskInReg;
15277   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15278   if (MaskC)
15279     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15280   else
15281     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15282   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15283   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15284   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15285   return SDValue(Res, 1);
15286 }
15287
15288 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15289                                SDValue Mask, SDValue Base, SDValue Index,
15290                                SDValue ScaleOp, SDValue Chain) {
15291   SDLoc dl(Op);
15292   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15293   assert(C && "Invalid scale type");
15294   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15295   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15296   SDValue Segment = DAG.getRegister(0, MVT::i32);
15297   EVT MaskVT =
15298     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15299   SDValue MaskInReg;
15300   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15301   if (MaskC)
15302     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15303   else
15304     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15305   //SDVTList VTs = DAG.getVTList(MVT::Other);
15306   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15307   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15308   return SDValue(Res, 0);
15309 }
15310
15311 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15312 // read performance monitor counters (x86_rdpmc).
15313 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15314                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15315                               SmallVectorImpl<SDValue> &Results) {
15316   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15317   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15318   SDValue LO, HI;
15319
15320   // The ECX register is used to select the index of the performance counter
15321   // to read.
15322   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15323                                    N->getOperand(2));
15324   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15325
15326   // Reads the content of a 64-bit performance counter and returns it in the
15327   // registers EDX:EAX.
15328   if (Subtarget->is64Bit()) {
15329     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15330     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15331                             LO.getValue(2));
15332   } else {
15333     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15334     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15335                             LO.getValue(2));
15336   }
15337   Chain = HI.getValue(1);
15338
15339   if (Subtarget->is64Bit()) {
15340     // The EAX register is loaded with the low-order 32 bits. The EDX register
15341     // is loaded with the supported high-order bits of the counter.
15342     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15343                               DAG.getConstant(32, DL, MVT::i8));
15344     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15345     Results.push_back(Chain);
15346     return;
15347   }
15348
15349   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15350   SDValue Ops[] = { LO, HI };
15351   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15352   Results.push_back(Pair);
15353   Results.push_back(Chain);
15354 }
15355
15356 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15357 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15358 // also used to custom lower READCYCLECOUNTER nodes.
15359 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15360                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15361                               SmallVectorImpl<SDValue> &Results) {
15362   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15363   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15364   SDValue LO, HI;
15365
15366   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15367   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15368   // and the EAX register is loaded with the low-order 32 bits.
15369   if (Subtarget->is64Bit()) {
15370     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15371     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15372                             LO.getValue(2));
15373   } else {
15374     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15375     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15376                             LO.getValue(2));
15377   }
15378   SDValue Chain = HI.getValue(1);
15379
15380   if (Opcode == X86ISD::RDTSCP_DAG) {
15381     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15382
15383     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15384     // the ECX register. Add 'ecx' explicitly to the chain.
15385     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15386                                      HI.getValue(2));
15387     // Explicitly store the content of ECX at the location passed in input
15388     // to the 'rdtscp' intrinsic.
15389     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15390                          MachinePointerInfo(), false, false, 0);
15391   }
15392
15393   if (Subtarget->is64Bit()) {
15394     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15395     // the EAX register is loaded with the low-order 32 bits.
15396     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15397                               DAG.getConstant(32, DL, MVT::i8));
15398     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15399     Results.push_back(Chain);
15400     return;
15401   }
15402
15403   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15404   SDValue Ops[] = { LO, HI };
15405   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15406   Results.push_back(Pair);
15407   Results.push_back(Chain);
15408 }
15409
15410 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15411                                      SelectionDAG &DAG) {
15412   SmallVector<SDValue, 2> Results;
15413   SDLoc DL(Op);
15414   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15415                           Results);
15416   return DAG.getMergeValues(Results, DL);
15417 }
15418
15419
15420 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15421                                       SelectionDAG &DAG) {
15422   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15423
15424   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15425   if (!IntrData)
15426     return SDValue();
15427
15428   SDLoc dl(Op);
15429   switch(IntrData->Type) {
15430   default:
15431     llvm_unreachable("Unknown Intrinsic Type");
15432     break;
15433   case RDSEED:
15434   case RDRAND: {
15435     // Emit the node with the right value type.
15436     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15437     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15438
15439     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15440     // Otherwise return the value from Rand, which is always 0, casted to i32.
15441     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15442                       DAG.getConstant(1, dl, Op->getValueType(1)),
15443                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15444                       SDValue(Result.getNode(), 1) };
15445     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15446                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15447                                   Ops);
15448
15449     // Return { result, isValid, chain }.
15450     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15451                        SDValue(Result.getNode(), 2));
15452   }
15453   case GATHER: {
15454   //gather(v1, mask, index, base, scale);
15455     SDValue Chain = Op.getOperand(0);
15456     SDValue Src   = Op.getOperand(2);
15457     SDValue Base  = Op.getOperand(3);
15458     SDValue Index = Op.getOperand(4);
15459     SDValue Mask  = Op.getOperand(5);
15460     SDValue Scale = Op.getOperand(6);
15461     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15462                          Chain, Subtarget);
15463   }
15464   case SCATTER: {
15465   //scatter(base, mask, index, v1, scale);
15466     SDValue Chain = Op.getOperand(0);
15467     SDValue Base  = Op.getOperand(2);
15468     SDValue Mask  = Op.getOperand(3);
15469     SDValue Index = Op.getOperand(4);
15470     SDValue Src   = Op.getOperand(5);
15471     SDValue Scale = Op.getOperand(6);
15472     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15473                           Scale, Chain);
15474   }
15475   case PREFETCH: {
15476     SDValue Hint = Op.getOperand(6);
15477     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15478     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15479     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15480     SDValue Chain = Op.getOperand(0);
15481     SDValue Mask  = Op.getOperand(2);
15482     SDValue Index = Op.getOperand(3);
15483     SDValue Base  = Op.getOperand(4);
15484     SDValue Scale = Op.getOperand(5);
15485     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15486   }
15487   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15488   case RDTSC: {
15489     SmallVector<SDValue, 2> Results;
15490     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15491                             Results);
15492     return DAG.getMergeValues(Results, dl);
15493   }
15494   // Read Performance Monitoring Counters.
15495   case RDPMC: {
15496     SmallVector<SDValue, 2> Results;
15497     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15498     return DAG.getMergeValues(Results, dl);
15499   }
15500   // XTEST intrinsics.
15501   case XTEST: {
15502     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15503     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15504     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15505                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15506                                 InTrans);
15507     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15508     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15509                        Ret, SDValue(InTrans.getNode(), 1));
15510   }
15511   // ADC/ADCX/SBB
15512   case ADX: {
15513     SmallVector<SDValue, 2> Results;
15514     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15515     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15516     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15517                                 DAG.getConstant(-1, dl, MVT::i8));
15518     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15519                               Op.getOperand(4), GenCF.getValue(1));
15520     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15521                                  Op.getOperand(5), MachinePointerInfo(),
15522                                  false, false, 0);
15523     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15524                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15525                                 Res.getValue(1));
15526     Results.push_back(SetCC);
15527     Results.push_back(Store);
15528     return DAG.getMergeValues(Results, dl);
15529   }
15530   case COMPRESS_TO_MEM: {
15531     SDLoc dl(Op);
15532     SDValue Mask = Op.getOperand(4);
15533     SDValue DataToCompress = Op.getOperand(3);
15534     SDValue Addr = Op.getOperand(2);
15535     SDValue Chain = Op.getOperand(0);
15536
15537     if (isAllOnes(Mask)) // return just a store
15538       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15539                           MachinePointerInfo(), false, false, 0);
15540
15541     EVT VT = DataToCompress.getValueType();
15542     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15543                                   VT.getVectorNumElements());
15544     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15545                                      Mask.getValueType().getSizeInBits());
15546     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15547                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15548                                 DAG.getIntPtrConstant(0, dl));
15549
15550     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15551                                       DataToCompress, DAG.getUNDEF(VT));
15552     return DAG.getStore(Chain, dl, Compressed, Addr,
15553                         MachinePointerInfo(), false, false, 0);
15554   }
15555   case EXPAND_FROM_MEM: {
15556     SDLoc dl(Op);
15557     SDValue Mask = Op.getOperand(4);
15558     SDValue PathThru = Op.getOperand(3);
15559     SDValue Addr = Op.getOperand(2);
15560     SDValue Chain = Op.getOperand(0);
15561     EVT VT = Op.getValueType();
15562
15563     if (isAllOnes(Mask)) // return just a load
15564       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15565                          false, 0);
15566     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15567                                   VT.getVectorNumElements());
15568     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15569                                      Mask.getValueType().getSizeInBits());
15570     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15571                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15572                                 DAG.getIntPtrConstant(0, dl));
15573
15574     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15575                                    false, false, false, 0);
15576
15577     SDValue Results[] = {
15578         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15579         Chain};
15580     return DAG.getMergeValues(Results, dl);
15581   }
15582   }
15583 }
15584
15585 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15586                                            SelectionDAG &DAG) const {
15587   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15588   MFI->setReturnAddressIsTaken(true);
15589
15590   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15591     return SDValue();
15592
15593   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15594   SDLoc dl(Op);
15595   EVT PtrVT = getPointerTy();
15596
15597   if (Depth > 0) {
15598     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15599     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15600     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15601     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15602                        DAG.getNode(ISD::ADD, dl, PtrVT,
15603                                    FrameAddr, Offset),
15604                        MachinePointerInfo(), false, false, false, 0);
15605   }
15606
15607   // Just load the return address.
15608   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15609   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15610                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15611 }
15612
15613 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15614   MachineFunction &MF = DAG.getMachineFunction();
15615   MachineFrameInfo *MFI = MF.getFrameInfo();
15616   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15617   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15618   EVT VT = Op.getValueType();
15619
15620   MFI->setFrameAddressIsTaken(true);
15621
15622   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15623     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15624     // is not possible to crawl up the stack without looking at the unwind codes
15625     // simultaneously.
15626     int FrameAddrIndex = FuncInfo->getFAIndex();
15627     if (!FrameAddrIndex) {
15628       // Set up a frame object for the return address.
15629       unsigned SlotSize = RegInfo->getSlotSize();
15630       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15631           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15632       FuncInfo->setFAIndex(FrameAddrIndex);
15633     }
15634     return DAG.getFrameIndex(FrameAddrIndex, VT);
15635   }
15636
15637   unsigned FrameReg =
15638       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15639   SDLoc dl(Op);  // FIXME probably not meaningful
15640   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15641   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15642           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15643          "Invalid Frame Register!");
15644   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15645   while (Depth--)
15646     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15647                             MachinePointerInfo(),
15648                             false, false, false, 0);
15649   return FrameAddr;
15650 }
15651
15652 // FIXME? Maybe this could be a TableGen attribute on some registers and
15653 // this table could be generated automatically from RegInfo.
15654 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15655                                               EVT VT) const {
15656   unsigned Reg = StringSwitch<unsigned>(RegName)
15657                        .Case("esp", X86::ESP)
15658                        .Case("rsp", X86::RSP)
15659                        .Default(0);
15660   if (Reg)
15661     return Reg;
15662   report_fatal_error("Invalid register name global variable");
15663 }
15664
15665 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15666                                                      SelectionDAG &DAG) const {
15667   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15668   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15669 }
15670
15671 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15672   SDValue Chain     = Op.getOperand(0);
15673   SDValue Offset    = Op.getOperand(1);
15674   SDValue Handler   = Op.getOperand(2);
15675   SDLoc dl      (Op);
15676
15677   EVT PtrVT = getPointerTy();
15678   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15679   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15680   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15681           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15682          "Invalid Frame Register!");
15683   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15684   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15685
15686   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15687                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15688                                                        dl));
15689   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15690   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15691                        false, false, 0);
15692   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15693
15694   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15695                      DAG.getRegister(StoreAddrReg, PtrVT));
15696 }
15697
15698 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15699                                                SelectionDAG &DAG) const {
15700   SDLoc DL(Op);
15701   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15702                      DAG.getVTList(MVT::i32, MVT::Other),
15703                      Op.getOperand(0), Op.getOperand(1));
15704 }
15705
15706 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15707                                                 SelectionDAG &DAG) const {
15708   SDLoc DL(Op);
15709   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15710                      Op.getOperand(0), Op.getOperand(1));
15711 }
15712
15713 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15714   return Op.getOperand(0);
15715 }
15716
15717 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15718                                                 SelectionDAG &DAG) const {
15719   SDValue Root = Op.getOperand(0);
15720   SDValue Trmp = Op.getOperand(1); // trampoline
15721   SDValue FPtr = Op.getOperand(2); // nested function
15722   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15723   SDLoc dl (Op);
15724
15725   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15726   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15727
15728   if (Subtarget->is64Bit()) {
15729     SDValue OutChains[6];
15730
15731     // Large code-model.
15732     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15733     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15734
15735     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15736     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15737
15738     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15739
15740     // Load the pointer to the nested function into R11.
15741     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15742     SDValue Addr = Trmp;
15743     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15744                                 Addr, MachinePointerInfo(TrmpAddr),
15745                                 false, false, 0);
15746
15747     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15748                        DAG.getConstant(2, dl, MVT::i64));
15749     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15750                                 MachinePointerInfo(TrmpAddr, 2),
15751                                 false, false, 2);
15752
15753     // Load the 'nest' parameter value into R10.
15754     // R10 is specified in X86CallingConv.td
15755     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15756     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15757                        DAG.getConstant(10, dl, MVT::i64));
15758     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15759                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15760                                 false, false, 0);
15761
15762     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15763                        DAG.getConstant(12, dl, MVT::i64));
15764     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15765                                 MachinePointerInfo(TrmpAddr, 12),
15766                                 false, false, 2);
15767
15768     // Jump to the nested function.
15769     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15770     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15771                        DAG.getConstant(20, dl, MVT::i64));
15772     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15773                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15774                                 false, false, 0);
15775
15776     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15777     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15778                        DAG.getConstant(22, dl, MVT::i64));
15779     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15780                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15781                                 false, false, 0);
15782
15783     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15784   } else {
15785     const Function *Func =
15786       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15787     CallingConv::ID CC = Func->getCallingConv();
15788     unsigned NestReg;
15789
15790     switch (CC) {
15791     default:
15792       llvm_unreachable("Unsupported calling convention");
15793     case CallingConv::C:
15794     case CallingConv::X86_StdCall: {
15795       // Pass 'nest' parameter in ECX.
15796       // Must be kept in sync with X86CallingConv.td
15797       NestReg = X86::ECX;
15798
15799       // Check that ECX wasn't needed by an 'inreg' parameter.
15800       FunctionType *FTy = Func->getFunctionType();
15801       const AttributeSet &Attrs = Func->getAttributes();
15802
15803       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15804         unsigned InRegCount = 0;
15805         unsigned Idx = 1;
15806
15807         for (FunctionType::param_iterator I = FTy->param_begin(),
15808              E = FTy->param_end(); I != E; ++I, ++Idx)
15809           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15810             // FIXME: should only count parameters that are lowered to integers.
15811             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15812
15813         if (InRegCount > 2) {
15814           report_fatal_error("Nest register in use - reduce number of inreg"
15815                              " parameters!");
15816         }
15817       }
15818       break;
15819     }
15820     case CallingConv::X86_FastCall:
15821     case CallingConv::X86_ThisCall:
15822     case CallingConv::Fast:
15823       // Pass 'nest' parameter in EAX.
15824       // Must be kept in sync with X86CallingConv.td
15825       NestReg = X86::EAX;
15826       break;
15827     }
15828
15829     SDValue OutChains[4];
15830     SDValue Addr, Disp;
15831
15832     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15833                        DAG.getConstant(10, dl, MVT::i32));
15834     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15835
15836     // This is storing the opcode for MOV32ri.
15837     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15838     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15839     OutChains[0] = DAG.getStore(Root, dl,
15840                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15841                                 Trmp, MachinePointerInfo(TrmpAddr),
15842                                 false, false, 0);
15843
15844     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15845                        DAG.getConstant(1, dl, MVT::i32));
15846     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15847                                 MachinePointerInfo(TrmpAddr, 1),
15848                                 false, false, 1);
15849
15850     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15851     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15852                        DAG.getConstant(5, dl, MVT::i32));
15853     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15854                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15855                                 false, false, 1);
15856
15857     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15858                        DAG.getConstant(6, dl, MVT::i32));
15859     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15860                                 MachinePointerInfo(TrmpAddr, 6),
15861                                 false, false, 1);
15862
15863     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15864   }
15865 }
15866
15867 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15868                                             SelectionDAG &DAG) const {
15869   /*
15870    The rounding mode is in bits 11:10 of FPSR, and has the following
15871    settings:
15872      00 Round to nearest
15873      01 Round to -inf
15874      10 Round to +inf
15875      11 Round to 0
15876
15877   FLT_ROUNDS, on the other hand, expects the following:
15878     -1 Undefined
15879      0 Round to 0
15880      1 Round to nearest
15881      2 Round to +inf
15882      3 Round to -inf
15883
15884   To perform the conversion, we do:
15885     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15886   */
15887
15888   MachineFunction &MF = DAG.getMachineFunction();
15889   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15890   unsigned StackAlignment = TFI.getStackAlignment();
15891   MVT VT = Op.getSimpleValueType();
15892   SDLoc DL(Op);
15893
15894   // Save FP Control Word to stack slot
15895   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15896   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15897
15898   MachineMemOperand *MMO =
15899    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15900                            MachineMemOperand::MOStore, 2, 2);
15901
15902   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15903   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15904                                           DAG.getVTList(MVT::Other),
15905                                           Ops, MVT::i16, MMO);
15906
15907   // Load FP Control Word from stack slot
15908   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15909                             MachinePointerInfo(), false, false, false, 0);
15910
15911   // Transform as necessary
15912   SDValue CWD1 =
15913     DAG.getNode(ISD::SRL, DL, MVT::i16,
15914                 DAG.getNode(ISD::AND, DL, MVT::i16,
15915                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15916                 DAG.getConstant(11, DL, MVT::i8));
15917   SDValue CWD2 =
15918     DAG.getNode(ISD::SRL, DL, MVT::i16,
15919                 DAG.getNode(ISD::AND, DL, MVT::i16,
15920                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15921                 DAG.getConstant(9, DL, MVT::i8));
15922
15923   SDValue RetVal =
15924     DAG.getNode(ISD::AND, DL, MVT::i16,
15925                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15926                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15927                             DAG.getConstant(1, DL, MVT::i16)),
15928                 DAG.getConstant(3, DL, MVT::i16));
15929
15930   return DAG.getNode((VT.getSizeInBits() < 16 ?
15931                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15932 }
15933
15934 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15935   MVT VT = Op.getSimpleValueType();
15936   EVT OpVT = VT;
15937   unsigned NumBits = VT.getSizeInBits();
15938   SDLoc dl(Op);
15939
15940   Op = Op.getOperand(0);
15941   if (VT == MVT::i8) {
15942     // Zero extend to i32 since there is not an i8 bsr.
15943     OpVT = MVT::i32;
15944     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15945   }
15946
15947   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15948   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15949   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15950
15951   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15952   SDValue Ops[] = {
15953     Op,
15954     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15955     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15956     Op.getValue(1)
15957   };
15958   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15959
15960   // Finally xor with NumBits-1.
15961   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15962                    DAG.getConstant(NumBits - 1, dl, OpVT));
15963
15964   if (VT == MVT::i8)
15965     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15966   return Op;
15967 }
15968
15969 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15970   MVT VT = Op.getSimpleValueType();
15971   EVT OpVT = VT;
15972   unsigned NumBits = VT.getSizeInBits();
15973   SDLoc dl(Op);
15974
15975   Op = Op.getOperand(0);
15976   if (VT == MVT::i8) {
15977     // Zero extend to i32 since there is not an i8 bsr.
15978     OpVT = MVT::i32;
15979     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15980   }
15981
15982   // Issue a bsr (scan bits in reverse).
15983   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15984   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15985
15986   // And xor with NumBits-1.
15987   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15988                    DAG.getConstant(NumBits - 1, dl, OpVT));
15989
15990   if (VT == MVT::i8)
15991     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15992   return Op;
15993 }
15994
15995 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15996   MVT VT = Op.getSimpleValueType();
15997   unsigned NumBits = VT.getSizeInBits();
15998   SDLoc dl(Op);
15999   Op = Op.getOperand(0);
16000
16001   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16002   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16003   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16004
16005   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16006   SDValue Ops[] = {
16007     Op,
16008     DAG.getConstant(NumBits, dl, VT),
16009     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16010     Op.getValue(1)
16011   };
16012   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16013 }
16014
16015 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16016 // ones, and then concatenate the result back.
16017 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16018   MVT VT = Op.getSimpleValueType();
16019
16020   assert(VT.is256BitVector() && VT.isInteger() &&
16021          "Unsupported value type for operation");
16022
16023   unsigned NumElems = VT.getVectorNumElements();
16024   SDLoc dl(Op);
16025
16026   // Extract the LHS vectors
16027   SDValue LHS = Op.getOperand(0);
16028   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16029   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16030
16031   // Extract the RHS vectors
16032   SDValue RHS = Op.getOperand(1);
16033   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16034   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16035
16036   MVT EltVT = VT.getVectorElementType();
16037   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16038
16039   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16040                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16041                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16042 }
16043
16044 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16045   assert(Op.getSimpleValueType().is256BitVector() &&
16046          Op.getSimpleValueType().isInteger() &&
16047          "Only handle AVX 256-bit vector integer operation");
16048   return Lower256IntArith(Op, DAG);
16049 }
16050
16051 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16052   assert(Op.getSimpleValueType().is256BitVector() &&
16053          Op.getSimpleValueType().isInteger() &&
16054          "Only handle AVX 256-bit vector integer operation");
16055   return Lower256IntArith(Op, DAG);
16056 }
16057
16058 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16059                         SelectionDAG &DAG) {
16060   SDLoc dl(Op);
16061   MVT VT = Op.getSimpleValueType();
16062
16063   // Decompose 256-bit ops into smaller 128-bit ops.
16064   if (VT.is256BitVector() && !Subtarget->hasInt256())
16065     return Lower256IntArith(Op, DAG);
16066
16067   SDValue A = Op.getOperand(0);
16068   SDValue B = Op.getOperand(1);
16069
16070   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16071   // pairs, multiply and truncate.
16072   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16073     if (Subtarget->hasInt256()) {
16074       if (VT == MVT::v32i8) {
16075         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16076         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16077         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16078         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16079         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16080         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16081         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16082         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16083                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16084                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16085       }
16086
16087       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16088       return DAG.getNode(
16089           ISD::TRUNCATE, dl, VT,
16090           DAG.getNode(ISD::MUL, dl, ExVT,
16091                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16092                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16093     }
16094
16095     assert(VT == MVT::v16i8 &&
16096            "Pre-AVX2 support only supports v16i8 multiplication");
16097     MVT ExVT = MVT::v8i16;
16098
16099     // Extract the lo parts and sign extend to i16
16100     SDValue ALo, BLo;
16101     if (Subtarget->hasSSE41()) {
16102       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16103       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16104     } else {
16105       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16106                               -1, 4, -1, 5, -1, 6, -1, 7};
16107       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16108       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16109       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16110       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16111       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16112       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16113     }
16114
16115     // Extract the hi parts and sign extend to i16
16116     SDValue AHi, BHi;
16117     if (Subtarget->hasSSE41()) {
16118       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16119                               -1, -1, -1, -1, -1, -1, -1, -1};
16120       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16121       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16122       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16123       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16124     } else {
16125       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16126                               -1, 12, -1, 13, -1, 14, -1, 15};
16127       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16128       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16129       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16130       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16131       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16132       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16133     }
16134
16135     // Multiply, mask the lower 8bits of the lo/hi results and pack
16136     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16137     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16138     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16139     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16140     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16141   }
16142
16143   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16144   if (VT == MVT::v4i32) {
16145     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16146            "Should not custom lower when pmuldq is available!");
16147
16148     // Extract the odd parts.
16149     static const int UnpackMask[] = { 1, -1, 3, -1 };
16150     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16151     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16152
16153     // Multiply the even parts.
16154     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16155     // Now multiply odd parts.
16156     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16157
16158     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16159     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16160
16161     // Merge the two vectors back together with a shuffle. This expands into 2
16162     // shuffles.
16163     static const int ShufMask[] = { 0, 4, 2, 6 };
16164     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16165   }
16166
16167   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16168          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16169
16170   //  Ahi = psrlqi(a, 32);
16171   //  Bhi = psrlqi(b, 32);
16172   //
16173   //  AloBlo = pmuludq(a, b);
16174   //  AloBhi = pmuludq(a, Bhi);
16175   //  AhiBlo = pmuludq(Ahi, b);
16176
16177   //  AloBhi = psllqi(AloBhi, 32);
16178   //  AhiBlo = psllqi(AhiBlo, 32);
16179   //  return AloBlo + AloBhi + AhiBlo;
16180
16181   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16182   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16183
16184   // Bit cast to 32-bit vectors for MULUDQ
16185   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16186                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16187   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16188   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16189   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16190   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16191
16192   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16193   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16194   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16195
16196   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16197   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16198
16199   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16200   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16201 }
16202
16203 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16204   assert(Subtarget->isTargetWin64() && "Unexpected target");
16205   EVT VT = Op.getValueType();
16206   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16207          "Unexpected return type for lowering");
16208
16209   RTLIB::Libcall LC;
16210   bool isSigned;
16211   switch (Op->getOpcode()) {
16212   default: llvm_unreachable("Unexpected request for libcall!");
16213   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16214   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16215   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16216   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16217   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16218   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16219   }
16220
16221   SDLoc dl(Op);
16222   SDValue InChain = DAG.getEntryNode();
16223
16224   TargetLowering::ArgListTy Args;
16225   TargetLowering::ArgListEntry Entry;
16226   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16227     EVT ArgVT = Op->getOperand(i).getValueType();
16228     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16229            "Unexpected argument type for lowering");
16230     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16231     Entry.Node = StackPtr;
16232     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16233                            false, false, 16);
16234     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16235     Entry.Ty = PointerType::get(ArgTy,0);
16236     Entry.isSExt = false;
16237     Entry.isZExt = false;
16238     Args.push_back(Entry);
16239   }
16240
16241   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16242                                          getPointerTy());
16243
16244   TargetLowering::CallLoweringInfo CLI(DAG);
16245   CLI.setDebugLoc(dl).setChain(InChain)
16246     .setCallee(getLibcallCallingConv(LC),
16247                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16248                Callee, std::move(Args), 0)
16249     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16250
16251   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16252   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16253 }
16254
16255 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16256                              SelectionDAG &DAG) {
16257   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16258   EVT VT = Op0.getValueType();
16259   SDLoc dl(Op);
16260
16261   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16262          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16263
16264   // PMULxD operations multiply each even value (starting at 0) of LHS with
16265   // the related value of RHS and produce a widen result.
16266   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16267   // => <2 x i64> <ae|cg>
16268   //
16269   // In other word, to have all the results, we need to perform two PMULxD:
16270   // 1. one with the even values.
16271   // 2. one with the odd values.
16272   // To achieve #2, with need to place the odd values at an even position.
16273   //
16274   // Place the odd value at an even position (basically, shift all values 1
16275   // step to the left):
16276   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16277   // <a|b|c|d> => <b|undef|d|undef>
16278   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16279   // <e|f|g|h> => <f|undef|h|undef>
16280   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16281
16282   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16283   // ints.
16284   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16285   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16286   unsigned Opcode =
16287       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16288   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16289   // => <2 x i64> <ae|cg>
16290   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16291                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16292   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16293   // => <2 x i64> <bf|dh>
16294   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16295                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16296
16297   // Shuffle it back into the right order.
16298   SDValue Highs, Lows;
16299   if (VT == MVT::v8i32) {
16300     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16301     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16302     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16303     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16304   } else {
16305     const int HighMask[] = {1, 5, 3, 7};
16306     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16307     const int LowMask[] = {0, 4, 2, 6};
16308     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16309   }
16310
16311   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16312   // unsigned multiply.
16313   if (IsSigned && !Subtarget->hasSSE41()) {
16314     SDValue ShAmt =
16315         DAG.getConstant(31, dl,
16316                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16317     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16318                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16319     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16320                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16321
16322     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16323     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16324   }
16325
16326   // The first result of MUL_LOHI is actually the low value, followed by the
16327   // high value.
16328   SDValue Ops[] = {Lows, Highs};
16329   return DAG.getMergeValues(Ops, dl);
16330 }
16331
16332 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16333                                          const X86Subtarget *Subtarget) {
16334   MVT VT = Op.getSimpleValueType();
16335   SDLoc dl(Op);
16336   SDValue R = Op.getOperand(0);
16337   SDValue Amt = Op.getOperand(1);
16338
16339   // Optimize shl/srl/sra with constant shift amount.
16340   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16341     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16342       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16343
16344       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16345           (Subtarget->hasInt256() &&
16346            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16347           (Subtarget->hasAVX512() &&
16348            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16349         if (Op.getOpcode() == ISD::SHL)
16350           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16351                                             DAG);
16352         if (Op.getOpcode() == ISD::SRL)
16353           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16354                                             DAG);
16355         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16356           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16357                                             DAG);
16358       }
16359
16360       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16361         unsigned NumElts = VT.getVectorNumElements();
16362         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16363
16364         if (Op.getOpcode() == ISD::SHL) {
16365           // Make a large shift.
16366           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16367                                                    R, ShiftAmt, DAG);
16368           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16369           // Zero out the rightmost bits.
16370           SmallVector<SDValue, 32> V(
16371               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16372           return DAG.getNode(ISD::AND, dl, VT, SHL,
16373                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16374         }
16375         if (Op.getOpcode() == ISD::SRL) {
16376           // Make a large shift.
16377           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16378                                                    R, ShiftAmt, DAG);
16379           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16380           // Zero out the leftmost bits.
16381           SmallVector<SDValue, 32> V(
16382               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16383           return DAG.getNode(ISD::AND, dl, VT, SRL,
16384                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16385         }
16386         if (Op.getOpcode() == ISD::SRA) {
16387           if (ShiftAmt == 7) {
16388             // R s>> 7  ===  R s< 0
16389             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16390             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16391           }
16392
16393           // R s>> a === ((R u>> a) ^ m) - m
16394           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16395           SmallVector<SDValue, 32> V(NumElts,
16396                                      DAG.getConstant(128 >> ShiftAmt, dl,
16397                                                      MVT::i8));
16398           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16399           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16400           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16401           return Res;
16402         }
16403         llvm_unreachable("Unknown shift opcode.");
16404       }
16405     }
16406   }
16407
16408   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16409   if (!Subtarget->is64Bit() &&
16410       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16411       Amt.getOpcode() == ISD::BITCAST &&
16412       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16413     Amt = Amt.getOperand(0);
16414     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16415                      VT.getVectorNumElements();
16416     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16417     uint64_t ShiftAmt = 0;
16418     for (unsigned i = 0; i != Ratio; ++i) {
16419       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16420       if (!C)
16421         return SDValue();
16422       // 6 == Log2(64)
16423       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16424     }
16425     // Check remaining shift amounts.
16426     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16427       uint64_t ShAmt = 0;
16428       for (unsigned j = 0; j != Ratio; ++j) {
16429         ConstantSDNode *C =
16430           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16431         if (!C)
16432           return SDValue();
16433         // 6 == Log2(64)
16434         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16435       }
16436       if (ShAmt != ShiftAmt)
16437         return SDValue();
16438     }
16439     switch (Op.getOpcode()) {
16440     default:
16441       llvm_unreachable("Unknown shift opcode!");
16442     case ISD::SHL:
16443       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16444                                         DAG);
16445     case ISD::SRL:
16446       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16447                                         DAG);
16448     case ISD::SRA:
16449       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16450                                         DAG);
16451     }
16452   }
16453
16454   return SDValue();
16455 }
16456
16457 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16458                                         const X86Subtarget* Subtarget) {
16459   MVT VT = Op.getSimpleValueType();
16460   SDLoc dl(Op);
16461   SDValue R = Op.getOperand(0);
16462   SDValue Amt = Op.getOperand(1);
16463
16464   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16465       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16466       (Subtarget->hasInt256() &&
16467        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16468         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16469        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16470     SDValue BaseShAmt;
16471     EVT EltVT = VT.getVectorElementType();
16472
16473     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16474       // Check if this build_vector node is doing a splat.
16475       // If so, then set BaseShAmt equal to the splat value.
16476       BaseShAmt = BV->getSplatValue();
16477       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16478         BaseShAmt = SDValue();
16479     } else {
16480       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16481         Amt = Amt.getOperand(0);
16482
16483       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16484       if (SVN && SVN->isSplat()) {
16485         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16486         SDValue InVec = Amt.getOperand(0);
16487         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16488           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16489                  "Unexpected shuffle index found!");
16490           BaseShAmt = InVec.getOperand(SplatIdx);
16491         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16492            if (ConstantSDNode *C =
16493                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16494              if (C->getZExtValue() == SplatIdx)
16495                BaseShAmt = InVec.getOperand(1);
16496            }
16497         }
16498
16499         if (!BaseShAmt)
16500           // Avoid introducing an extract element from a shuffle.
16501           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16502                                   DAG.getIntPtrConstant(SplatIdx, dl));
16503       }
16504     }
16505
16506     if (BaseShAmt.getNode()) {
16507       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16508       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16509         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16510       else if (EltVT.bitsLT(MVT::i32))
16511         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16512
16513       switch (Op.getOpcode()) {
16514       default:
16515         llvm_unreachable("Unknown shift opcode!");
16516       case ISD::SHL:
16517         switch (VT.SimpleTy) {
16518         default: return SDValue();
16519         case MVT::v2i64:
16520         case MVT::v4i32:
16521         case MVT::v8i16:
16522         case MVT::v4i64:
16523         case MVT::v8i32:
16524         case MVT::v16i16:
16525         case MVT::v16i32:
16526         case MVT::v8i64:
16527           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16528         }
16529       case ISD::SRA:
16530         switch (VT.SimpleTy) {
16531         default: return SDValue();
16532         case MVT::v4i32:
16533         case MVT::v8i16:
16534         case MVT::v8i32:
16535         case MVT::v16i16:
16536         case MVT::v16i32:
16537         case MVT::v8i64:
16538           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16539         }
16540       case ISD::SRL:
16541         switch (VT.SimpleTy) {
16542         default: return SDValue();
16543         case MVT::v2i64:
16544         case MVT::v4i32:
16545         case MVT::v8i16:
16546         case MVT::v4i64:
16547         case MVT::v8i32:
16548         case MVT::v16i16:
16549         case MVT::v16i32:
16550         case MVT::v8i64:
16551           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16552         }
16553       }
16554     }
16555   }
16556
16557   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16558   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16559       Amt.getOpcode() == ISD::BITCAST &&
16560       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16561     Amt = Amt.getOperand(0);
16562     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16563                      VT.getVectorNumElements();
16564     std::vector<SDValue> Vals(Ratio);
16565     for (unsigned i = 0; i != Ratio; ++i)
16566       Vals[i] = Amt.getOperand(i);
16567     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16568       for (unsigned j = 0; j != Ratio; ++j)
16569         if (Vals[j] != Amt.getOperand(i + j))
16570           return SDValue();
16571     }
16572     switch (Op.getOpcode()) {
16573     default:
16574       llvm_unreachable("Unknown shift opcode!");
16575     case ISD::SHL:
16576       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16577     case ISD::SRL:
16578       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16579     case ISD::SRA:
16580       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16581     }
16582   }
16583
16584   return SDValue();
16585 }
16586
16587 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16588                           SelectionDAG &DAG) {
16589   MVT VT = Op.getSimpleValueType();
16590   SDLoc dl(Op);
16591   SDValue R = Op.getOperand(0);
16592   SDValue Amt = Op.getOperand(1);
16593
16594   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16595   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16596
16597   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16598     return V;
16599
16600   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16601       return V;
16602
16603   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16604     return Op;
16605
16606   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16607   if (Subtarget->hasInt256()) {
16608     if (Op.getOpcode() == ISD::SRL &&
16609         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16610          VT == MVT::v4i64 || VT == MVT::v8i32))
16611       return Op;
16612     if (Op.getOpcode() == ISD::SHL &&
16613         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16614          VT == MVT::v4i64 || VT == MVT::v8i32))
16615       return Op;
16616     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16617       return Op;
16618   }
16619
16620   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16621   // shifts per-lane and then shuffle the partial results back together.
16622   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16623     // Splat the shift amounts so the scalar shifts above will catch it.
16624     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16625     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16626     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16627     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16628     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16629   }
16630
16631   // If possible, lower this packed shift into a vector multiply instead of
16632   // expanding it into a sequence of scalar shifts.
16633   // Do this only if the vector shift count is a constant build_vector.
16634   if (Op.getOpcode() == ISD::SHL &&
16635       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16636        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16637       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16638     SmallVector<SDValue, 8> Elts;
16639     EVT SVT = VT.getScalarType();
16640     unsigned SVTBits = SVT.getSizeInBits();
16641     const APInt &One = APInt(SVTBits, 1);
16642     unsigned NumElems = VT.getVectorNumElements();
16643
16644     for (unsigned i=0; i !=NumElems; ++i) {
16645       SDValue Op = Amt->getOperand(i);
16646       if (Op->getOpcode() == ISD::UNDEF) {
16647         Elts.push_back(Op);
16648         continue;
16649       }
16650
16651       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16652       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16653       uint64_t ShAmt = C.getZExtValue();
16654       if (ShAmt >= SVTBits) {
16655         Elts.push_back(DAG.getUNDEF(SVT));
16656         continue;
16657       }
16658       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16659     }
16660     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16661     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16662   }
16663
16664   // Lower SHL with variable shift amount.
16665   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16666     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16667
16668     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16669                      DAG.getConstant(0x3f800000U, dl, VT));
16670     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16671     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16672     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16673   }
16674
16675   // If possible, lower this shift as a sequence of two shifts by
16676   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16677   // Example:
16678   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16679   //
16680   // Could be rewritten as:
16681   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16682   //
16683   // The advantage is that the two shifts from the example would be
16684   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16685   // the vector shift into four scalar shifts plus four pairs of vector
16686   // insert/extract.
16687   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16688       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16689     unsigned TargetOpcode = X86ISD::MOVSS;
16690     bool CanBeSimplified;
16691     // The splat value for the first packed shift (the 'X' from the example).
16692     SDValue Amt1 = Amt->getOperand(0);
16693     // The splat value for the second packed shift (the 'Y' from the example).
16694     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16695                                         Amt->getOperand(2);
16696
16697     // See if it is possible to replace this node with a sequence of
16698     // two shifts followed by a MOVSS/MOVSD
16699     if (VT == MVT::v4i32) {
16700       // Check if it is legal to use a MOVSS.
16701       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16702                         Amt2 == Amt->getOperand(3);
16703       if (!CanBeSimplified) {
16704         // Otherwise, check if we can still simplify this node using a MOVSD.
16705         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16706                           Amt->getOperand(2) == Amt->getOperand(3);
16707         TargetOpcode = X86ISD::MOVSD;
16708         Amt2 = Amt->getOperand(2);
16709       }
16710     } else {
16711       // Do similar checks for the case where the machine value type
16712       // is MVT::v8i16.
16713       CanBeSimplified = Amt1 == Amt->getOperand(1);
16714       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16715         CanBeSimplified = Amt2 == Amt->getOperand(i);
16716
16717       if (!CanBeSimplified) {
16718         TargetOpcode = X86ISD::MOVSD;
16719         CanBeSimplified = true;
16720         Amt2 = Amt->getOperand(4);
16721         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16722           CanBeSimplified = Amt1 == Amt->getOperand(i);
16723         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16724           CanBeSimplified = Amt2 == Amt->getOperand(j);
16725       }
16726     }
16727
16728     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16729         isa<ConstantSDNode>(Amt2)) {
16730       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16731       EVT CastVT = MVT::v4i32;
16732       SDValue Splat1 =
16733         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16734       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16735       SDValue Splat2 =
16736         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16737       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16738       if (TargetOpcode == X86ISD::MOVSD)
16739         CastVT = MVT::v2i64;
16740       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16741       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16742       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16743                                             BitCast1, DAG);
16744       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16745     }
16746   }
16747
16748   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16749     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16750     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16751
16752     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16753     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16754     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16755
16756     // r = VSELECT(r, shl(r, 4), a);
16757     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16758     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16759
16760     // a += a
16761     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16762     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16763     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16764
16765     // r = VSELECT(r, shl(r, 2), a);
16766     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16767     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16768
16769     // a += a
16770     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16771     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16772     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16773
16774     // return VSELECT(r, r+r, a);
16775     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16776                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16777     return R;
16778   }
16779
16780   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16781   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16782   // solution better.
16783   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16784     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16785     unsigned ExtOpc =
16786         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16787     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16788     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16789     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16790                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16791   }
16792
16793   // Decompose 256-bit shifts into smaller 128-bit shifts.
16794   if (VT.is256BitVector()) {
16795     unsigned NumElems = VT.getVectorNumElements();
16796     MVT EltVT = VT.getVectorElementType();
16797     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16798
16799     // Extract the two vectors
16800     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16801     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16802
16803     // Recreate the shift amount vectors
16804     SDValue Amt1, Amt2;
16805     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16806       // Constant shift amount
16807       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16808       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16809       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16810
16811       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16812       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16813     } else {
16814       // Variable shift amount
16815       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16816       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16817     }
16818
16819     // Issue new vector shifts for the smaller types
16820     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16821     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16822
16823     // Concatenate the result back
16824     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16825   }
16826
16827   return SDValue();
16828 }
16829
16830 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16831   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16832   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16833   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16834   // has only one use.
16835   SDNode *N = Op.getNode();
16836   SDValue LHS = N->getOperand(0);
16837   SDValue RHS = N->getOperand(1);
16838   unsigned BaseOp = 0;
16839   unsigned Cond = 0;
16840   SDLoc DL(Op);
16841   switch (Op.getOpcode()) {
16842   default: llvm_unreachable("Unknown ovf instruction!");
16843   case ISD::SADDO:
16844     // A subtract of one will be selected as a INC. Note that INC doesn't
16845     // set CF, so we can't do this for UADDO.
16846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16847       if (C->isOne()) {
16848         BaseOp = X86ISD::INC;
16849         Cond = X86::COND_O;
16850         break;
16851       }
16852     BaseOp = X86ISD::ADD;
16853     Cond = X86::COND_O;
16854     break;
16855   case ISD::UADDO:
16856     BaseOp = X86ISD::ADD;
16857     Cond = X86::COND_B;
16858     break;
16859   case ISD::SSUBO:
16860     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16861     // set CF, so we can't do this for USUBO.
16862     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16863       if (C->isOne()) {
16864         BaseOp = X86ISD::DEC;
16865         Cond = X86::COND_O;
16866         break;
16867       }
16868     BaseOp = X86ISD::SUB;
16869     Cond = X86::COND_O;
16870     break;
16871   case ISD::USUBO:
16872     BaseOp = X86ISD::SUB;
16873     Cond = X86::COND_B;
16874     break;
16875   case ISD::SMULO:
16876     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16877     Cond = X86::COND_O;
16878     break;
16879   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16880     if (N->getValueType(0) == MVT::i8) {
16881       BaseOp = X86ISD::UMUL8;
16882       Cond = X86::COND_O;
16883       break;
16884     }
16885     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16886                                  MVT::i32);
16887     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16888
16889     SDValue SetCC =
16890       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16891                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16892                   SDValue(Sum.getNode(), 2));
16893
16894     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16895   }
16896   }
16897
16898   // Also sets EFLAGS.
16899   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16900   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16901
16902   SDValue SetCC =
16903     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16904                 DAG.getConstant(Cond, DL, MVT::i32),
16905                 SDValue(Sum.getNode(), 1));
16906
16907   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16908 }
16909
16910 /// Returns true if the operand type is exactly twice the native width, and
16911 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16912 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16913 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16914 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16915   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16916
16917   if (OpWidth == 64)
16918     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16919   else if (OpWidth == 128)
16920     return Subtarget->hasCmpxchg16b();
16921   else
16922     return false;
16923 }
16924
16925 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16926   return needsCmpXchgNb(SI->getValueOperand()->getType());
16927 }
16928
16929 // Note: this turns large loads into lock cmpxchg8b/16b.
16930 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16931 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16932   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16933   return needsCmpXchgNb(PTy->getElementType());
16934 }
16935
16936 TargetLoweringBase::AtomicRMWExpansionKind
16937 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16938   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16939   const Type *MemType = AI->getType();
16940
16941   // If the operand is too big, we must see if cmpxchg8/16b is available
16942   // and default to library calls otherwise.
16943   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16944     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16945                                    : AtomicRMWExpansionKind::None;
16946   }
16947
16948   AtomicRMWInst::BinOp Op = AI->getOperation();
16949   switch (Op) {
16950   default:
16951     llvm_unreachable("Unknown atomic operation");
16952   case AtomicRMWInst::Xchg:
16953   case AtomicRMWInst::Add:
16954   case AtomicRMWInst::Sub:
16955     // It's better to use xadd, xsub or xchg for these in all cases.
16956     return AtomicRMWExpansionKind::None;
16957   case AtomicRMWInst::Or:
16958   case AtomicRMWInst::And:
16959   case AtomicRMWInst::Xor:
16960     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16961     // prefix to a normal instruction for these operations.
16962     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16963                             : AtomicRMWExpansionKind::None;
16964   case AtomicRMWInst::Nand:
16965   case AtomicRMWInst::Max:
16966   case AtomicRMWInst::Min:
16967   case AtomicRMWInst::UMax:
16968   case AtomicRMWInst::UMin:
16969     // These always require a non-trivial set of data operations on x86. We must
16970     // use a cmpxchg loop.
16971     return AtomicRMWExpansionKind::CmpXChg;
16972   }
16973 }
16974
16975 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16976   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16977   // no-sse2). There isn't any reason to disable it if the target processor
16978   // supports it.
16979   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16980 }
16981
16982 LoadInst *
16983 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16984   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16985   const Type *MemType = AI->getType();
16986   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16987   // there is no benefit in turning such RMWs into loads, and it is actually
16988   // harmful as it introduces a mfence.
16989   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16990     return nullptr;
16991
16992   auto Builder = IRBuilder<>(AI);
16993   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16994   auto SynchScope = AI->getSynchScope();
16995   // We must restrict the ordering to avoid generating loads with Release or
16996   // ReleaseAcquire orderings.
16997   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16998   auto Ptr = AI->getPointerOperand();
16999
17000   // Before the load we need a fence. Here is an example lifted from
17001   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17002   // is required:
17003   // Thread 0:
17004   //   x.store(1, relaxed);
17005   //   r1 = y.fetch_add(0, release);
17006   // Thread 1:
17007   //   y.fetch_add(42, acquire);
17008   //   r2 = x.load(relaxed);
17009   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17010   // lowered to just a load without a fence. A mfence flushes the store buffer,
17011   // making the optimization clearly correct.
17012   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17013   // otherwise, we might be able to be more agressive on relaxed idempotent
17014   // rmw. In practice, they do not look useful, so we don't try to be
17015   // especially clever.
17016   if (SynchScope == SingleThread) {
17017     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17018     // the IR level, so we must wrap it in an intrinsic.
17019     return nullptr;
17020   } else if (hasMFENCE(*Subtarget)) {
17021     Function *MFence = llvm::Intrinsic::getDeclaration(M,
17022             Intrinsic::x86_sse2_mfence);
17023     Builder.CreateCall(MFence);
17024   } else {
17025     // FIXME: it might make sense to use a locked operation here but on a
17026     // different cache-line to prevent cache-line bouncing. In practice it
17027     // is probably a small win, and x86 processors without mfence are rare
17028     // enough that we do not bother.
17029     return nullptr;
17030   }
17031
17032   // Finally we can emit the atomic load.
17033   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17034           AI->getType()->getPrimitiveSizeInBits());
17035   Loaded->setAtomic(Order, SynchScope);
17036   AI->replaceAllUsesWith(Loaded);
17037   AI->eraseFromParent();
17038   return Loaded;
17039 }
17040
17041 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17042                                  SelectionDAG &DAG) {
17043   SDLoc dl(Op);
17044   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17045     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17046   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17047     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17048
17049   // The only fence that needs an instruction is a sequentially-consistent
17050   // cross-thread fence.
17051   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17052     if (hasMFENCE(*Subtarget))
17053       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17054
17055     SDValue Chain = Op.getOperand(0);
17056     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17057     SDValue Ops[] = {
17058       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17059       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17060       DAG.getRegister(0, MVT::i32),            // Index
17061       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17062       DAG.getRegister(0, MVT::i32),            // Segment.
17063       Zero,
17064       Chain
17065     };
17066     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17067     return SDValue(Res, 0);
17068   }
17069
17070   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17071   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17072 }
17073
17074 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17075                              SelectionDAG &DAG) {
17076   MVT T = Op.getSimpleValueType();
17077   SDLoc DL(Op);
17078   unsigned Reg = 0;
17079   unsigned size = 0;
17080   switch(T.SimpleTy) {
17081   default: llvm_unreachable("Invalid value type!");
17082   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17083   case MVT::i16: Reg = X86::AX;  size = 2; break;
17084   case MVT::i32: Reg = X86::EAX; size = 4; break;
17085   case MVT::i64:
17086     assert(Subtarget->is64Bit() && "Node not type legal!");
17087     Reg = X86::RAX; size = 8;
17088     break;
17089   }
17090   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17091                                   Op.getOperand(2), SDValue());
17092   SDValue Ops[] = { cpIn.getValue(0),
17093                     Op.getOperand(1),
17094                     Op.getOperand(3),
17095                     DAG.getTargetConstant(size, DL, MVT::i8),
17096                     cpIn.getValue(1) };
17097   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17098   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17099   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17100                                            Ops, T, MMO);
17101
17102   SDValue cpOut =
17103     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17104   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17105                                       MVT::i32, cpOut.getValue(2));
17106   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17107                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17108                                 EFLAGS);
17109
17110   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17111   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17112   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17113   return SDValue();
17114 }
17115
17116 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17117                             SelectionDAG &DAG) {
17118   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17119   MVT DstVT = Op.getSimpleValueType();
17120
17121   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17122     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17123     if (DstVT != MVT::f64)
17124       // This conversion needs to be expanded.
17125       return SDValue();
17126
17127     SDValue InVec = Op->getOperand(0);
17128     SDLoc dl(Op);
17129     unsigned NumElts = SrcVT.getVectorNumElements();
17130     EVT SVT = SrcVT.getVectorElementType();
17131
17132     // Widen the vector in input in the case of MVT::v2i32.
17133     // Example: from MVT::v2i32 to MVT::v4i32.
17134     SmallVector<SDValue, 16> Elts;
17135     for (unsigned i = 0, e = NumElts; i != e; ++i)
17136       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17137                                  DAG.getIntPtrConstant(i, dl)));
17138
17139     // Explicitly mark the extra elements as Undef.
17140     Elts.append(NumElts, DAG.getUNDEF(SVT));
17141
17142     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17143     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17144     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17145     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17146                        DAG.getIntPtrConstant(0, dl));
17147   }
17148
17149   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17150          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17151   assert((DstVT == MVT::i64 ||
17152           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17153          "Unexpected custom BITCAST");
17154   // i64 <=> MMX conversions are Legal.
17155   if (SrcVT==MVT::i64 && DstVT.isVector())
17156     return Op;
17157   if (DstVT==MVT::i64 && SrcVT.isVector())
17158     return Op;
17159   // MMX <=> MMX conversions are Legal.
17160   if (SrcVT.isVector() && DstVT.isVector())
17161     return Op;
17162   // All other conversions need to be expanded.
17163   return SDValue();
17164 }
17165
17166 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17167                           SelectionDAG &DAG) {
17168   SDNode *Node = Op.getNode();
17169   SDLoc dl(Node);
17170
17171   Op = Op.getOperand(0);
17172   EVT VT = Op.getValueType();
17173   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17174          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17175
17176   unsigned NumElts = VT.getVectorNumElements();
17177   EVT EltVT = VT.getVectorElementType();
17178   unsigned Len = EltVT.getSizeInBits();
17179
17180   // This is the vectorized version of the "best" algorithm from
17181   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17182   // with a minor tweak to use a series of adds + shifts instead of vector
17183   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17184   //
17185   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17186   //  v8i32 => Always profitable
17187   //
17188   // FIXME: There a couple of possible improvements:
17189   //
17190   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17191   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17192   //
17193   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17194          "CTPOP not implemented for this vector element type.");
17195
17196   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17197   // extra legalization.
17198   bool NeedsBitcast = EltVT == MVT::i32;
17199   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17200
17201   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17202                                   EltVT);
17203   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17204                                   EltVT);
17205   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17206                                   EltVT);
17207
17208   // v = v - ((v >> 1) & 0x55555555...)
17209   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17210   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17211   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17212   if (NeedsBitcast)
17213     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17214
17215   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17216   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17217   if (NeedsBitcast)
17218     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17219
17220   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17221   if (VT != And.getValueType())
17222     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17223   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17224
17225   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17226   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17227   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17228   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17229   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17230
17231   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17232   if (NeedsBitcast) {
17233     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17234     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17235     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17236   }
17237
17238   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17239   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17240   if (VT != AndRHS.getValueType()) {
17241     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17242     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17243   }
17244   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17245
17246   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17247   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17248   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17249   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17250   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17251
17252   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17253   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17254   if (NeedsBitcast) {
17255     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17256     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17257   }
17258   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17259   if (VT != And.getValueType())
17260     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17261
17262   // The algorithm mentioned above uses:
17263   //    v = (v * 0x01010101...) >> (Len - 8)
17264   //
17265   // Change it to use vector adds + vector shifts which yield faster results on
17266   // Haswell than using vector integer multiplication.
17267   //
17268   // For i32 elements:
17269   //    v = v + (v >> 8)
17270   //    v = v + (v >> 16)
17271   //
17272   // For i64 elements:
17273   //    v = v + (v >> 8)
17274   //    v = v + (v >> 16)
17275   //    v = v + (v >> 32)
17276   //
17277   Add = And;
17278   SmallVector<SDValue, 8> Csts;
17279   for (unsigned i = 8; i <= Len/2; i *= 2) {
17280     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17281     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17282     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17283     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17284     Csts.clear();
17285   }
17286
17287   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17288   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17289                                   EltVT);
17290   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17291   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17292   if (NeedsBitcast) {
17293     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17294     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17295   }
17296   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17297   if (VT != And.getValueType())
17298     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17299
17300   return And;
17301 }
17302
17303 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17304   SDNode *Node = Op.getNode();
17305   SDLoc dl(Node);
17306   EVT T = Node->getValueType(0);
17307   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17308                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17309   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17310                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17311                        Node->getOperand(0),
17312                        Node->getOperand(1), negOp,
17313                        cast<AtomicSDNode>(Node)->getMemOperand(),
17314                        cast<AtomicSDNode>(Node)->getOrdering(),
17315                        cast<AtomicSDNode>(Node)->getSynchScope());
17316 }
17317
17318 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17319   SDNode *Node = Op.getNode();
17320   SDLoc dl(Node);
17321   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17322
17323   // Convert seq_cst store -> xchg
17324   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17325   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17326   //        (The only way to get a 16-byte store is cmpxchg16b)
17327   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17328   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17329       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17330     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17331                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17332                                  Node->getOperand(0),
17333                                  Node->getOperand(1), Node->getOperand(2),
17334                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17335                                  cast<AtomicSDNode>(Node)->getOrdering(),
17336                                  cast<AtomicSDNode>(Node)->getSynchScope());
17337     return Swap.getValue(1);
17338   }
17339   // Other atomic stores have a simple pattern.
17340   return Op;
17341 }
17342
17343 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17344   EVT VT = Op.getNode()->getSimpleValueType(0);
17345
17346   // Let legalize expand this if it isn't a legal type yet.
17347   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17348     return SDValue();
17349
17350   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17351
17352   unsigned Opc;
17353   bool ExtraOp = false;
17354   switch (Op.getOpcode()) {
17355   default: llvm_unreachable("Invalid code");
17356   case ISD::ADDC: Opc = X86ISD::ADD; break;
17357   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17358   case ISD::SUBC: Opc = X86ISD::SUB; break;
17359   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17360   }
17361
17362   if (!ExtraOp)
17363     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17364                        Op.getOperand(1));
17365   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17366                      Op.getOperand(1), Op.getOperand(2));
17367 }
17368
17369 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17370                             SelectionDAG &DAG) {
17371   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17372
17373   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17374   // which returns the values as { float, float } (in XMM0) or
17375   // { double, double } (which is returned in XMM0, XMM1).
17376   SDLoc dl(Op);
17377   SDValue Arg = Op.getOperand(0);
17378   EVT ArgVT = Arg.getValueType();
17379   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17380
17381   TargetLowering::ArgListTy Args;
17382   TargetLowering::ArgListEntry Entry;
17383
17384   Entry.Node = Arg;
17385   Entry.Ty = ArgTy;
17386   Entry.isSExt = false;
17387   Entry.isZExt = false;
17388   Args.push_back(Entry);
17389
17390   bool isF64 = ArgVT == MVT::f64;
17391   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17392   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17393   // the results are returned via SRet in memory.
17394   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17396   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17397
17398   Type *RetTy = isF64
17399     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17400     : (Type*)VectorType::get(ArgTy, 4);
17401
17402   TargetLowering::CallLoweringInfo CLI(DAG);
17403   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17404     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17405
17406   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17407
17408   if (isF64)
17409     // Returned in xmm0 and xmm1.
17410     return CallResult.first;
17411
17412   // Returned in bits 0:31 and 32:64 xmm0.
17413   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17414                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17415   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17416                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17417   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17418   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17419 }
17420
17421 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17422                              SelectionDAG &DAG) {
17423   assert(Subtarget->hasAVX512() &&
17424          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17425
17426   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17427   EVT VT = N->getValue().getValueType();
17428   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17429   SDLoc dl(Op);
17430
17431   // X86 scatter kills mask register, so its type should be added to
17432   // the list of return values
17433   if (N->getNumValues() == 1) {
17434     SDValue Index = N->getIndex();
17435     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17436         !Index.getValueType().is512BitVector())
17437       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17438
17439     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17440     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17441                       N->getOperand(3), Index };
17442
17443     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17444     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17445     return SDValue(NewScatter.getNode(), 0);
17446   }
17447   return Op;
17448 }
17449
17450 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17451                             SelectionDAG &DAG) {
17452   assert(Subtarget->hasAVX512() &&
17453          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17454
17455   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17456   EVT VT = Op.getValueType();
17457   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17458   SDLoc dl(Op);
17459
17460   SDValue Index = N->getIndex();
17461   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17462       !Index.getValueType().is512BitVector()) {
17463     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17464     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17465                       N->getOperand(3), Index };
17466     DAG.UpdateNodeOperands(N, Ops);
17467   }
17468   return Op;
17469 }
17470
17471 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17472                                                     SelectionDAG &DAG) const {
17473   // TODO: Eventually, the lowering of these nodes should be informed by or
17474   // deferred to the GC strategy for the function in which they appear. For
17475   // now, however, they must be lowered to something. Since they are logically
17476   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17477   // require special handling for these nodes), lower them as literal NOOPs for
17478   // the time being.
17479   SmallVector<SDValue, 2> Ops;
17480
17481   Ops.push_back(Op.getOperand(0));
17482   if (Op->getGluedNode())
17483     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17484
17485   SDLoc OpDL(Op);
17486   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17487   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17488
17489   return NOOP;
17490 }
17491
17492 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17493                                                   SelectionDAG &DAG) const {
17494   // TODO: Eventually, the lowering of these nodes should be informed by or
17495   // deferred to the GC strategy for the function in which they appear. For
17496   // now, however, they must be lowered to something. Since they are logically
17497   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17498   // require special handling for these nodes), lower them as literal NOOPs for
17499   // the time being.
17500   SmallVector<SDValue, 2> Ops;
17501
17502   Ops.push_back(Op.getOperand(0));
17503   if (Op->getGluedNode())
17504     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17505
17506   SDLoc OpDL(Op);
17507   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17508   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17509
17510   return NOOP;
17511 }
17512
17513 /// LowerOperation - Provide custom lowering hooks for some operations.
17514 ///
17515 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17516   switch (Op.getOpcode()) {
17517   default: llvm_unreachable("Should not custom lower this!");
17518   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17519   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17520     return LowerCMP_SWAP(Op, Subtarget, DAG);
17521   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17522   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17523   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17524   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17525   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17526   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17527   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17528   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17529   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17530   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17531   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17532   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17533   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17534   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17535   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17536   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17537   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17538   case ISD::SHL_PARTS:
17539   case ISD::SRA_PARTS:
17540   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17541   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17542   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17543   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17544   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17545   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17546   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17547   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17548   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17549   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17550   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17551   case ISD::FABS:
17552   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17553   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17554   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17555   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17556   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17557   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17558   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17559   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17560   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17561   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17562   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17563   case ISD::INTRINSIC_VOID:
17564   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17565   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17566   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17567   case ISD::FRAME_TO_ARGS_OFFSET:
17568                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17569   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17570   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17571   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17572   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17573   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17574   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17575   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17576   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17577   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17578   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17579   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17580   case ISD::UMUL_LOHI:
17581   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17582   case ISD::SRA:
17583   case ISD::SRL:
17584   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17585   case ISD::SADDO:
17586   case ISD::UADDO:
17587   case ISD::SSUBO:
17588   case ISD::USUBO:
17589   case ISD::SMULO:
17590   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17591   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17592   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17593   case ISD::ADDC:
17594   case ISD::ADDE:
17595   case ISD::SUBC:
17596   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17597   case ISD::ADD:                return LowerADD(Op, DAG);
17598   case ISD::SUB:                return LowerSUB(Op, DAG);
17599   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17600   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17601   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17602   case ISD::GC_TRANSITION_START:
17603                                 return LowerGC_TRANSITION_START(Op, DAG);
17604   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17605   }
17606 }
17607
17608 /// ReplaceNodeResults - Replace a node with an illegal result type
17609 /// with a new node built out of custom code.
17610 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17611                                            SmallVectorImpl<SDValue>&Results,
17612                                            SelectionDAG &DAG) const {
17613   SDLoc dl(N);
17614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17615   switch (N->getOpcode()) {
17616   default:
17617     llvm_unreachable("Do not know how to custom type legalize this operation!");
17618   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17619   case X86ISD::FMINC:
17620   case X86ISD::FMIN:
17621   case X86ISD::FMAXC:
17622   case X86ISD::FMAX: {
17623     EVT VT = N->getValueType(0);
17624     if (VT != MVT::v2f32)
17625       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17626     SDValue UNDEF = DAG.getUNDEF(VT);
17627     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17628                               N->getOperand(0), UNDEF);
17629     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17630                               N->getOperand(1), UNDEF);
17631     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17632     return;
17633   }
17634   case ISD::SIGN_EXTEND_INREG:
17635   case ISD::ADDC:
17636   case ISD::ADDE:
17637   case ISD::SUBC:
17638   case ISD::SUBE:
17639     // We don't want to expand or promote these.
17640     return;
17641   case ISD::SDIV:
17642   case ISD::UDIV:
17643   case ISD::SREM:
17644   case ISD::UREM:
17645   case ISD::SDIVREM:
17646   case ISD::UDIVREM: {
17647     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17648     Results.push_back(V);
17649     return;
17650   }
17651   case ISD::FP_TO_SINT:
17652     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17653     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17654     if (N->getOperand(0).getValueType() == MVT::f16)
17655       break;
17656     // fallthrough
17657   case ISD::FP_TO_UINT: {
17658     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17659
17660     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17661       return;
17662
17663     std::pair<SDValue,SDValue> Vals =
17664         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17665     SDValue FIST = Vals.first, StackSlot = Vals.second;
17666     if (FIST.getNode()) {
17667       EVT VT = N->getValueType(0);
17668       // Return a load from the stack slot.
17669       if (StackSlot.getNode())
17670         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17671                                       MachinePointerInfo(),
17672                                       false, false, false, 0));
17673       else
17674         Results.push_back(FIST);
17675     }
17676     return;
17677   }
17678   case ISD::UINT_TO_FP: {
17679     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17680     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17681         N->getValueType(0) != MVT::v2f32)
17682       return;
17683     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17684                                  N->getOperand(0));
17685     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17686                                      MVT::f64);
17687     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17688     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17689                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17690     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17691     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17692     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17693     return;
17694   }
17695   case ISD::FP_ROUND: {
17696     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17697         return;
17698     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17699     Results.push_back(V);
17700     return;
17701   }
17702   case ISD::FP_EXTEND: {
17703     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17704     // No other ValueType for FP_EXTEND should reach this point.
17705     assert(N->getValueType(0) == MVT::v2f32 &&
17706            "Do not know how to legalize this Node");
17707     return;
17708   }
17709   case ISD::INTRINSIC_W_CHAIN: {
17710     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17711     switch (IntNo) {
17712     default : llvm_unreachable("Do not know how to custom type "
17713                                "legalize this intrinsic operation!");
17714     case Intrinsic::x86_rdtsc:
17715       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17716                                      Results);
17717     case Intrinsic::x86_rdtscp:
17718       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17719                                      Results);
17720     case Intrinsic::x86_rdpmc:
17721       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17722     }
17723   }
17724   case ISD::READCYCLECOUNTER: {
17725     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17726                                    Results);
17727   }
17728   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17729     EVT T = N->getValueType(0);
17730     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17731     bool Regs64bit = T == MVT::i128;
17732     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17733     SDValue cpInL, cpInH;
17734     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17735                         DAG.getConstant(0, dl, HalfT));
17736     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17737                         DAG.getConstant(1, dl, HalfT));
17738     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17739                              Regs64bit ? X86::RAX : X86::EAX,
17740                              cpInL, SDValue());
17741     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17742                              Regs64bit ? X86::RDX : X86::EDX,
17743                              cpInH, cpInL.getValue(1));
17744     SDValue swapInL, swapInH;
17745     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17746                           DAG.getConstant(0, dl, HalfT));
17747     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17748                           DAG.getConstant(1, dl, HalfT));
17749     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17750                                Regs64bit ? X86::RBX : X86::EBX,
17751                                swapInL, cpInH.getValue(1));
17752     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17753                                Regs64bit ? X86::RCX : X86::ECX,
17754                                swapInH, swapInL.getValue(1));
17755     SDValue Ops[] = { swapInH.getValue(0),
17756                       N->getOperand(1),
17757                       swapInH.getValue(1) };
17758     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17759     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17760     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17761                                   X86ISD::LCMPXCHG8_DAG;
17762     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17763     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17764                                         Regs64bit ? X86::RAX : X86::EAX,
17765                                         HalfT, Result.getValue(1));
17766     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17767                                         Regs64bit ? X86::RDX : X86::EDX,
17768                                         HalfT, cpOutL.getValue(2));
17769     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17770
17771     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17772                                         MVT::i32, cpOutH.getValue(2));
17773     SDValue Success =
17774         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17775                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17776     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17777
17778     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17779     Results.push_back(Success);
17780     Results.push_back(EFLAGS.getValue(1));
17781     return;
17782   }
17783   case ISD::ATOMIC_SWAP:
17784   case ISD::ATOMIC_LOAD_ADD:
17785   case ISD::ATOMIC_LOAD_SUB:
17786   case ISD::ATOMIC_LOAD_AND:
17787   case ISD::ATOMIC_LOAD_OR:
17788   case ISD::ATOMIC_LOAD_XOR:
17789   case ISD::ATOMIC_LOAD_NAND:
17790   case ISD::ATOMIC_LOAD_MIN:
17791   case ISD::ATOMIC_LOAD_MAX:
17792   case ISD::ATOMIC_LOAD_UMIN:
17793   case ISD::ATOMIC_LOAD_UMAX:
17794   case ISD::ATOMIC_LOAD: {
17795     // Delegate to generic TypeLegalization. Situations we can really handle
17796     // should have already been dealt with by AtomicExpandPass.cpp.
17797     break;
17798   }
17799   case ISD::BITCAST: {
17800     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17801     EVT DstVT = N->getValueType(0);
17802     EVT SrcVT = N->getOperand(0)->getValueType(0);
17803
17804     if (SrcVT != MVT::f64 ||
17805         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17806       return;
17807
17808     unsigned NumElts = DstVT.getVectorNumElements();
17809     EVT SVT = DstVT.getVectorElementType();
17810     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17811     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17812                                    MVT::v2f64, N->getOperand(0));
17813     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17814
17815     if (ExperimentalVectorWideningLegalization) {
17816       // If we are legalizing vectors by widening, we already have the desired
17817       // legal vector type, just return it.
17818       Results.push_back(ToVecInt);
17819       return;
17820     }
17821
17822     SmallVector<SDValue, 8> Elts;
17823     for (unsigned i = 0, e = NumElts; i != e; ++i)
17824       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17825                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17826
17827     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17828   }
17829   }
17830 }
17831
17832 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17833   switch ((X86ISD::NodeType)Opcode) {
17834   case X86ISD::FIRST_NUMBER:       break;
17835   case X86ISD::BSF:                return "X86ISD::BSF";
17836   case X86ISD::BSR:                return "X86ISD::BSR";
17837   case X86ISD::SHLD:               return "X86ISD::SHLD";
17838   case X86ISD::SHRD:               return "X86ISD::SHRD";
17839   case X86ISD::FAND:               return "X86ISD::FAND";
17840   case X86ISD::FANDN:              return "X86ISD::FANDN";
17841   case X86ISD::FOR:                return "X86ISD::FOR";
17842   case X86ISD::FXOR:               return "X86ISD::FXOR";
17843   case X86ISD::FSRL:               return "X86ISD::FSRL";
17844   case X86ISD::FILD:               return "X86ISD::FILD";
17845   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17846   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17847   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17848   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17849   case X86ISD::FLD:                return "X86ISD::FLD";
17850   case X86ISD::FST:                return "X86ISD::FST";
17851   case X86ISD::CALL:               return "X86ISD::CALL";
17852   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17853   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17854   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17855   case X86ISD::BT:                 return "X86ISD::BT";
17856   case X86ISD::CMP:                return "X86ISD::CMP";
17857   case X86ISD::COMI:               return "X86ISD::COMI";
17858   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17859   case X86ISD::CMPM:               return "X86ISD::CMPM";
17860   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17861   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17862   case X86ISD::SETCC:              return "X86ISD::SETCC";
17863   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17864   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17865   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17866   case X86ISD::CMOV:               return "X86ISD::CMOV";
17867   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17868   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17869   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17870   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17871   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17872   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17873   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17874   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17875   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17876   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17877   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17878   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17879   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17880   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17881   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17882   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17883   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17884   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17885   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17886   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17887   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17888   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17889   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17890   case X86ISD::HADD:               return "X86ISD::HADD";
17891   case X86ISD::HSUB:               return "X86ISD::HSUB";
17892   case X86ISD::FHADD:              return "X86ISD::FHADD";
17893   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17894   case X86ISD::UMAX:               return "X86ISD::UMAX";
17895   case X86ISD::UMIN:               return "X86ISD::UMIN";
17896   case X86ISD::SMAX:               return "X86ISD::SMAX";
17897   case X86ISD::SMIN:               return "X86ISD::SMIN";
17898   case X86ISD::FMAX:               return "X86ISD::FMAX";
17899   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17900   case X86ISD::FMIN:               return "X86ISD::FMIN";
17901   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
17902   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17903   case X86ISD::FMINC:              return "X86ISD::FMINC";
17904   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17905   case X86ISD::FRCP:               return "X86ISD::FRCP";
17906   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17907   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17908   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17909   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17910   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17911   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17912   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17913   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17914   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17915   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17916   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17917   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17918   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17919   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17920   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17921   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17922   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17923   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17924   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17925   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17926   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17927   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17928   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17929   case X86ISD::VSHL:               return "X86ISD::VSHL";
17930   case X86ISD::VSRL:               return "X86ISD::VSRL";
17931   case X86ISD::VSRA:               return "X86ISD::VSRA";
17932   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17933   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17934   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17935   case X86ISD::CMPP:               return "X86ISD::CMPP";
17936   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17937   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17938   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17939   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17940   case X86ISD::ADD:                return "X86ISD::ADD";
17941   case X86ISD::SUB:                return "X86ISD::SUB";
17942   case X86ISD::ADC:                return "X86ISD::ADC";
17943   case X86ISD::SBB:                return "X86ISD::SBB";
17944   case X86ISD::SMUL:               return "X86ISD::SMUL";
17945   case X86ISD::UMUL:               return "X86ISD::UMUL";
17946   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17947   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17948   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17949   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17950   case X86ISD::INC:                return "X86ISD::INC";
17951   case X86ISD::DEC:                return "X86ISD::DEC";
17952   case X86ISD::OR:                 return "X86ISD::OR";
17953   case X86ISD::XOR:                return "X86ISD::XOR";
17954   case X86ISD::AND:                return "X86ISD::AND";
17955   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17956   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17957   case X86ISD::PTEST:              return "X86ISD::PTEST";
17958   case X86ISD::TESTP:              return "X86ISD::TESTP";
17959   case X86ISD::TESTM:              return "X86ISD::TESTM";
17960   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17961   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17962   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17963   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17964   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17965   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17966   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17967   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17968   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17969   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17970   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17971   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17972   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17973   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17974   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17975   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17976   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17977   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17978   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17979   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17980   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17981   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17982   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17983   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17984   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
17985   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17986   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17987   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17988   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17989   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17990   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17991   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17992   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17993   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17994   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17995   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17996   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17997   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
17998   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
17999   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18000   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18001   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18002   case X86ISD::SAHF:               return "X86ISD::SAHF";
18003   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18004   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18005   case X86ISD::FMADD:              return "X86ISD::FMADD";
18006   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18007   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18008   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18009   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18010   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18011   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18012   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18013   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18014   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18015   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18016   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18017   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18018   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18019   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18020   case X86ISD::XTEST:              return "X86ISD::XTEST";
18021   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18022   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18023   case X86ISD::SELECT:             return "X86ISD::SELECT";
18024   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18025   case X86ISD::RCP28:              return "X86ISD::RCP28";
18026   case X86ISD::EXP2:               return "X86ISD::EXP2";
18027   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18028   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18029   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18030   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18031   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18032   case X86ISD::ADDS:               return "X86ISD::ADDS";
18033   case X86ISD::SUBS:               return "X86ISD::SUBS";
18034   }
18035   return nullptr;
18036 }
18037
18038 // isLegalAddressingMode - Return true if the addressing mode represented
18039 // by AM is legal for this target, for a load/store of the specified type.
18040 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18041                                               Type *Ty) const {
18042   // X86 supports extremely general addressing modes.
18043   CodeModel::Model M = getTargetMachine().getCodeModel();
18044   Reloc::Model R = getTargetMachine().getRelocationModel();
18045
18046   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18047   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18048     return false;
18049
18050   if (AM.BaseGV) {
18051     unsigned GVFlags =
18052       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18053
18054     // If a reference to this global requires an extra load, we can't fold it.
18055     if (isGlobalStubReference(GVFlags))
18056       return false;
18057
18058     // If BaseGV requires a register for the PIC base, we cannot also have a
18059     // BaseReg specified.
18060     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18061       return false;
18062
18063     // If lower 4G is not available, then we must use rip-relative addressing.
18064     if ((M != CodeModel::Small || R != Reloc::Static) &&
18065         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18066       return false;
18067   }
18068
18069   switch (AM.Scale) {
18070   case 0:
18071   case 1:
18072   case 2:
18073   case 4:
18074   case 8:
18075     // These scales always work.
18076     break;
18077   case 3:
18078   case 5:
18079   case 9:
18080     // These scales are formed with basereg+scalereg.  Only accept if there is
18081     // no basereg yet.
18082     if (AM.HasBaseReg)
18083       return false;
18084     break;
18085   default:  // Other stuff never works.
18086     return false;
18087   }
18088
18089   return true;
18090 }
18091
18092 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18093   unsigned Bits = Ty->getScalarSizeInBits();
18094
18095   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18096   // particularly cheaper than those without.
18097   if (Bits == 8)
18098     return false;
18099
18100   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18101   // variable shifts just as cheap as scalar ones.
18102   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18103     return false;
18104
18105   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18106   // fully general vector.
18107   return true;
18108 }
18109
18110 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18111   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18112     return false;
18113   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18114   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18115   return NumBits1 > NumBits2;
18116 }
18117
18118 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18119   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18120     return false;
18121
18122   if (!isTypeLegal(EVT::getEVT(Ty1)))
18123     return false;
18124
18125   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18126
18127   // Assuming the caller doesn't have a zeroext or signext return parameter,
18128   // truncation all the way down to i1 is valid.
18129   return true;
18130 }
18131
18132 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18133   return isInt<32>(Imm);
18134 }
18135
18136 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18137   // Can also use sub to handle negated immediates.
18138   return isInt<32>(Imm);
18139 }
18140
18141 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18142   if (!VT1.isInteger() || !VT2.isInteger())
18143     return false;
18144   unsigned NumBits1 = VT1.getSizeInBits();
18145   unsigned NumBits2 = VT2.getSizeInBits();
18146   return NumBits1 > NumBits2;
18147 }
18148
18149 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18150   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18151   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18152 }
18153
18154 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18155   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18156   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18157 }
18158
18159 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18160   EVT VT1 = Val.getValueType();
18161   if (isZExtFree(VT1, VT2))
18162     return true;
18163
18164   if (Val.getOpcode() != ISD::LOAD)
18165     return false;
18166
18167   if (!VT1.isSimple() || !VT1.isInteger() ||
18168       !VT2.isSimple() || !VT2.isInteger())
18169     return false;
18170
18171   switch (VT1.getSimpleVT().SimpleTy) {
18172   default: break;
18173   case MVT::i8:
18174   case MVT::i16:
18175   case MVT::i32:
18176     // X86 has 8, 16, and 32-bit zero-extending loads.
18177     return true;
18178   }
18179
18180   return false;
18181 }
18182
18183 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18184
18185 bool
18186 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18187   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18188     return false;
18189
18190   VT = VT.getScalarType();
18191
18192   if (!VT.isSimple())
18193     return false;
18194
18195   switch (VT.getSimpleVT().SimpleTy) {
18196   case MVT::f32:
18197   case MVT::f64:
18198     return true;
18199   default:
18200     break;
18201   }
18202
18203   return false;
18204 }
18205
18206 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18207   // i16 instructions are longer (0x66 prefix) and potentially slower.
18208   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18209 }
18210
18211 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18212 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18213 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18214 /// are assumed to be legal.
18215 bool
18216 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18217                                       EVT VT) const {
18218   if (!VT.isSimple())
18219     return false;
18220
18221   // Not for i1 vectors
18222   if (VT.getScalarType() == MVT::i1)
18223     return false;
18224
18225   // Very little shuffling can be done for 64-bit vectors right now.
18226   if (VT.getSizeInBits() == 64)
18227     return false;
18228
18229   // We only care that the types being shuffled are legal. The lowering can
18230   // handle any possible shuffle mask that results.
18231   return isTypeLegal(VT.getSimpleVT());
18232 }
18233
18234 bool
18235 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18236                                           EVT VT) const {
18237   // Just delegate to the generic legality, clear masks aren't special.
18238   return isShuffleMaskLegal(Mask, VT);
18239 }
18240
18241 //===----------------------------------------------------------------------===//
18242 //                           X86 Scheduler Hooks
18243 //===----------------------------------------------------------------------===//
18244
18245 /// Utility function to emit xbegin specifying the start of an RTM region.
18246 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18247                                      const TargetInstrInfo *TII) {
18248   DebugLoc DL = MI->getDebugLoc();
18249
18250   const BasicBlock *BB = MBB->getBasicBlock();
18251   MachineFunction::iterator I = MBB;
18252   ++I;
18253
18254   // For the v = xbegin(), we generate
18255   //
18256   // thisMBB:
18257   //  xbegin sinkMBB
18258   //
18259   // mainMBB:
18260   //  eax = -1
18261   //
18262   // sinkMBB:
18263   //  v = eax
18264
18265   MachineBasicBlock *thisMBB = MBB;
18266   MachineFunction *MF = MBB->getParent();
18267   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18268   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18269   MF->insert(I, mainMBB);
18270   MF->insert(I, sinkMBB);
18271
18272   // Transfer the remainder of BB and its successor edges to sinkMBB.
18273   sinkMBB->splice(sinkMBB->begin(), MBB,
18274                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18275   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18276
18277   // thisMBB:
18278   //  xbegin sinkMBB
18279   //  # fallthrough to mainMBB
18280   //  # abortion to sinkMBB
18281   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18282   thisMBB->addSuccessor(mainMBB);
18283   thisMBB->addSuccessor(sinkMBB);
18284
18285   // mainMBB:
18286   //  EAX = -1
18287   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18288   mainMBB->addSuccessor(sinkMBB);
18289
18290   // sinkMBB:
18291   // EAX is live into the sinkMBB
18292   sinkMBB->addLiveIn(X86::EAX);
18293   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18294           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18295     .addReg(X86::EAX);
18296
18297   MI->eraseFromParent();
18298   return sinkMBB;
18299 }
18300
18301 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18302 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18303 // in the .td file.
18304 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18305                                        const TargetInstrInfo *TII) {
18306   unsigned Opc;
18307   switch (MI->getOpcode()) {
18308   default: llvm_unreachable("illegal opcode!");
18309   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18310   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18311   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18312   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18313   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18314   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18315   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18316   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18317   }
18318
18319   DebugLoc dl = MI->getDebugLoc();
18320   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18321
18322   unsigned NumArgs = MI->getNumOperands();
18323   for (unsigned i = 1; i < NumArgs; ++i) {
18324     MachineOperand &Op = MI->getOperand(i);
18325     if (!(Op.isReg() && Op.isImplicit()))
18326       MIB.addOperand(Op);
18327   }
18328   if (MI->hasOneMemOperand())
18329     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18330
18331   BuildMI(*BB, MI, dl,
18332     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18333     .addReg(X86::XMM0);
18334
18335   MI->eraseFromParent();
18336   return BB;
18337 }
18338
18339 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18340 // defs in an instruction pattern
18341 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18342                                        const TargetInstrInfo *TII) {
18343   unsigned Opc;
18344   switch (MI->getOpcode()) {
18345   default: llvm_unreachable("illegal opcode!");
18346   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18347   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18348   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18349   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18350   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18351   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18352   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18353   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18354   }
18355
18356   DebugLoc dl = MI->getDebugLoc();
18357   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18358
18359   unsigned NumArgs = MI->getNumOperands(); // remove the results
18360   for (unsigned i = 1; i < NumArgs; ++i) {
18361     MachineOperand &Op = MI->getOperand(i);
18362     if (!(Op.isReg() && Op.isImplicit()))
18363       MIB.addOperand(Op);
18364   }
18365   if (MI->hasOneMemOperand())
18366     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18367
18368   BuildMI(*BB, MI, dl,
18369     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18370     .addReg(X86::ECX);
18371
18372   MI->eraseFromParent();
18373   return BB;
18374 }
18375
18376 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18377                                       const X86Subtarget *Subtarget) {
18378   DebugLoc dl = MI->getDebugLoc();
18379   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18380   // Address into RAX/EAX, other two args into ECX, EDX.
18381   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18382   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18383   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18384   for (int i = 0; i < X86::AddrNumOperands; ++i)
18385     MIB.addOperand(MI->getOperand(i));
18386
18387   unsigned ValOps = X86::AddrNumOperands;
18388   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18389     .addReg(MI->getOperand(ValOps).getReg());
18390   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18391     .addReg(MI->getOperand(ValOps+1).getReg());
18392
18393   // The instruction doesn't actually take any operands though.
18394   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18395
18396   MI->eraseFromParent(); // The pseudo is gone now.
18397   return BB;
18398 }
18399
18400 MachineBasicBlock *
18401 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18402                                                  MachineBasicBlock *MBB) const {
18403   // Emit va_arg instruction on X86-64.
18404
18405   // Operands to this pseudo-instruction:
18406   // 0  ) Output        : destination address (reg)
18407   // 1-5) Input         : va_list address (addr, i64mem)
18408   // 6  ) ArgSize       : Size (in bytes) of vararg type
18409   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18410   // 8  ) Align         : Alignment of type
18411   // 9  ) EFLAGS (implicit-def)
18412
18413   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18414   static_assert(X86::AddrNumOperands == 5,
18415                 "VAARG_64 assumes 5 address operands");
18416
18417   unsigned DestReg = MI->getOperand(0).getReg();
18418   MachineOperand &Base = MI->getOperand(1);
18419   MachineOperand &Scale = MI->getOperand(2);
18420   MachineOperand &Index = MI->getOperand(3);
18421   MachineOperand &Disp = MI->getOperand(4);
18422   MachineOperand &Segment = MI->getOperand(5);
18423   unsigned ArgSize = MI->getOperand(6).getImm();
18424   unsigned ArgMode = MI->getOperand(7).getImm();
18425   unsigned Align = MI->getOperand(8).getImm();
18426
18427   // Memory Reference
18428   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18429   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18430   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18431
18432   // Machine Information
18433   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18434   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18435   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18436   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18437   DebugLoc DL = MI->getDebugLoc();
18438
18439   // struct va_list {
18440   //   i32   gp_offset
18441   //   i32   fp_offset
18442   //   i64   overflow_area (address)
18443   //   i64   reg_save_area (address)
18444   // }
18445   // sizeof(va_list) = 24
18446   // alignment(va_list) = 8
18447
18448   unsigned TotalNumIntRegs = 6;
18449   unsigned TotalNumXMMRegs = 8;
18450   bool UseGPOffset = (ArgMode == 1);
18451   bool UseFPOffset = (ArgMode == 2);
18452   unsigned MaxOffset = TotalNumIntRegs * 8 +
18453                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18454
18455   /* Align ArgSize to a multiple of 8 */
18456   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18457   bool NeedsAlign = (Align > 8);
18458
18459   MachineBasicBlock *thisMBB = MBB;
18460   MachineBasicBlock *overflowMBB;
18461   MachineBasicBlock *offsetMBB;
18462   MachineBasicBlock *endMBB;
18463
18464   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18465   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18466   unsigned OffsetReg = 0;
18467
18468   if (!UseGPOffset && !UseFPOffset) {
18469     // If we only pull from the overflow region, we don't create a branch.
18470     // We don't need to alter control flow.
18471     OffsetDestReg = 0; // unused
18472     OverflowDestReg = DestReg;
18473
18474     offsetMBB = nullptr;
18475     overflowMBB = thisMBB;
18476     endMBB = thisMBB;
18477   } else {
18478     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18479     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18480     // If not, pull from overflow_area. (branch to overflowMBB)
18481     //
18482     //       thisMBB
18483     //         |     .
18484     //         |        .
18485     //     offsetMBB   overflowMBB
18486     //         |        .
18487     //         |     .
18488     //        endMBB
18489
18490     // Registers for the PHI in endMBB
18491     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18492     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18493
18494     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18495     MachineFunction *MF = MBB->getParent();
18496     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18497     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18498     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18499
18500     MachineFunction::iterator MBBIter = MBB;
18501     ++MBBIter;
18502
18503     // Insert the new basic blocks
18504     MF->insert(MBBIter, offsetMBB);
18505     MF->insert(MBBIter, overflowMBB);
18506     MF->insert(MBBIter, endMBB);
18507
18508     // Transfer the remainder of MBB and its successor edges to endMBB.
18509     endMBB->splice(endMBB->begin(), thisMBB,
18510                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18511     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18512
18513     // Make offsetMBB and overflowMBB successors of thisMBB
18514     thisMBB->addSuccessor(offsetMBB);
18515     thisMBB->addSuccessor(overflowMBB);
18516
18517     // endMBB is a successor of both offsetMBB and overflowMBB
18518     offsetMBB->addSuccessor(endMBB);
18519     overflowMBB->addSuccessor(endMBB);
18520
18521     // Load the offset value into a register
18522     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18523     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18524       .addOperand(Base)
18525       .addOperand(Scale)
18526       .addOperand(Index)
18527       .addDisp(Disp, UseFPOffset ? 4 : 0)
18528       .addOperand(Segment)
18529       .setMemRefs(MMOBegin, MMOEnd);
18530
18531     // Check if there is enough room left to pull this argument.
18532     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18533       .addReg(OffsetReg)
18534       .addImm(MaxOffset + 8 - ArgSizeA8);
18535
18536     // Branch to "overflowMBB" if offset >= max
18537     // Fall through to "offsetMBB" otherwise
18538     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18539       .addMBB(overflowMBB);
18540   }
18541
18542   // In offsetMBB, emit code to use the reg_save_area.
18543   if (offsetMBB) {
18544     assert(OffsetReg != 0);
18545
18546     // Read the reg_save_area address.
18547     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18548     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18549       .addOperand(Base)
18550       .addOperand(Scale)
18551       .addOperand(Index)
18552       .addDisp(Disp, 16)
18553       .addOperand(Segment)
18554       .setMemRefs(MMOBegin, MMOEnd);
18555
18556     // Zero-extend the offset
18557     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18558       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18559         .addImm(0)
18560         .addReg(OffsetReg)
18561         .addImm(X86::sub_32bit);
18562
18563     // Add the offset to the reg_save_area to get the final address.
18564     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18565       .addReg(OffsetReg64)
18566       .addReg(RegSaveReg);
18567
18568     // Compute the offset for the next argument
18569     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18570     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18571       .addReg(OffsetReg)
18572       .addImm(UseFPOffset ? 16 : 8);
18573
18574     // Store it back into the va_list.
18575     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18576       .addOperand(Base)
18577       .addOperand(Scale)
18578       .addOperand(Index)
18579       .addDisp(Disp, UseFPOffset ? 4 : 0)
18580       .addOperand(Segment)
18581       .addReg(NextOffsetReg)
18582       .setMemRefs(MMOBegin, MMOEnd);
18583
18584     // Jump to endMBB
18585     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18586       .addMBB(endMBB);
18587   }
18588
18589   //
18590   // Emit code to use overflow area
18591   //
18592
18593   // Load the overflow_area address into a register.
18594   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18595   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18596     .addOperand(Base)
18597     .addOperand(Scale)
18598     .addOperand(Index)
18599     .addDisp(Disp, 8)
18600     .addOperand(Segment)
18601     .setMemRefs(MMOBegin, MMOEnd);
18602
18603   // If we need to align it, do so. Otherwise, just copy the address
18604   // to OverflowDestReg.
18605   if (NeedsAlign) {
18606     // Align the overflow address
18607     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18608     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18609
18610     // aligned_addr = (addr + (align-1)) & ~(align-1)
18611     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18612       .addReg(OverflowAddrReg)
18613       .addImm(Align-1);
18614
18615     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18616       .addReg(TmpReg)
18617       .addImm(~(uint64_t)(Align-1));
18618   } else {
18619     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18620       .addReg(OverflowAddrReg);
18621   }
18622
18623   // Compute the next overflow address after this argument.
18624   // (the overflow address should be kept 8-byte aligned)
18625   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18626   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18627     .addReg(OverflowDestReg)
18628     .addImm(ArgSizeA8);
18629
18630   // Store the new overflow address.
18631   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18632     .addOperand(Base)
18633     .addOperand(Scale)
18634     .addOperand(Index)
18635     .addDisp(Disp, 8)
18636     .addOperand(Segment)
18637     .addReg(NextAddrReg)
18638     .setMemRefs(MMOBegin, MMOEnd);
18639
18640   // If we branched, emit the PHI to the front of endMBB.
18641   if (offsetMBB) {
18642     BuildMI(*endMBB, endMBB->begin(), DL,
18643             TII->get(X86::PHI), DestReg)
18644       .addReg(OffsetDestReg).addMBB(offsetMBB)
18645       .addReg(OverflowDestReg).addMBB(overflowMBB);
18646   }
18647
18648   // Erase the pseudo instruction
18649   MI->eraseFromParent();
18650
18651   return endMBB;
18652 }
18653
18654 MachineBasicBlock *
18655 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18656                                                  MachineInstr *MI,
18657                                                  MachineBasicBlock *MBB) const {
18658   // Emit code to save XMM registers to the stack. The ABI says that the
18659   // number of registers to save is given in %al, so it's theoretically
18660   // possible to do an indirect jump trick to avoid saving all of them,
18661   // however this code takes a simpler approach and just executes all
18662   // of the stores if %al is non-zero. It's less code, and it's probably
18663   // easier on the hardware branch predictor, and stores aren't all that
18664   // expensive anyway.
18665
18666   // Create the new basic blocks. One block contains all the XMM stores,
18667   // and one block is the final destination regardless of whether any
18668   // stores were performed.
18669   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18670   MachineFunction *F = MBB->getParent();
18671   MachineFunction::iterator MBBIter = MBB;
18672   ++MBBIter;
18673   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18674   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18675   F->insert(MBBIter, XMMSaveMBB);
18676   F->insert(MBBIter, EndMBB);
18677
18678   // Transfer the remainder of MBB and its successor edges to EndMBB.
18679   EndMBB->splice(EndMBB->begin(), MBB,
18680                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18681   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18682
18683   // The original block will now fall through to the XMM save block.
18684   MBB->addSuccessor(XMMSaveMBB);
18685   // The XMMSaveMBB will fall through to the end block.
18686   XMMSaveMBB->addSuccessor(EndMBB);
18687
18688   // Now add the instructions.
18689   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18690   DebugLoc DL = MI->getDebugLoc();
18691
18692   unsigned CountReg = MI->getOperand(0).getReg();
18693   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18694   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18695
18696   if (!Subtarget->isTargetWin64()) {
18697     // If %al is 0, branch around the XMM save block.
18698     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18699     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18700     MBB->addSuccessor(EndMBB);
18701   }
18702
18703   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18704   // that was just emitted, but clearly shouldn't be "saved".
18705   assert((MI->getNumOperands() <= 3 ||
18706           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18707           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18708          && "Expected last argument to be EFLAGS");
18709   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18710   // In the XMM save block, save all the XMM argument registers.
18711   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18712     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18713     MachineMemOperand *MMO =
18714       F->getMachineMemOperand(
18715           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18716         MachineMemOperand::MOStore,
18717         /*Size=*/16, /*Align=*/16);
18718     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18719       .addFrameIndex(RegSaveFrameIndex)
18720       .addImm(/*Scale=*/1)
18721       .addReg(/*IndexReg=*/0)
18722       .addImm(/*Disp=*/Offset)
18723       .addReg(/*Segment=*/0)
18724       .addReg(MI->getOperand(i).getReg())
18725       .addMemOperand(MMO);
18726   }
18727
18728   MI->eraseFromParent();   // The pseudo instruction is gone now.
18729
18730   return EndMBB;
18731 }
18732
18733 // The EFLAGS operand of SelectItr might be missing a kill marker
18734 // because there were multiple uses of EFLAGS, and ISel didn't know
18735 // which to mark. Figure out whether SelectItr should have had a
18736 // kill marker, and set it if it should. Returns the correct kill
18737 // marker value.
18738 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18739                                      MachineBasicBlock* BB,
18740                                      const TargetRegisterInfo* TRI) {
18741   // Scan forward through BB for a use/def of EFLAGS.
18742   MachineBasicBlock::iterator miI(std::next(SelectItr));
18743   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18744     const MachineInstr& mi = *miI;
18745     if (mi.readsRegister(X86::EFLAGS))
18746       return false;
18747     if (mi.definesRegister(X86::EFLAGS))
18748       break; // Should have kill-flag - update below.
18749   }
18750
18751   // If we hit the end of the block, check whether EFLAGS is live into a
18752   // successor.
18753   if (miI == BB->end()) {
18754     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18755                                           sEnd = BB->succ_end();
18756          sItr != sEnd; ++sItr) {
18757       MachineBasicBlock* succ = *sItr;
18758       if (succ->isLiveIn(X86::EFLAGS))
18759         return false;
18760     }
18761   }
18762
18763   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18764   // out. SelectMI should have a kill flag on EFLAGS.
18765   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18766   return true;
18767 }
18768
18769 MachineBasicBlock *
18770 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18771                                      MachineBasicBlock *BB) const {
18772   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18773   DebugLoc DL = MI->getDebugLoc();
18774
18775   // To "insert" a SELECT_CC instruction, we actually have to insert the
18776   // diamond control-flow pattern.  The incoming instruction knows the
18777   // destination vreg to set, the condition code register to branch on, the
18778   // true/false values to select between, and a branch opcode to use.
18779   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18780   MachineFunction::iterator It = BB;
18781   ++It;
18782
18783   //  thisMBB:
18784   //  ...
18785   //   TrueVal = ...
18786   //   cmpTY ccX, r1, r2
18787   //   bCC copy1MBB
18788   //   fallthrough --> copy0MBB
18789   MachineBasicBlock *thisMBB = BB;
18790   MachineFunction *F = BB->getParent();
18791
18792   // We also lower double CMOVs:
18793   //   (CMOV (CMOV F, T, cc1), T, cc2)
18794   // to two successives branches.  For that, we look for another CMOV as the
18795   // following instruction.
18796   //
18797   // Without this, we would add a PHI between the two jumps, which ends up
18798   // creating a few copies all around. For instance, for
18799   //
18800   //    (sitofp (zext (fcmp une)))
18801   //
18802   // we would generate:
18803   //
18804   //         ucomiss %xmm1, %xmm0
18805   //         movss  <1.0f>, %xmm0
18806   //         movaps  %xmm0, %xmm1
18807   //         jne     .LBB5_2
18808   //         xorps   %xmm1, %xmm1
18809   // .LBB5_2:
18810   //         jp      .LBB5_4
18811   //         movaps  %xmm1, %xmm0
18812   // .LBB5_4:
18813   //         retq
18814   //
18815   // because this custom-inserter would have generated:
18816   //
18817   //   A
18818   //   | \
18819   //   |  B
18820   //   | /
18821   //   C
18822   //   | \
18823   //   |  D
18824   //   | /
18825   //   E
18826   //
18827   // A: X = ...; Y = ...
18828   // B: empty
18829   // C: Z = PHI [X, A], [Y, B]
18830   // D: empty
18831   // E: PHI [X, C], [Z, D]
18832   //
18833   // If we lower both CMOVs in a single step, we can instead generate:
18834   //
18835   //   A
18836   //   | \
18837   //   |  C
18838   //   | /|
18839   //   |/ |
18840   //   |  |
18841   //   |  D
18842   //   | /
18843   //   E
18844   //
18845   // A: X = ...; Y = ...
18846   // D: empty
18847   // E: PHI [X, A], [X, C], [Y, D]
18848   //
18849   // Which, in our sitofp/fcmp example, gives us something like:
18850   //
18851   //         ucomiss %xmm1, %xmm0
18852   //         movss  <1.0f>, %xmm0
18853   //         jne     .LBB5_4
18854   //         jp      .LBB5_4
18855   //         xorps   %xmm0, %xmm0
18856   // .LBB5_4:
18857   //         retq
18858   //
18859   MachineInstr *NextCMOV = nullptr;
18860   MachineBasicBlock::iterator NextMIIt =
18861       std::next(MachineBasicBlock::iterator(MI));
18862   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18863       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18864       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18865     NextCMOV = &*NextMIIt;
18866
18867   MachineBasicBlock *jcc1MBB = nullptr;
18868
18869   // If we have a double CMOV, we lower it to two successive branches to
18870   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18871   if (NextCMOV) {
18872     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18873     F->insert(It, jcc1MBB);
18874     jcc1MBB->addLiveIn(X86::EFLAGS);
18875   }
18876
18877   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18878   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18879   F->insert(It, copy0MBB);
18880   F->insert(It, sinkMBB);
18881
18882   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18883   // live into the sink and copy blocks.
18884   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18885
18886   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18887   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18888       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18889     copy0MBB->addLiveIn(X86::EFLAGS);
18890     sinkMBB->addLiveIn(X86::EFLAGS);
18891   }
18892
18893   // Transfer the remainder of BB and its successor edges to sinkMBB.
18894   sinkMBB->splice(sinkMBB->begin(), BB,
18895                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18896   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18897
18898   // Add the true and fallthrough blocks as its successors.
18899   if (NextCMOV) {
18900     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18901     BB->addSuccessor(jcc1MBB);
18902
18903     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18904     // jump to the sinkMBB.
18905     jcc1MBB->addSuccessor(copy0MBB);
18906     jcc1MBB->addSuccessor(sinkMBB);
18907   } else {
18908     BB->addSuccessor(copy0MBB);
18909   }
18910
18911   // The true block target of the first (or only) branch is always sinkMBB.
18912   BB->addSuccessor(sinkMBB);
18913
18914   // Create the conditional branch instruction.
18915   unsigned Opc =
18916     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18917   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18918
18919   if (NextCMOV) {
18920     unsigned Opc2 = X86::GetCondBranchFromCond(
18921         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18922     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18923   }
18924
18925   //  copy0MBB:
18926   //   %FalseValue = ...
18927   //   # fallthrough to sinkMBB
18928   copy0MBB->addSuccessor(sinkMBB);
18929
18930   //  sinkMBB:
18931   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18932   //  ...
18933   MachineInstrBuilder MIB =
18934       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18935               MI->getOperand(0).getReg())
18936           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18937           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18938
18939   // If we have a double CMOV, the second Jcc provides the same incoming
18940   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18941   if (NextCMOV) {
18942     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18943     // Copy the PHI result to the register defined by the second CMOV.
18944     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18945             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18946         .addReg(MI->getOperand(0).getReg());
18947     NextCMOV->eraseFromParent();
18948   }
18949
18950   MI->eraseFromParent();   // The pseudo instruction is gone now.
18951   return sinkMBB;
18952 }
18953
18954 MachineBasicBlock *
18955 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18956                                         MachineBasicBlock *BB) const {
18957   MachineFunction *MF = BB->getParent();
18958   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18959   DebugLoc DL = MI->getDebugLoc();
18960   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18961
18962   assert(MF->shouldSplitStack());
18963
18964   const bool Is64Bit = Subtarget->is64Bit();
18965   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18966
18967   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18968   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18969
18970   // BB:
18971   //  ... [Till the alloca]
18972   // If stacklet is not large enough, jump to mallocMBB
18973   //
18974   // bumpMBB:
18975   //  Allocate by subtracting from RSP
18976   //  Jump to continueMBB
18977   //
18978   // mallocMBB:
18979   //  Allocate by call to runtime
18980   //
18981   // continueMBB:
18982   //  ...
18983   //  [rest of original BB]
18984   //
18985
18986   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18987   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18988   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18989
18990   MachineRegisterInfo &MRI = MF->getRegInfo();
18991   const TargetRegisterClass *AddrRegClass =
18992     getRegClassFor(getPointerTy());
18993
18994   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18995     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18996     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18997     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18998     sizeVReg = MI->getOperand(1).getReg(),
18999     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19000
19001   MachineFunction::iterator MBBIter = BB;
19002   ++MBBIter;
19003
19004   MF->insert(MBBIter, bumpMBB);
19005   MF->insert(MBBIter, mallocMBB);
19006   MF->insert(MBBIter, continueMBB);
19007
19008   continueMBB->splice(continueMBB->begin(), BB,
19009                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19010   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19011
19012   // Add code to the main basic block to check if the stack limit has been hit,
19013   // and if so, jump to mallocMBB otherwise to bumpMBB.
19014   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19015   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19016     .addReg(tmpSPVReg).addReg(sizeVReg);
19017   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19018     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19019     .addReg(SPLimitVReg);
19020   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19021
19022   // bumpMBB simply decreases the stack pointer, since we know the current
19023   // stacklet has enough space.
19024   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19025     .addReg(SPLimitVReg);
19026   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19027     .addReg(SPLimitVReg);
19028   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19029
19030   // Calls into a routine in libgcc to allocate more space from the heap.
19031   const uint32_t *RegMask =
19032       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19033   if (IsLP64) {
19034     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19035       .addReg(sizeVReg);
19036     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19037       .addExternalSymbol("__morestack_allocate_stack_space")
19038       .addRegMask(RegMask)
19039       .addReg(X86::RDI, RegState::Implicit)
19040       .addReg(X86::RAX, RegState::ImplicitDefine);
19041   } else if (Is64Bit) {
19042     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19043       .addReg(sizeVReg);
19044     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19045       .addExternalSymbol("__morestack_allocate_stack_space")
19046       .addRegMask(RegMask)
19047       .addReg(X86::EDI, RegState::Implicit)
19048       .addReg(X86::EAX, RegState::ImplicitDefine);
19049   } else {
19050     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19051       .addImm(12);
19052     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19053     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19054       .addExternalSymbol("__morestack_allocate_stack_space")
19055       .addRegMask(RegMask)
19056       .addReg(X86::EAX, RegState::ImplicitDefine);
19057   }
19058
19059   if (!Is64Bit)
19060     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19061       .addImm(16);
19062
19063   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19064     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19065   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19066
19067   // Set up the CFG correctly.
19068   BB->addSuccessor(bumpMBB);
19069   BB->addSuccessor(mallocMBB);
19070   mallocMBB->addSuccessor(continueMBB);
19071   bumpMBB->addSuccessor(continueMBB);
19072
19073   // Take care of the PHI nodes.
19074   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19075           MI->getOperand(0).getReg())
19076     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19077     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19078
19079   // Delete the original pseudo instruction.
19080   MI->eraseFromParent();
19081
19082   // And we're done.
19083   return continueMBB;
19084 }
19085
19086 MachineBasicBlock *
19087 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19088                                         MachineBasicBlock *BB) const {
19089   DebugLoc DL = MI->getDebugLoc();
19090
19091   assert(!Subtarget->isTargetMachO());
19092
19093   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19094
19095   MI->eraseFromParent();   // The pseudo instruction is gone now.
19096   return BB;
19097 }
19098
19099 MachineBasicBlock *
19100 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19101                                       MachineBasicBlock *BB) const {
19102   // This is pretty easy.  We're taking the value that we received from
19103   // our load from the relocation, sticking it in either RDI (x86-64)
19104   // or EAX and doing an indirect call.  The return value will then
19105   // be in the normal return register.
19106   MachineFunction *F = BB->getParent();
19107   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19108   DebugLoc DL = MI->getDebugLoc();
19109
19110   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19111   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19112
19113   // Get a register mask for the lowered call.
19114   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19115   // proper register mask.
19116   const uint32_t *RegMask =
19117       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19118   if (Subtarget->is64Bit()) {
19119     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19120                                       TII->get(X86::MOV64rm), X86::RDI)
19121     .addReg(X86::RIP)
19122     .addImm(0).addReg(0)
19123     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19124                       MI->getOperand(3).getTargetFlags())
19125     .addReg(0);
19126     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19127     addDirectMem(MIB, X86::RDI);
19128     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19129   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19130     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19131                                       TII->get(X86::MOV32rm), X86::EAX)
19132     .addReg(0)
19133     .addImm(0).addReg(0)
19134     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19135                       MI->getOperand(3).getTargetFlags())
19136     .addReg(0);
19137     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19138     addDirectMem(MIB, X86::EAX);
19139     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19140   } else {
19141     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19142                                       TII->get(X86::MOV32rm), X86::EAX)
19143     .addReg(TII->getGlobalBaseReg(F))
19144     .addImm(0).addReg(0)
19145     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19146                       MI->getOperand(3).getTargetFlags())
19147     .addReg(0);
19148     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19149     addDirectMem(MIB, X86::EAX);
19150     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19151   }
19152
19153   MI->eraseFromParent(); // The pseudo instruction is gone now.
19154   return BB;
19155 }
19156
19157 MachineBasicBlock *
19158 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19159                                     MachineBasicBlock *MBB) const {
19160   DebugLoc DL = MI->getDebugLoc();
19161   MachineFunction *MF = MBB->getParent();
19162   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19163   MachineRegisterInfo &MRI = MF->getRegInfo();
19164
19165   const BasicBlock *BB = MBB->getBasicBlock();
19166   MachineFunction::iterator I = MBB;
19167   ++I;
19168
19169   // Memory Reference
19170   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19171   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19172
19173   unsigned DstReg;
19174   unsigned MemOpndSlot = 0;
19175
19176   unsigned CurOp = 0;
19177
19178   DstReg = MI->getOperand(CurOp++).getReg();
19179   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19180   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19181   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19182   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19183
19184   MemOpndSlot = CurOp;
19185
19186   MVT PVT = getPointerTy();
19187   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19188          "Invalid Pointer Size!");
19189
19190   // For v = setjmp(buf), we generate
19191   //
19192   // thisMBB:
19193   //  buf[LabelOffset] = restoreMBB
19194   //  SjLjSetup restoreMBB
19195   //
19196   // mainMBB:
19197   //  v_main = 0
19198   //
19199   // sinkMBB:
19200   //  v = phi(main, restore)
19201   //
19202   // restoreMBB:
19203   //  if base pointer being used, load it from frame
19204   //  v_restore = 1
19205
19206   MachineBasicBlock *thisMBB = MBB;
19207   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19208   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19209   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19210   MF->insert(I, mainMBB);
19211   MF->insert(I, sinkMBB);
19212   MF->push_back(restoreMBB);
19213
19214   MachineInstrBuilder MIB;
19215
19216   // Transfer the remainder of BB and its successor edges to sinkMBB.
19217   sinkMBB->splice(sinkMBB->begin(), MBB,
19218                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19219   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19220
19221   // thisMBB:
19222   unsigned PtrStoreOpc = 0;
19223   unsigned LabelReg = 0;
19224   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19225   Reloc::Model RM = MF->getTarget().getRelocationModel();
19226   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19227                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19228
19229   // Prepare IP either in reg or imm.
19230   if (!UseImmLabel) {
19231     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19232     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19233     LabelReg = MRI.createVirtualRegister(PtrRC);
19234     if (Subtarget->is64Bit()) {
19235       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19236               .addReg(X86::RIP)
19237               .addImm(0)
19238               .addReg(0)
19239               .addMBB(restoreMBB)
19240               .addReg(0);
19241     } else {
19242       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19243       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19244               .addReg(XII->getGlobalBaseReg(MF))
19245               .addImm(0)
19246               .addReg(0)
19247               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19248               .addReg(0);
19249     }
19250   } else
19251     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19252   // Store IP
19253   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19254   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19255     if (i == X86::AddrDisp)
19256       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19257     else
19258       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19259   }
19260   if (!UseImmLabel)
19261     MIB.addReg(LabelReg);
19262   else
19263     MIB.addMBB(restoreMBB);
19264   MIB.setMemRefs(MMOBegin, MMOEnd);
19265   // Setup
19266   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19267           .addMBB(restoreMBB);
19268
19269   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19270   MIB.addRegMask(RegInfo->getNoPreservedMask());
19271   thisMBB->addSuccessor(mainMBB);
19272   thisMBB->addSuccessor(restoreMBB);
19273
19274   // mainMBB:
19275   //  EAX = 0
19276   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19277   mainMBB->addSuccessor(sinkMBB);
19278
19279   // sinkMBB:
19280   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19281           TII->get(X86::PHI), DstReg)
19282     .addReg(mainDstReg).addMBB(mainMBB)
19283     .addReg(restoreDstReg).addMBB(restoreMBB);
19284
19285   // restoreMBB:
19286   if (RegInfo->hasBasePointer(*MF)) {
19287     const bool Uses64BitFramePtr =
19288         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19289     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19290     X86FI->setRestoreBasePointer(MF);
19291     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19292     unsigned BasePtr = RegInfo->getBaseRegister();
19293     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19294     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19295                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19296       .setMIFlag(MachineInstr::FrameSetup);
19297   }
19298   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19299   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19300   restoreMBB->addSuccessor(sinkMBB);
19301
19302   MI->eraseFromParent();
19303   return sinkMBB;
19304 }
19305
19306 MachineBasicBlock *
19307 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19308                                      MachineBasicBlock *MBB) const {
19309   DebugLoc DL = MI->getDebugLoc();
19310   MachineFunction *MF = MBB->getParent();
19311   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19312   MachineRegisterInfo &MRI = MF->getRegInfo();
19313
19314   // Memory Reference
19315   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19316   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19317
19318   MVT PVT = getPointerTy();
19319   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19320          "Invalid Pointer Size!");
19321
19322   const TargetRegisterClass *RC =
19323     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19324   unsigned Tmp = MRI.createVirtualRegister(RC);
19325   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19326   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19327   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19328   unsigned SP = RegInfo->getStackRegister();
19329
19330   MachineInstrBuilder MIB;
19331
19332   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19333   const int64_t SPOffset = 2 * PVT.getStoreSize();
19334
19335   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19336   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19337
19338   // Reload FP
19339   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19340   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19341     MIB.addOperand(MI->getOperand(i));
19342   MIB.setMemRefs(MMOBegin, MMOEnd);
19343   // Reload IP
19344   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19345   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19346     if (i == X86::AddrDisp)
19347       MIB.addDisp(MI->getOperand(i), LabelOffset);
19348     else
19349       MIB.addOperand(MI->getOperand(i));
19350   }
19351   MIB.setMemRefs(MMOBegin, MMOEnd);
19352   // Reload SP
19353   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19354   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19355     if (i == X86::AddrDisp)
19356       MIB.addDisp(MI->getOperand(i), SPOffset);
19357     else
19358       MIB.addOperand(MI->getOperand(i));
19359   }
19360   MIB.setMemRefs(MMOBegin, MMOEnd);
19361   // Jump
19362   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19363
19364   MI->eraseFromParent();
19365   return MBB;
19366 }
19367
19368 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19369 // accumulator loops. Writing back to the accumulator allows the coalescer
19370 // to remove extra copies in the loop.
19371 MachineBasicBlock *
19372 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19373                                  MachineBasicBlock *MBB) const {
19374   MachineOperand &AddendOp = MI->getOperand(3);
19375
19376   // Bail out early if the addend isn't a register - we can't switch these.
19377   if (!AddendOp.isReg())
19378     return MBB;
19379
19380   MachineFunction &MF = *MBB->getParent();
19381   MachineRegisterInfo &MRI = MF.getRegInfo();
19382
19383   // Check whether the addend is defined by a PHI:
19384   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19385   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19386   if (!AddendDef.isPHI())
19387     return MBB;
19388
19389   // Look for the following pattern:
19390   // loop:
19391   //   %addend = phi [%entry, 0], [%loop, %result]
19392   //   ...
19393   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19394
19395   // Replace with:
19396   //   loop:
19397   //   %addend = phi [%entry, 0], [%loop, %result]
19398   //   ...
19399   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19400
19401   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19402     assert(AddendDef.getOperand(i).isReg());
19403     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19404     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19405     if (&PHISrcInst == MI) {
19406       // Found a matching instruction.
19407       unsigned NewFMAOpc = 0;
19408       switch (MI->getOpcode()) {
19409         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19410         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19411         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19412         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19413         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19414         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19415         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19416         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19417         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19418         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19419         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19420         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19421         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19422         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19423         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19424         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19425         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19426         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19427         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19428         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19429
19430         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19431         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19432         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19433         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19434         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19435         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19436         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19437         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19438         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19439         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19440         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19441         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19442         default: llvm_unreachable("Unrecognized FMA variant.");
19443       }
19444
19445       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19446       MachineInstrBuilder MIB =
19447         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19448         .addOperand(MI->getOperand(0))
19449         .addOperand(MI->getOperand(3))
19450         .addOperand(MI->getOperand(2))
19451         .addOperand(MI->getOperand(1));
19452       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19453       MI->eraseFromParent();
19454     }
19455   }
19456
19457   return MBB;
19458 }
19459
19460 MachineBasicBlock *
19461 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19462                                                MachineBasicBlock *BB) const {
19463   switch (MI->getOpcode()) {
19464   default: llvm_unreachable("Unexpected instr type to insert");
19465   case X86::TAILJMPd64:
19466   case X86::TAILJMPr64:
19467   case X86::TAILJMPm64:
19468   case X86::TAILJMPd64_REX:
19469   case X86::TAILJMPr64_REX:
19470   case X86::TAILJMPm64_REX:
19471     llvm_unreachable("TAILJMP64 would not be touched here.");
19472   case X86::TCRETURNdi64:
19473   case X86::TCRETURNri64:
19474   case X86::TCRETURNmi64:
19475     return BB;
19476   case X86::WIN_ALLOCA:
19477     return EmitLoweredWinAlloca(MI, BB);
19478   case X86::SEG_ALLOCA_32:
19479   case X86::SEG_ALLOCA_64:
19480     return EmitLoweredSegAlloca(MI, BB);
19481   case X86::TLSCall_32:
19482   case X86::TLSCall_64:
19483     return EmitLoweredTLSCall(MI, BB);
19484   case X86::CMOV_GR8:
19485   case X86::CMOV_FR32:
19486   case X86::CMOV_FR64:
19487   case X86::CMOV_V4F32:
19488   case X86::CMOV_V2F64:
19489   case X86::CMOV_V2I64:
19490   case X86::CMOV_V8F32:
19491   case X86::CMOV_V4F64:
19492   case X86::CMOV_V4I64:
19493   case X86::CMOV_V16F32:
19494   case X86::CMOV_V8F64:
19495   case X86::CMOV_V8I64:
19496   case X86::CMOV_GR16:
19497   case X86::CMOV_GR32:
19498   case X86::CMOV_RFP32:
19499   case X86::CMOV_RFP64:
19500   case X86::CMOV_RFP80:
19501   case X86::CMOV_V8I1:
19502   case X86::CMOV_V16I1:
19503   case X86::CMOV_V32I1:
19504   case X86::CMOV_V64I1:
19505     return EmitLoweredSelect(MI, BB);
19506
19507   case X86::FP32_TO_INT16_IN_MEM:
19508   case X86::FP32_TO_INT32_IN_MEM:
19509   case X86::FP32_TO_INT64_IN_MEM:
19510   case X86::FP64_TO_INT16_IN_MEM:
19511   case X86::FP64_TO_INT32_IN_MEM:
19512   case X86::FP64_TO_INT64_IN_MEM:
19513   case X86::FP80_TO_INT16_IN_MEM:
19514   case X86::FP80_TO_INT32_IN_MEM:
19515   case X86::FP80_TO_INT64_IN_MEM: {
19516     MachineFunction *F = BB->getParent();
19517     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19518     DebugLoc DL = MI->getDebugLoc();
19519
19520     // Change the floating point control register to use "round towards zero"
19521     // mode when truncating to an integer value.
19522     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19523     addFrameReference(BuildMI(*BB, MI, DL,
19524                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19525
19526     // Load the old value of the high byte of the control word...
19527     unsigned OldCW =
19528       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19529     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19530                       CWFrameIdx);
19531
19532     // Set the high part to be round to zero...
19533     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19534       .addImm(0xC7F);
19535
19536     // Reload the modified control word now...
19537     addFrameReference(BuildMI(*BB, MI, DL,
19538                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19539
19540     // Restore the memory image of control word to original value
19541     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19542       .addReg(OldCW);
19543
19544     // Get the X86 opcode to use.
19545     unsigned Opc;
19546     switch (MI->getOpcode()) {
19547     default: llvm_unreachable("illegal opcode!");
19548     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19549     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19550     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19551     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19552     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19553     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19554     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19555     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19556     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19557     }
19558
19559     X86AddressMode AM;
19560     MachineOperand &Op = MI->getOperand(0);
19561     if (Op.isReg()) {
19562       AM.BaseType = X86AddressMode::RegBase;
19563       AM.Base.Reg = Op.getReg();
19564     } else {
19565       AM.BaseType = X86AddressMode::FrameIndexBase;
19566       AM.Base.FrameIndex = Op.getIndex();
19567     }
19568     Op = MI->getOperand(1);
19569     if (Op.isImm())
19570       AM.Scale = Op.getImm();
19571     Op = MI->getOperand(2);
19572     if (Op.isImm())
19573       AM.IndexReg = Op.getImm();
19574     Op = MI->getOperand(3);
19575     if (Op.isGlobal()) {
19576       AM.GV = Op.getGlobal();
19577     } else {
19578       AM.Disp = Op.getImm();
19579     }
19580     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19581                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19582
19583     // Reload the original control word now.
19584     addFrameReference(BuildMI(*BB, MI, DL,
19585                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19586
19587     MI->eraseFromParent();   // The pseudo instruction is gone now.
19588     return BB;
19589   }
19590     // String/text processing lowering.
19591   case X86::PCMPISTRM128REG:
19592   case X86::VPCMPISTRM128REG:
19593   case X86::PCMPISTRM128MEM:
19594   case X86::VPCMPISTRM128MEM:
19595   case X86::PCMPESTRM128REG:
19596   case X86::VPCMPESTRM128REG:
19597   case X86::PCMPESTRM128MEM:
19598   case X86::VPCMPESTRM128MEM:
19599     assert(Subtarget->hasSSE42() &&
19600            "Target must have SSE4.2 or AVX features enabled");
19601     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19602
19603   // String/text processing lowering.
19604   case X86::PCMPISTRIREG:
19605   case X86::VPCMPISTRIREG:
19606   case X86::PCMPISTRIMEM:
19607   case X86::VPCMPISTRIMEM:
19608   case X86::PCMPESTRIREG:
19609   case X86::VPCMPESTRIREG:
19610   case X86::PCMPESTRIMEM:
19611   case X86::VPCMPESTRIMEM:
19612     assert(Subtarget->hasSSE42() &&
19613            "Target must have SSE4.2 or AVX features enabled");
19614     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19615
19616   // Thread synchronization.
19617   case X86::MONITOR:
19618     return EmitMonitor(MI, BB, Subtarget);
19619
19620   // xbegin
19621   case X86::XBEGIN:
19622     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19623
19624   case X86::VASTART_SAVE_XMM_REGS:
19625     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19626
19627   case X86::VAARG_64:
19628     return EmitVAARG64WithCustomInserter(MI, BB);
19629
19630   case X86::EH_SjLj_SetJmp32:
19631   case X86::EH_SjLj_SetJmp64:
19632     return emitEHSjLjSetJmp(MI, BB);
19633
19634   case X86::EH_SjLj_LongJmp32:
19635   case X86::EH_SjLj_LongJmp64:
19636     return emitEHSjLjLongJmp(MI, BB);
19637
19638   case TargetOpcode::STATEPOINT:
19639     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19640     // this point in the process.  We diverge later.
19641     return emitPatchPoint(MI, BB);
19642
19643   case TargetOpcode::STACKMAP:
19644   case TargetOpcode::PATCHPOINT:
19645     return emitPatchPoint(MI, BB);
19646
19647   case X86::VFMADDPDr213r:
19648   case X86::VFMADDPSr213r:
19649   case X86::VFMADDSDr213r:
19650   case X86::VFMADDSSr213r:
19651   case X86::VFMSUBPDr213r:
19652   case X86::VFMSUBPSr213r:
19653   case X86::VFMSUBSDr213r:
19654   case X86::VFMSUBSSr213r:
19655   case X86::VFNMADDPDr213r:
19656   case X86::VFNMADDPSr213r:
19657   case X86::VFNMADDSDr213r:
19658   case X86::VFNMADDSSr213r:
19659   case X86::VFNMSUBPDr213r:
19660   case X86::VFNMSUBPSr213r:
19661   case X86::VFNMSUBSDr213r:
19662   case X86::VFNMSUBSSr213r:
19663   case X86::VFMADDSUBPDr213r:
19664   case X86::VFMADDSUBPSr213r:
19665   case X86::VFMSUBADDPDr213r:
19666   case X86::VFMSUBADDPSr213r:
19667   case X86::VFMADDPDr213rY:
19668   case X86::VFMADDPSr213rY:
19669   case X86::VFMSUBPDr213rY:
19670   case X86::VFMSUBPSr213rY:
19671   case X86::VFNMADDPDr213rY:
19672   case X86::VFNMADDPSr213rY:
19673   case X86::VFNMSUBPDr213rY:
19674   case X86::VFNMSUBPSr213rY:
19675   case X86::VFMADDSUBPDr213rY:
19676   case X86::VFMADDSUBPSr213rY:
19677   case X86::VFMSUBADDPDr213rY:
19678   case X86::VFMSUBADDPSr213rY:
19679     return emitFMA3Instr(MI, BB);
19680   }
19681 }
19682
19683 //===----------------------------------------------------------------------===//
19684 //                           X86 Optimization Hooks
19685 //===----------------------------------------------------------------------===//
19686
19687 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19688                                                       APInt &KnownZero,
19689                                                       APInt &KnownOne,
19690                                                       const SelectionDAG &DAG,
19691                                                       unsigned Depth) const {
19692   unsigned BitWidth = KnownZero.getBitWidth();
19693   unsigned Opc = Op.getOpcode();
19694   assert((Opc >= ISD::BUILTIN_OP_END ||
19695           Opc == ISD::INTRINSIC_WO_CHAIN ||
19696           Opc == ISD::INTRINSIC_W_CHAIN ||
19697           Opc == ISD::INTRINSIC_VOID) &&
19698          "Should use MaskedValueIsZero if you don't know whether Op"
19699          " is a target node!");
19700
19701   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19702   switch (Opc) {
19703   default: break;
19704   case X86ISD::ADD:
19705   case X86ISD::SUB:
19706   case X86ISD::ADC:
19707   case X86ISD::SBB:
19708   case X86ISD::SMUL:
19709   case X86ISD::UMUL:
19710   case X86ISD::INC:
19711   case X86ISD::DEC:
19712   case X86ISD::OR:
19713   case X86ISD::XOR:
19714   case X86ISD::AND:
19715     // These nodes' second result is a boolean.
19716     if (Op.getResNo() == 0)
19717       break;
19718     // Fallthrough
19719   case X86ISD::SETCC:
19720     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19721     break;
19722   case ISD::INTRINSIC_WO_CHAIN: {
19723     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19724     unsigned NumLoBits = 0;
19725     switch (IntId) {
19726     default: break;
19727     case Intrinsic::x86_sse_movmsk_ps:
19728     case Intrinsic::x86_avx_movmsk_ps_256:
19729     case Intrinsic::x86_sse2_movmsk_pd:
19730     case Intrinsic::x86_avx_movmsk_pd_256:
19731     case Intrinsic::x86_mmx_pmovmskb:
19732     case Intrinsic::x86_sse2_pmovmskb_128:
19733     case Intrinsic::x86_avx2_pmovmskb: {
19734       // High bits of movmskp{s|d}, pmovmskb are known zero.
19735       switch (IntId) {
19736         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19737         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19738         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19739         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19740         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19741         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19742         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19743         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19744       }
19745       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19746       break;
19747     }
19748     }
19749     break;
19750   }
19751   }
19752 }
19753
19754 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19755   SDValue Op,
19756   const SelectionDAG &,
19757   unsigned Depth) const {
19758   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19759   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19760     return Op.getValueType().getScalarType().getSizeInBits();
19761
19762   // Fallback case.
19763   return 1;
19764 }
19765
19766 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19767 /// node is a GlobalAddress + offset.
19768 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19769                                        const GlobalValue* &GA,
19770                                        int64_t &Offset) const {
19771   if (N->getOpcode() == X86ISD::Wrapper) {
19772     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19773       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19774       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19775       return true;
19776     }
19777   }
19778   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19779 }
19780
19781 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19782 /// same as extracting the high 128-bit part of 256-bit vector and then
19783 /// inserting the result into the low part of a new 256-bit vector
19784 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19785   EVT VT = SVOp->getValueType(0);
19786   unsigned NumElems = VT.getVectorNumElements();
19787
19788   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19789   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19790     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19791         SVOp->getMaskElt(j) >= 0)
19792       return false;
19793
19794   return true;
19795 }
19796
19797 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19798 /// same as extracting the low 128-bit part of 256-bit vector and then
19799 /// inserting the result into the high part of a new 256-bit vector
19800 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19801   EVT VT = SVOp->getValueType(0);
19802   unsigned NumElems = VT.getVectorNumElements();
19803
19804   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19805   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19806     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19807         SVOp->getMaskElt(j) >= 0)
19808       return false;
19809
19810   return true;
19811 }
19812
19813 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19814 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19815                                         TargetLowering::DAGCombinerInfo &DCI,
19816                                         const X86Subtarget* Subtarget) {
19817   SDLoc dl(N);
19818   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19819   SDValue V1 = SVOp->getOperand(0);
19820   SDValue V2 = SVOp->getOperand(1);
19821   EVT VT = SVOp->getValueType(0);
19822   unsigned NumElems = VT.getVectorNumElements();
19823
19824   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19825       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19826     //
19827     //                   0,0,0,...
19828     //                      |
19829     //    V      UNDEF    BUILD_VECTOR    UNDEF
19830     //     \      /           \           /
19831     //  CONCAT_VECTOR         CONCAT_VECTOR
19832     //         \                  /
19833     //          \                /
19834     //          RESULT: V + zero extended
19835     //
19836     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19837         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19838         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19839       return SDValue();
19840
19841     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19842       return SDValue();
19843
19844     // To match the shuffle mask, the first half of the mask should
19845     // be exactly the first vector, and all the rest a splat with the
19846     // first element of the second one.
19847     for (unsigned i = 0; i != NumElems/2; ++i)
19848       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19849           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19850         return SDValue();
19851
19852     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19853     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19854       if (Ld->hasNUsesOfValue(1, 0)) {
19855         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19856         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19857         SDValue ResNode =
19858           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19859                                   Ld->getMemoryVT(),
19860                                   Ld->getPointerInfo(),
19861                                   Ld->getAlignment(),
19862                                   false/*isVolatile*/, true/*ReadMem*/,
19863                                   false/*WriteMem*/);
19864
19865         // Make sure the newly-created LOAD is in the same position as Ld in
19866         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19867         // and update uses of Ld's output chain to use the TokenFactor.
19868         if (Ld->hasAnyUseOfValue(1)) {
19869           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19870                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19871           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19872           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19873                                  SDValue(ResNode.getNode(), 1));
19874         }
19875
19876         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19877       }
19878     }
19879
19880     // Emit a zeroed vector and insert the desired subvector on its
19881     // first half.
19882     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19883     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19884     return DCI.CombineTo(N, InsV);
19885   }
19886
19887   //===--------------------------------------------------------------------===//
19888   // Combine some shuffles into subvector extracts and inserts:
19889   //
19890
19891   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19892   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19893     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19894     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19895     return DCI.CombineTo(N, InsV);
19896   }
19897
19898   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19899   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19900     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19901     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19902     return DCI.CombineTo(N, InsV);
19903   }
19904
19905   return SDValue();
19906 }
19907
19908 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19909 /// possible.
19910 ///
19911 /// This is the leaf of the recursive combinine below. When we have found some
19912 /// chain of single-use x86 shuffle instructions and accumulated the combined
19913 /// shuffle mask represented by them, this will try to pattern match that mask
19914 /// into either a single instruction if there is a special purpose instruction
19915 /// for this operation, or into a PSHUFB instruction which is a fully general
19916 /// instruction but should only be used to replace chains over a certain depth.
19917 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19918                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19919                                    TargetLowering::DAGCombinerInfo &DCI,
19920                                    const X86Subtarget *Subtarget) {
19921   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19922
19923   // Find the operand that enters the chain. Note that multiple uses are OK
19924   // here, we're not going to remove the operand we find.
19925   SDValue Input = Op.getOperand(0);
19926   while (Input.getOpcode() == ISD::BITCAST)
19927     Input = Input.getOperand(0);
19928
19929   MVT VT = Input.getSimpleValueType();
19930   MVT RootVT = Root.getSimpleValueType();
19931   SDLoc DL(Root);
19932
19933   // Just remove no-op shuffle masks.
19934   if (Mask.size() == 1) {
19935     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19936                   /*AddTo*/ true);
19937     return true;
19938   }
19939
19940   // Use the float domain if the operand type is a floating point type.
19941   bool FloatDomain = VT.isFloatingPoint();
19942
19943   // For floating point shuffles, we don't have free copies in the shuffle
19944   // instructions or the ability to load as part of the instruction, so
19945   // canonicalize their shuffles to UNPCK or MOV variants.
19946   //
19947   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19948   // vectors because it can have a load folded into it that UNPCK cannot. This
19949   // doesn't preclude something switching to the shorter encoding post-RA.
19950   //
19951   // FIXME: Should teach these routines about AVX vector widths.
19952   if (FloatDomain && VT.getSizeInBits() == 128) {
19953     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19954       bool Lo = Mask.equals({0, 0});
19955       unsigned Shuffle;
19956       MVT ShuffleVT;
19957       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19958       // is no slower than UNPCKLPD but has the option to fold the input operand
19959       // into even an unaligned memory load.
19960       if (Lo && Subtarget->hasSSE3()) {
19961         Shuffle = X86ISD::MOVDDUP;
19962         ShuffleVT = MVT::v2f64;
19963       } else {
19964         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19965         // than the UNPCK variants.
19966         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19967         ShuffleVT = MVT::v4f32;
19968       }
19969       if (Depth == 1 && Root->getOpcode() == Shuffle)
19970         return false; // Nothing to do!
19971       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19972       DCI.AddToWorklist(Op.getNode());
19973       if (Shuffle == X86ISD::MOVDDUP)
19974         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19975       else
19976         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19977       DCI.AddToWorklist(Op.getNode());
19978       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19979                     /*AddTo*/ true);
19980       return true;
19981     }
19982     if (Subtarget->hasSSE3() &&
19983         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19984       bool Lo = Mask.equals({0, 0, 2, 2});
19985       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19986       MVT ShuffleVT = MVT::v4f32;
19987       if (Depth == 1 && Root->getOpcode() == Shuffle)
19988         return false; // Nothing to do!
19989       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19990       DCI.AddToWorklist(Op.getNode());
19991       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19992       DCI.AddToWorklist(Op.getNode());
19993       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19994                     /*AddTo*/ true);
19995       return true;
19996     }
19997     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19998       bool Lo = Mask.equals({0, 0, 1, 1});
19999       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20000       MVT ShuffleVT = MVT::v4f32;
20001       if (Depth == 1 && Root->getOpcode() == Shuffle)
20002         return false; // Nothing to do!
20003       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20004       DCI.AddToWorklist(Op.getNode());
20005       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20006       DCI.AddToWorklist(Op.getNode());
20007       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20008                     /*AddTo*/ true);
20009       return true;
20010     }
20011   }
20012
20013   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20014   // variants as none of these have single-instruction variants that are
20015   // superior to the UNPCK formulation.
20016   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20017       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20018        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20019        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20020        Mask.equals(
20021            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20022     bool Lo = Mask[0] == 0;
20023     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20024     if (Depth == 1 && Root->getOpcode() == Shuffle)
20025       return false; // Nothing to do!
20026     MVT ShuffleVT;
20027     switch (Mask.size()) {
20028     case 8:
20029       ShuffleVT = MVT::v8i16;
20030       break;
20031     case 16:
20032       ShuffleVT = MVT::v16i8;
20033       break;
20034     default:
20035       llvm_unreachable("Impossible mask size!");
20036     };
20037     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20038     DCI.AddToWorklist(Op.getNode());
20039     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20040     DCI.AddToWorklist(Op.getNode());
20041     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20042                   /*AddTo*/ true);
20043     return true;
20044   }
20045
20046   // Don't try to re-form single instruction chains under any circumstances now
20047   // that we've done encoding canonicalization for them.
20048   if (Depth < 2)
20049     return false;
20050
20051   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20052   // can replace them with a single PSHUFB instruction profitably. Intel's
20053   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20054   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20055   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20056     SmallVector<SDValue, 16> PSHUFBMask;
20057     int NumBytes = VT.getSizeInBits() / 8;
20058     int Ratio = NumBytes / Mask.size();
20059     for (int i = 0; i < NumBytes; ++i) {
20060       if (Mask[i / Ratio] == SM_SentinelUndef) {
20061         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20062         continue;
20063       }
20064       int M = Mask[i / Ratio] != SM_SentinelZero
20065                   ? Ratio * Mask[i / Ratio] + i % Ratio
20066                   : 255;
20067       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20068     }
20069     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20070     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20071     DCI.AddToWorklist(Op.getNode());
20072     SDValue PSHUFBMaskOp =
20073         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20074     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20075     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20076     DCI.AddToWorklist(Op.getNode());
20077     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20078                   /*AddTo*/ true);
20079     return true;
20080   }
20081
20082   // Failed to find any combines.
20083   return false;
20084 }
20085
20086 /// \brief Fully generic combining of x86 shuffle instructions.
20087 ///
20088 /// This should be the last combine run over the x86 shuffle instructions. Once
20089 /// they have been fully optimized, this will recursively consider all chains
20090 /// of single-use shuffle instructions, build a generic model of the cumulative
20091 /// shuffle operation, and check for simpler instructions which implement this
20092 /// operation. We use this primarily for two purposes:
20093 ///
20094 /// 1) Collapse generic shuffles to specialized single instructions when
20095 ///    equivalent. In most cases, this is just an encoding size win, but
20096 ///    sometimes we will collapse multiple generic shuffles into a single
20097 ///    special-purpose shuffle.
20098 /// 2) Look for sequences of shuffle instructions with 3 or more total
20099 ///    instructions, and replace them with the slightly more expensive SSSE3
20100 ///    PSHUFB instruction if available. We do this as the last combining step
20101 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20102 ///    a suitable short sequence of other instructions. The PHUFB will either
20103 ///    use a register or have to read from memory and so is slightly (but only
20104 ///    slightly) more expensive than the other shuffle instructions.
20105 ///
20106 /// Because this is inherently a quadratic operation (for each shuffle in
20107 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20108 /// This should never be an issue in practice as the shuffle lowering doesn't
20109 /// produce sequences of more than 8 instructions.
20110 ///
20111 /// FIXME: We will currently miss some cases where the redundant shuffling
20112 /// would simplify under the threshold for PSHUFB formation because of
20113 /// combine-ordering. To fix this, we should do the redundant instruction
20114 /// combining in this recursive walk.
20115 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20116                                           ArrayRef<int> RootMask,
20117                                           int Depth, bool HasPSHUFB,
20118                                           SelectionDAG &DAG,
20119                                           TargetLowering::DAGCombinerInfo &DCI,
20120                                           const X86Subtarget *Subtarget) {
20121   // Bound the depth of our recursive combine because this is ultimately
20122   // quadratic in nature.
20123   if (Depth > 8)
20124     return false;
20125
20126   // Directly rip through bitcasts to find the underlying operand.
20127   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20128     Op = Op.getOperand(0);
20129
20130   MVT VT = Op.getSimpleValueType();
20131   if (!VT.isVector())
20132     return false; // Bail if we hit a non-vector.
20133
20134   assert(Root.getSimpleValueType().isVector() &&
20135          "Shuffles operate on vector types!");
20136   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20137          "Can only combine shuffles of the same vector register size.");
20138
20139   if (!isTargetShuffle(Op.getOpcode()))
20140     return false;
20141   SmallVector<int, 16> OpMask;
20142   bool IsUnary;
20143   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20144   // We only can combine unary shuffles which we can decode the mask for.
20145   if (!HaveMask || !IsUnary)
20146     return false;
20147
20148   assert(VT.getVectorNumElements() == OpMask.size() &&
20149          "Different mask size from vector size!");
20150   assert(((RootMask.size() > OpMask.size() &&
20151            RootMask.size() % OpMask.size() == 0) ||
20152           (OpMask.size() > RootMask.size() &&
20153            OpMask.size() % RootMask.size() == 0) ||
20154           OpMask.size() == RootMask.size()) &&
20155          "The smaller number of elements must divide the larger.");
20156   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20157   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20158   assert(((RootRatio == 1 && OpRatio == 1) ||
20159           (RootRatio == 1) != (OpRatio == 1)) &&
20160          "Must not have a ratio for both incoming and op masks!");
20161
20162   SmallVector<int, 16> Mask;
20163   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20164
20165   // Merge this shuffle operation's mask into our accumulated mask. Note that
20166   // this shuffle's mask will be the first applied to the input, followed by the
20167   // root mask to get us all the way to the root value arrangement. The reason
20168   // for this order is that we are recursing up the operation chain.
20169   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20170     int RootIdx = i / RootRatio;
20171     if (RootMask[RootIdx] < 0) {
20172       // This is a zero or undef lane, we're done.
20173       Mask.push_back(RootMask[RootIdx]);
20174       continue;
20175     }
20176
20177     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20178     int OpIdx = RootMaskedIdx / OpRatio;
20179     if (OpMask[OpIdx] < 0) {
20180       // The incoming lanes are zero or undef, it doesn't matter which ones we
20181       // are using.
20182       Mask.push_back(OpMask[OpIdx]);
20183       continue;
20184     }
20185
20186     // Ok, we have non-zero lanes, map them through.
20187     Mask.push_back(OpMask[OpIdx] * OpRatio +
20188                    RootMaskedIdx % OpRatio);
20189   }
20190
20191   // See if we can recurse into the operand to combine more things.
20192   switch (Op.getOpcode()) {
20193     case X86ISD::PSHUFB:
20194       HasPSHUFB = true;
20195     case X86ISD::PSHUFD:
20196     case X86ISD::PSHUFHW:
20197     case X86ISD::PSHUFLW:
20198       if (Op.getOperand(0).hasOneUse() &&
20199           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20200                                         HasPSHUFB, DAG, DCI, Subtarget))
20201         return true;
20202       break;
20203
20204     case X86ISD::UNPCKL:
20205     case X86ISD::UNPCKH:
20206       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20207       // We can't check for single use, we have to check that this shuffle is the only user.
20208       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20209           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20210                                         HasPSHUFB, DAG, DCI, Subtarget))
20211           return true;
20212       break;
20213   }
20214
20215   // Minor canonicalization of the accumulated shuffle mask to make it easier
20216   // to match below. All this does is detect masks with squential pairs of
20217   // elements, and shrink them to the half-width mask. It does this in a loop
20218   // so it will reduce the size of the mask to the minimal width mask which
20219   // performs an equivalent shuffle.
20220   SmallVector<int, 16> WidenedMask;
20221   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20222     Mask = std::move(WidenedMask);
20223     WidenedMask.clear();
20224   }
20225
20226   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20227                                 Subtarget);
20228 }
20229
20230 /// \brief Get the PSHUF-style mask from PSHUF node.
20231 ///
20232 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20233 /// PSHUF-style masks that can be reused with such instructions.
20234 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20235   MVT VT = N.getSimpleValueType();
20236   SmallVector<int, 4> Mask;
20237   bool IsUnary;
20238   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20239   (void)HaveMask;
20240   assert(HaveMask);
20241
20242   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20243   // matter. Check that the upper masks are repeats and remove them.
20244   if (VT.getSizeInBits() > 128) {
20245     int LaneElts = 128 / VT.getScalarSizeInBits();
20246 #ifndef NDEBUG
20247     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20248       for (int j = 0; j < LaneElts; ++j)
20249         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20250                "Mask doesn't repeat in high 128-bit lanes!");
20251 #endif
20252     Mask.resize(LaneElts);
20253   }
20254
20255   switch (N.getOpcode()) {
20256   case X86ISD::PSHUFD:
20257     return Mask;
20258   case X86ISD::PSHUFLW:
20259     Mask.resize(4);
20260     return Mask;
20261   case X86ISD::PSHUFHW:
20262     Mask.erase(Mask.begin(), Mask.begin() + 4);
20263     for (int &M : Mask)
20264       M -= 4;
20265     return Mask;
20266   default:
20267     llvm_unreachable("No valid shuffle instruction found!");
20268   }
20269 }
20270
20271 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20272 ///
20273 /// We walk up the chain and look for a combinable shuffle, skipping over
20274 /// shuffles that we could hoist this shuffle's transformation past without
20275 /// altering anything.
20276 static SDValue
20277 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20278                              SelectionDAG &DAG,
20279                              TargetLowering::DAGCombinerInfo &DCI) {
20280   assert(N.getOpcode() == X86ISD::PSHUFD &&
20281          "Called with something other than an x86 128-bit half shuffle!");
20282   SDLoc DL(N);
20283
20284   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20285   // of the shuffles in the chain so that we can form a fresh chain to replace
20286   // this one.
20287   SmallVector<SDValue, 8> Chain;
20288   SDValue V = N.getOperand(0);
20289   for (; V.hasOneUse(); V = V.getOperand(0)) {
20290     switch (V.getOpcode()) {
20291     default:
20292       return SDValue(); // Nothing combined!
20293
20294     case ISD::BITCAST:
20295       // Skip bitcasts as we always know the type for the target specific
20296       // instructions.
20297       continue;
20298
20299     case X86ISD::PSHUFD:
20300       // Found another dword shuffle.
20301       break;
20302
20303     case X86ISD::PSHUFLW:
20304       // Check that the low words (being shuffled) are the identity in the
20305       // dword shuffle, and the high words are self-contained.
20306       if (Mask[0] != 0 || Mask[1] != 1 ||
20307           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20308         return SDValue();
20309
20310       Chain.push_back(V);
20311       continue;
20312
20313     case X86ISD::PSHUFHW:
20314       // Check that the high words (being shuffled) are the identity in the
20315       // dword shuffle, and the low words are self-contained.
20316       if (Mask[2] != 2 || Mask[3] != 3 ||
20317           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20318         return SDValue();
20319
20320       Chain.push_back(V);
20321       continue;
20322
20323     case X86ISD::UNPCKL:
20324     case X86ISD::UNPCKH:
20325       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20326       // shuffle into a preceding word shuffle.
20327       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20328           V.getSimpleValueType().getScalarType() != MVT::i16)
20329         return SDValue();
20330
20331       // Search for a half-shuffle which we can combine with.
20332       unsigned CombineOp =
20333           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20334       if (V.getOperand(0) != V.getOperand(1) ||
20335           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20336         return SDValue();
20337       Chain.push_back(V);
20338       V = V.getOperand(0);
20339       do {
20340         switch (V.getOpcode()) {
20341         default:
20342           return SDValue(); // Nothing to combine.
20343
20344         case X86ISD::PSHUFLW:
20345         case X86ISD::PSHUFHW:
20346           if (V.getOpcode() == CombineOp)
20347             break;
20348
20349           Chain.push_back(V);
20350
20351           // Fallthrough!
20352         case ISD::BITCAST:
20353           V = V.getOperand(0);
20354           continue;
20355         }
20356         break;
20357       } while (V.hasOneUse());
20358       break;
20359     }
20360     // Break out of the loop if we break out of the switch.
20361     break;
20362   }
20363
20364   if (!V.hasOneUse())
20365     // We fell out of the loop without finding a viable combining instruction.
20366     return SDValue();
20367
20368   // Merge this node's mask and our incoming mask.
20369   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20370   for (int &M : Mask)
20371     M = VMask[M];
20372   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20373                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20374
20375   // Rebuild the chain around this new shuffle.
20376   while (!Chain.empty()) {
20377     SDValue W = Chain.pop_back_val();
20378
20379     if (V.getValueType() != W.getOperand(0).getValueType())
20380       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20381
20382     switch (W.getOpcode()) {
20383     default:
20384       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20385
20386     case X86ISD::UNPCKL:
20387     case X86ISD::UNPCKH:
20388       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20389       break;
20390
20391     case X86ISD::PSHUFD:
20392     case X86ISD::PSHUFLW:
20393     case X86ISD::PSHUFHW:
20394       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20395       break;
20396     }
20397   }
20398   if (V.getValueType() != N.getValueType())
20399     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20400
20401   // Return the new chain to replace N.
20402   return V;
20403 }
20404
20405 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20406 ///
20407 /// We walk up the chain, skipping shuffles of the other half and looking
20408 /// through shuffles which switch halves trying to find a shuffle of the same
20409 /// pair of dwords.
20410 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20411                                         SelectionDAG &DAG,
20412                                         TargetLowering::DAGCombinerInfo &DCI) {
20413   assert(
20414       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20415       "Called with something other than an x86 128-bit half shuffle!");
20416   SDLoc DL(N);
20417   unsigned CombineOpcode = N.getOpcode();
20418
20419   // Walk up a single-use chain looking for a combinable shuffle.
20420   SDValue V = N.getOperand(0);
20421   for (; V.hasOneUse(); V = V.getOperand(0)) {
20422     switch (V.getOpcode()) {
20423     default:
20424       return false; // Nothing combined!
20425
20426     case ISD::BITCAST:
20427       // Skip bitcasts as we always know the type for the target specific
20428       // instructions.
20429       continue;
20430
20431     case X86ISD::PSHUFLW:
20432     case X86ISD::PSHUFHW:
20433       if (V.getOpcode() == CombineOpcode)
20434         break;
20435
20436       // Other-half shuffles are no-ops.
20437       continue;
20438     }
20439     // Break out of the loop if we break out of the switch.
20440     break;
20441   }
20442
20443   if (!V.hasOneUse())
20444     // We fell out of the loop without finding a viable combining instruction.
20445     return false;
20446
20447   // Combine away the bottom node as its shuffle will be accumulated into
20448   // a preceding shuffle.
20449   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20450
20451   // Record the old value.
20452   SDValue Old = V;
20453
20454   // Merge this node's mask and our incoming mask (adjusted to account for all
20455   // the pshufd instructions encountered).
20456   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20457   for (int &M : Mask)
20458     M = VMask[M];
20459   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20460                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20461
20462   // Check that the shuffles didn't cancel each other out. If not, we need to
20463   // combine to the new one.
20464   if (Old != V)
20465     // Replace the combinable shuffle with the combined one, updating all users
20466     // so that we re-evaluate the chain here.
20467     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20468
20469   return true;
20470 }
20471
20472 /// \brief Try to combine x86 target specific shuffles.
20473 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20474                                            TargetLowering::DAGCombinerInfo &DCI,
20475                                            const X86Subtarget *Subtarget) {
20476   SDLoc DL(N);
20477   MVT VT = N.getSimpleValueType();
20478   SmallVector<int, 4> Mask;
20479
20480   switch (N.getOpcode()) {
20481   case X86ISD::PSHUFD:
20482   case X86ISD::PSHUFLW:
20483   case X86ISD::PSHUFHW:
20484     Mask = getPSHUFShuffleMask(N);
20485     assert(Mask.size() == 4);
20486     break;
20487   default:
20488     return SDValue();
20489   }
20490
20491   // Nuke no-op shuffles that show up after combining.
20492   if (isNoopShuffleMask(Mask))
20493     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20494
20495   // Look for simplifications involving one or two shuffle instructions.
20496   SDValue V = N.getOperand(0);
20497   switch (N.getOpcode()) {
20498   default:
20499     break;
20500   case X86ISD::PSHUFLW:
20501   case X86ISD::PSHUFHW:
20502     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20503
20504     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20505       return SDValue(); // We combined away this shuffle, so we're done.
20506
20507     // See if this reduces to a PSHUFD which is no more expensive and can
20508     // combine with more operations. Note that it has to at least flip the
20509     // dwords as otherwise it would have been removed as a no-op.
20510     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20511       int DMask[] = {0, 1, 2, 3};
20512       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20513       DMask[DOffset + 0] = DOffset + 1;
20514       DMask[DOffset + 1] = DOffset + 0;
20515       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20516       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20517       DCI.AddToWorklist(V.getNode());
20518       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20519                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20520       DCI.AddToWorklist(V.getNode());
20521       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20522     }
20523
20524     // Look for shuffle patterns which can be implemented as a single unpack.
20525     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20526     // only works when we have a PSHUFD followed by two half-shuffles.
20527     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20528         (V.getOpcode() == X86ISD::PSHUFLW ||
20529          V.getOpcode() == X86ISD::PSHUFHW) &&
20530         V.getOpcode() != N.getOpcode() &&
20531         V.hasOneUse()) {
20532       SDValue D = V.getOperand(0);
20533       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20534         D = D.getOperand(0);
20535       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20536         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20537         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20538         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20539         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20540         int WordMask[8];
20541         for (int i = 0; i < 4; ++i) {
20542           WordMask[i + NOffset] = Mask[i] + NOffset;
20543           WordMask[i + VOffset] = VMask[i] + VOffset;
20544         }
20545         // Map the word mask through the DWord mask.
20546         int MappedMask[8];
20547         for (int i = 0; i < 8; ++i)
20548           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20549         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20550             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20551           // We can replace all three shuffles with an unpack.
20552           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20553           DCI.AddToWorklist(V.getNode());
20554           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20555                                                 : X86ISD::UNPCKH,
20556                              DL, VT, V, V);
20557         }
20558       }
20559     }
20560
20561     break;
20562
20563   case X86ISD::PSHUFD:
20564     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20565       return NewN;
20566
20567     break;
20568   }
20569
20570   return SDValue();
20571 }
20572
20573 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20574 ///
20575 /// We combine this directly on the abstract vector shuffle nodes so it is
20576 /// easier to generically match. We also insert dummy vector shuffle nodes for
20577 /// the operands which explicitly discard the lanes which are unused by this
20578 /// operation to try to flow through the rest of the combiner the fact that
20579 /// they're unused.
20580 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20581   SDLoc DL(N);
20582   EVT VT = N->getValueType(0);
20583
20584   // We only handle target-independent shuffles.
20585   // FIXME: It would be easy and harmless to use the target shuffle mask
20586   // extraction tool to support more.
20587   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20588     return SDValue();
20589
20590   auto *SVN = cast<ShuffleVectorSDNode>(N);
20591   ArrayRef<int> Mask = SVN->getMask();
20592   SDValue V1 = N->getOperand(0);
20593   SDValue V2 = N->getOperand(1);
20594
20595   // We require the first shuffle operand to be the SUB node, and the second to
20596   // be the ADD node.
20597   // FIXME: We should support the commuted patterns.
20598   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20599     return SDValue();
20600
20601   // If there are other uses of these operations we can't fold them.
20602   if (!V1->hasOneUse() || !V2->hasOneUse())
20603     return SDValue();
20604
20605   // Ensure that both operations have the same operands. Note that we can
20606   // commute the FADD operands.
20607   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20608   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20609       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20610     return SDValue();
20611
20612   // We're looking for blends between FADD and FSUB nodes. We insist on these
20613   // nodes being lined up in a specific expected pattern.
20614   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20615         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20616         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20617     return SDValue();
20618
20619   // Only specific types are legal at this point, assert so we notice if and
20620   // when these change.
20621   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20622           VT == MVT::v4f64) &&
20623          "Unknown vector type encountered!");
20624
20625   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20626 }
20627
20628 /// PerformShuffleCombine - Performs several different shuffle combines.
20629 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20630                                      TargetLowering::DAGCombinerInfo &DCI,
20631                                      const X86Subtarget *Subtarget) {
20632   SDLoc dl(N);
20633   SDValue N0 = N->getOperand(0);
20634   SDValue N1 = N->getOperand(1);
20635   EVT VT = N->getValueType(0);
20636
20637   // Don't create instructions with illegal types after legalize types has run.
20638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20639   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20640     return SDValue();
20641
20642   // If we have legalized the vector types, look for blends of FADD and FSUB
20643   // nodes that we can fuse into an ADDSUB node.
20644   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20645     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20646       return AddSub;
20647
20648   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20649   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20650       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20651     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20652
20653   // During Type Legalization, when promoting illegal vector types,
20654   // the backend might introduce new shuffle dag nodes and bitcasts.
20655   //
20656   // This code performs the following transformation:
20657   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20658   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20659   //
20660   // We do this only if both the bitcast and the BINOP dag nodes have
20661   // one use. Also, perform this transformation only if the new binary
20662   // operation is legal. This is to avoid introducing dag nodes that
20663   // potentially need to be further expanded (or custom lowered) into a
20664   // less optimal sequence of dag nodes.
20665   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20666       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20667       N0.getOpcode() == ISD::BITCAST) {
20668     SDValue BC0 = N0.getOperand(0);
20669     EVT SVT = BC0.getValueType();
20670     unsigned Opcode = BC0.getOpcode();
20671     unsigned NumElts = VT.getVectorNumElements();
20672
20673     if (BC0.hasOneUse() && SVT.isVector() &&
20674         SVT.getVectorNumElements() * 2 == NumElts &&
20675         TLI.isOperationLegal(Opcode, VT)) {
20676       bool CanFold = false;
20677       switch (Opcode) {
20678       default : break;
20679       case ISD::ADD :
20680       case ISD::FADD :
20681       case ISD::SUB :
20682       case ISD::FSUB :
20683       case ISD::MUL :
20684       case ISD::FMUL :
20685         CanFold = true;
20686       }
20687
20688       unsigned SVTNumElts = SVT.getVectorNumElements();
20689       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20690       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20691         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20692       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20693         CanFold = SVOp->getMaskElt(i) < 0;
20694
20695       if (CanFold) {
20696         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20697         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20698         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20699         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20700       }
20701     }
20702   }
20703
20704   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20705   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20706   // consecutive, non-overlapping, and in the right order.
20707   SmallVector<SDValue, 16> Elts;
20708   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20709     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20710
20711   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20712   if (LD.getNode())
20713     return LD;
20714
20715   if (isTargetShuffle(N->getOpcode())) {
20716     SDValue Shuffle =
20717         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20718     if (Shuffle.getNode())
20719       return Shuffle;
20720
20721     // Try recursively combining arbitrary sequences of x86 shuffle
20722     // instructions into higher-order shuffles. We do this after combining
20723     // specific PSHUF instruction sequences into their minimal form so that we
20724     // can evaluate how many specialized shuffle instructions are involved in
20725     // a particular chain.
20726     SmallVector<int, 1> NonceMask; // Just a placeholder.
20727     NonceMask.push_back(0);
20728     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20729                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20730                                       DCI, Subtarget))
20731       return SDValue(); // This routine will use CombineTo to replace N.
20732   }
20733
20734   return SDValue();
20735 }
20736
20737 /// PerformTruncateCombine - Converts truncate operation to
20738 /// a sequence of vector shuffle operations.
20739 /// It is possible when we truncate 256-bit vector to 128-bit vector
20740 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20741                                       TargetLowering::DAGCombinerInfo &DCI,
20742                                       const X86Subtarget *Subtarget)  {
20743   return SDValue();
20744 }
20745
20746 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20747 /// specific shuffle of a load can be folded into a single element load.
20748 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20749 /// shuffles have been custom lowered so we need to handle those here.
20750 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20751                                          TargetLowering::DAGCombinerInfo &DCI) {
20752   if (DCI.isBeforeLegalizeOps())
20753     return SDValue();
20754
20755   SDValue InVec = N->getOperand(0);
20756   SDValue EltNo = N->getOperand(1);
20757
20758   if (!isa<ConstantSDNode>(EltNo))
20759     return SDValue();
20760
20761   EVT OriginalVT = InVec.getValueType();
20762
20763   if (InVec.getOpcode() == ISD::BITCAST) {
20764     // Don't duplicate a load with other uses.
20765     if (!InVec.hasOneUse())
20766       return SDValue();
20767     EVT BCVT = InVec.getOperand(0).getValueType();
20768     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20769       return SDValue();
20770     InVec = InVec.getOperand(0);
20771   }
20772
20773   EVT CurrentVT = InVec.getValueType();
20774
20775   if (!isTargetShuffle(InVec.getOpcode()))
20776     return SDValue();
20777
20778   // Don't duplicate a load with other uses.
20779   if (!InVec.hasOneUse())
20780     return SDValue();
20781
20782   SmallVector<int, 16> ShuffleMask;
20783   bool UnaryShuffle;
20784   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20785                             ShuffleMask, UnaryShuffle))
20786     return SDValue();
20787
20788   // Select the input vector, guarding against out of range extract vector.
20789   unsigned NumElems = CurrentVT.getVectorNumElements();
20790   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20791   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20792   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20793                                          : InVec.getOperand(1);
20794
20795   // If inputs to shuffle are the same for both ops, then allow 2 uses
20796   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20797                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20798
20799   if (LdNode.getOpcode() == ISD::BITCAST) {
20800     // Don't duplicate a load with other uses.
20801     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20802       return SDValue();
20803
20804     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20805     LdNode = LdNode.getOperand(0);
20806   }
20807
20808   if (!ISD::isNormalLoad(LdNode.getNode()))
20809     return SDValue();
20810
20811   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20812
20813   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20814     return SDValue();
20815
20816   EVT EltVT = N->getValueType(0);
20817   // If there's a bitcast before the shuffle, check if the load type and
20818   // alignment is valid.
20819   unsigned Align = LN0->getAlignment();
20820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20821   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20822       EltVT.getTypeForEVT(*DAG.getContext()));
20823
20824   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20825     return SDValue();
20826
20827   // All checks match so transform back to vector_shuffle so that DAG combiner
20828   // can finish the job
20829   SDLoc dl(N);
20830
20831   // Create shuffle node taking into account the case that its a unary shuffle
20832   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20833                                    : InVec.getOperand(1);
20834   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20835                                  InVec.getOperand(0), Shuffle,
20836                                  &ShuffleMask[0]);
20837   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20838   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20839                      EltNo);
20840 }
20841
20842 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20843 /// special and don't usually play with other vector types, it's better to
20844 /// handle them early to be sure we emit efficient code by avoiding
20845 /// store-load conversions.
20846 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20847   if (N->getValueType(0) != MVT::x86mmx ||
20848       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20849       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20850     return SDValue();
20851
20852   SDValue V = N->getOperand(0);
20853   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20854   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20855     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20856                        N->getValueType(0), V.getOperand(0));
20857
20858   return SDValue();
20859 }
20860
20861 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20862 /// generation and convert it from being a bunch of shuffles and extracts
20863 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20864 /// storing the value and loading scalars back, while for x64 we should
20865 /// use 64-bit extracts and shifts.
20866 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20867                                          TargetLowering::DAGCombinerInfo &DCI) {
20868   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20869   if (NewOp.getNode())
20870     return NewOp;
20871
20872   SDValue InputVector = N->getOperand(0);
20873
20874   // Detect mmx to i32 conversion through a v2i32 elt extract.
20875   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20876       N->getValueType(0) == MVT::i32 &&
20877       InputVector.getValueType() == MVT::v2i32) {
20878
20879     // The bitcast source is a direct mmx result.
20880     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20881     if (MMXSrc.getValueType() == MVT::x86mmx)
20882       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20883                          N->getValueType(0),
20884                          InputVector.getNode()->getOperand(0));
20885
20886     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20887     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20888     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20889         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20890         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20891         MMXSrcOp.getValueType() == MVT::v1i64 &&
20892         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20893       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20894                          N->getValueType(0),
20895                          MMXSrcOp.getOperand(0));
20896   }
20897
20898   // Only operate on vectors of 4 elements, where the alternative shuffling
20899   // gets to be more expensive.
20900   if (InputVector.getValueType() != MVT::v4i32)
20901     return SDValue();
20902
20903   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20904   // single use which is a sign-extend or zero-extend, and all elements are
20905   // used.
20906   SmallVector<SDNode *, 4> Uses;
20907   unsigned ExtractedElements = 0;
20908   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20909        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20910     if (UI.getUse().getResNo() != InputVector.getResNo())
20911       return SDValue();
20912
20913     SDNode *Extract = *UI;
20914     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20915       return SDValue();
20916
20917     if (Extract->getValueType(0) != MVT::i32)
20918       return SDValue();
20919     if (!Extract->hasOneUse())
20920       return SDValue();
20921     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20922         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20923       return SDValue();
20924     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20925       return SDValue();
20926
20927     // Record which element was extracted.
20928     ExtractedElements |=
20929       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20930
20931     Uses.push_back(Extract);
20932   }
20933
20934   // If not all the elements were used, this may not be worthwhile.
20935   if (ExtractedElements != 15)
20936     return SDValue();
20937
20938   // Ok, we've now decided to do the transformation.
20939   // If 64-bit shifts are legal, use the extract-shift sequence,
20940   // otherwise bounce the vector off the cache.
20941   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20942   SDValue Vals[4];
20943   SDLoc dl(InputVector);
20944
20945   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20946     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20947     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20948     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20949       DAG.getConstant(0, dl, VecIdxTy));
20950     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20951       DAG.getConstant(1, dl, VecIdxTy));
20952
20953     SDValue ShAmt = DAG.getConstant(32, dl,
20954       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20955     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20956     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20957       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20958     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20959     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20960       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20961   } else {
20962     // Store the value to a temporary stack slot.
20963     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20964     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20965       MachinePointerInfo(), false, false, 0);
20966
20967     EVT ElementType = InputVector.getValueType().getVectorElementType();
20968     unsigned EltSize = ElementType.getSizeInBits() / 8;
20969
20970     // Replace each use (extract) with a load of the appropriate element.
20971     for (unsigned i = 0; i < 4; ++i) {
20972       uint64_t Offset = EltSize * i;
20973       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20974
20975       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20976                                        StackPtr, OffsetVal);
20977
20978       // Load the scalar.
20979       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20980                             ScalarAddr, MachinePointerInfo(),
20981                             false, false, false, 0);
20982
20983     }
20984   }
20985
20986   // Replace the extracts
20987   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20988     UE = Uses.end(); UI != UE; ++UI) {
20989     SDNode *Extract = *UI;
20990
20991     SDValue Idx = Extract->getOperand(1);
20992     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20993     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20994   }
20995
20996   // The replacement was made in place; don't return anything.
20997   return SDValue();
20998 }
20999
21000 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21001 static std::pair<unsigned, bool>
21002 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21003                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21004   if (!VT.isVector())
21005     return std::make_pair(0, false);
21006
21007   bool NeedSplit = false;
21008   switch (VT.getSimpleVT().SimpleTy) {
21009   default: return std::make_pair(0, false);
21010   case MVT::v4i64:
21011   case MVT::v2i64:
21012     if (!Subtarget->hasVLX())
21013       return std::make_pair(0, false);
21014     break;
21015   case MVT::v64i8:
21016   case MVT::v32i16:
21017     if (!Subtarget->hasBWI())
21018       return std::make_pair(0, false);
21019     break;
21020   case MVT::v16i32:
21021   case MVT::v8i64:
21022     if (!Subtarget->hasAVX512())
21023       return std::make_pair(0, false);
21024     break;
21025   case MVT::v32i8:
21026   case MVT::v16i16:
21027   case MVT::v8i32:
21028     if (!Subtarget->hasAVX2())
21029       NeedSplit = true;
21030     if (!Subtarget->hasAVX())
21031       return std::make_pair(0, false);
21032     break;
21033   case MVT::v16i8:
21034   case MVT::v8i16:
21035   case MVT::v4i32:
21036     if (!Subtarget->hasSSE2())
21037       return std::make_pair(0, false);
21038   }
21039
21040   // SSE2 has only a small subset of the operations.
21041   bool hasUnsigned = Subtarget->hasSSE41() ||
21042                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21043   bool hasSigned = Subtarget->hasSSE41() ||
21044                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21045
21046   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21047
21048   unsigned Opc = 0;
21049   // Check for x CC y ? x : y.
21050   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21051       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21052     switch (CC) {
21053     default: break;
21054     case ISD::SETULT:
21055     case ISD::SETULE:
21056       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21057     case ISD::SETUGT:
21058     case ISD::SETUGE:
21059       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21060     case ISD::SETLT:
21061     case ISD::SETLE:
21062       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21063     case ISD::SETGT:
21064     case ISD::SETGE:
21065       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21066     }
21067   // Check for x CC y ? y : x -- a min/max with reversed arms.
21068   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21069              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21070     switch (CC) {
21071     default: break;
21072     case ISD::SETULT:
21073     case ISD::SETULE:
21074       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21075     case ISD::SETUGT:
21076     case ISD::SETUGE:
21077       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21078     case ISD::SETLT:
21079     case ISD::SETLE:
21080       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21081     case ISD::SETGT:
21082     case ISD::SETGE:
21083       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21084     }
21085   }
21086
21087   return std::make_pair(Opc, NeedSplit);
21088 }
21089
21090 static SDValue
21091 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21092                                       const X86Subtarget *Subtarget) {
21093   SDLoc dl(N);
21094   SDValue Cond = N->getOperand(0);
21095   SDValue LHS = N->getOperand(1);
21096   SDValue RHS = N->getOperand(2);
21097
21098   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21099     SDValue CondSrc = Cond->getOperand(0);
21100     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21101       Cond = CondSrc->getOperand(0);
21102   }
21103
21104   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21105     return SDValue();
21106
21107   // A vselect where all conditions and data are constants can be optimized into
21108   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21109   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21110       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21111     return SDValue();
21112
21113   unsigned MaskValue = 0;
21114   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21115     return SDValue();
21116
21117   MVT VT = N->getSimpleValueType(0);
21118   unsigned NumElems = VT.getVectorNumElements();
21119   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21120   for (unsigned i = 0; i < NumElems; ++i) {
21121     // Be sure we emit undef where we can.
21122     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21123       ShuffleMask[i] = -1;
21124     else
21125       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21126   }
21127
21128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21129   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21130     return SDValue();
21131   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21132 }
21133
21134 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21135 /// nodes.
21136 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21137                                     TargetLowering::DAGCombinerInfo &DCI,
21138                                     const X86Subtarget *Subtarget) {
21139   SDLoc DL(N);
21140   SDValue Cond = N->getOperand(0);
21141   // Get the LHS/RHS of the select.
21142   SDValue LHS = N->getOperand(1);
21143   SDValue RHS = N->getOperand(2);
21144   EVT VT = LHS.getValueType();
21145   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21146
21147   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21148   // instructions match the semantics of the common C idiom x<y?x:y but not
21149   // x<=y?x:y, because of how they handle negative zero (which can be
21150   // ignored in unsafe-math mode).
21151   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21152   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21153       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21154       (Subtarget->hasSSE2() ||
21155        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21156     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21157
21158     unsigned Opcode = 0;
21159     // Check for x CC y ? x : y.
21160     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21161         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21162       switch (CC) {
21163       default: break;
21164       case ISD::SETULT:
21165         // Converting this to a min would handle NaNs incorrectly, and swapping
21166         // the operands would cause it to handle comparisons between positive
21167         // and negative zero incorrectly.
21168         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21169           if (!DAG.getTarget().Options.UnsafeFPMath &&
21170               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21171             break;
21172           std::swap(LHS, RHS);
21173         }
21174         Opcode = X86ISD::FMIN;
21175         break;
21176       case ISD::SETOLE:
21177         // Converting this to a min would handle comparisons between positive
21178         // and negative zero incorrectly.
21179         if (!DAG.getTarget().Options.UnsafeFPMath &&
21180             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21181           break;
21182         Opcode = X86ISD::FMIN;
21183         break;
21184       case ISD::SETULE:
21185         // Converting this to a min would handle both negative zeros and NaNs
21186         // incorrectly, but we can swap the operands to fix both.
21187         std::swap(LHS, RHS);
21188       case ISD::SETOLT:
21189       case ISD::SETLT:
21190       case ISD::SETLE:
21191         Opcode = X86ISD::FMIN;
21192         break;
21193
21194       case ISD::SETOGE:
21195         // Converting this to a max would handle comparisons between positive
21196         // and negative zero incorrectly.
21197         if (!DAG.getTarget().Options.UnsafeFPMath &&
21198             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21199           break;
21200         Opcode = X86ISD::FMAX;
21201         break;
21202       case ISD::SETUGT:
21203         // Converting this to a max would handle NaNs incorrectly, and swapping
21204         // the operands would cause it to handle comparisons between positive
21205         // and negative zero incorrectly.
21206         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21207           if (!DAG.getTarget().Options.UnsafeFPMath &&
21208               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21209             break;
21210           std::swap(LHS, RHS);
21211         }
21212         Opcode = X86ISD::FMAX;
21213         break;
21214       case ISD::SETUGE:
21215         // Converting this to a max would handle both negative zeros and NaNs
21216         // incorrectly, but we can swap the operands to fix both.
21217         std::swap(LHS, RHS);
21218       case ISD::SETOGT:
21219       case ISD::SETGT:
21220       case ISD::SETGE:
21221         Opcode = X86ISD::FMAX;
21222         break;
21223       }
21224     // Check for x CC y ? y : x -- a min/max with reversed arms.
21225     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21226                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21227       switch (CC) {
21228       default: break;
21229       case ISD::SETOGE:
21230         // Converting this to a min would handle comparisons between positive
21231         // and negative zero incorrectly, and swapping the operands would
21232         // cause it to handle NaNs incorrectly.
21233         if (!DAG.getTarget().Options.UnsafeFPMath &&
21234             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21235           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21236             break;
21237           std::swap(LHS, RHS);
21238         }
21239         Opcode = X86ISD::FMIN;
21240         break;
21241       case ISD::SETUGT:
21242         // Converting this to a min would handle NaNs incorrectly.
21243         if (!DAG.getTarget().Options.UnsafeFPMath &&
21244             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21245           break;
21246         Opcode = X86ISD::FMIN;
21247         break;
21248       case ISD::SETUGE:
21249         // Converting this to a min would handle both negative zeros and NaNs
21250         // incorrectly, but we can swap the operands to fix both.
21251         std::swap(LHS, RHS);
21252       case ISD::SETOGT:
21253       case ISD::SETGT:
21254       case ISD::SETGE:
21255         Opcode = X86ISD::FMIN;
21256         break;
21257
21258       case ISD::SETULT:
21259         // Converting this to a max would handle NaNs incorrectly.
21260         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21261           break;
21262         Opcode = X86ISD::FMAX;
21263         break;
21264       case ISD::SETOLE:
21265         // Converting this to a max would handle comparisons between positive
21266         // and negative zero incorrectly, and swapping the operands would
21267         // cause it to handle NaNs incorrectly.
21268         if (!DAG.getTarget().Options.UnsafeFPMath &&
21269             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21270           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21271             break;
21272           std::swap(LHS, RHS);
21273         }
21274         Opcode = X86ISD::FMAX;
21275         break;
21276       case ISD::SETULE:
21277         // Converting this to a max would handle both negative zeros and NaNs
21278         // incorrectly, but we can swap the operands to fix both.
21279         std::swap(LHS, RHS);
21280       case ISD::SETOLT:
21281       case ISD::SETLT:
21282       case ISD::SETLE:
21283         Opcode = X86ISD::FMAX;
21284         break;
21285       }
21286     }
21287
21288     if (Opcode)
21289       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21290   }
21291
21292   EVT CondVT = Cond.getValueType();
21293   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21294       CondVT.getVectorElementType() == MVT::i1) {
21295     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21296     // lowering on KNL. In this case we convert it to
21297     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21298     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21299     // Since SKX these selects have a proper lowering.
21300     EVT OpVT = LHS.getValueType();
21301     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21302         (OpVT.getVectorElementType() == MVT::i8 ||
21303          OpVT.getVectorElementType() == MVT::i16) &&
21304         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21305       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21306       DCI.AddToWorklist(Cond.getNode());
21307       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21308     }
21309   }
21310   // If this is a select between two integer constants, try to do some
21311   // optimizations.
21312   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21313     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21314       // Don't do this for crazy integer types.
21315       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21316         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21317         // so that TrueC (the true value) is larger than FalseC.
21318         bool NeedsCondInvert = false;
21319
21320         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21321             // Efficiently invertible.
21322             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21323              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21324               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21325           NeedsCondInvert = true;
21326           std::swap(TrueC, FalseC);
21327         }
21328
21329         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21330         if (FalseC->getAPIntValue() == 0 &&
21331             TrueC->getAPIntValue().isPowerOf2()) {
21332           if (NeedsCondInvert) // Invert the condition if needed.
21333             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21334                                DAG.getConstant(1, DL, Cond.getValueType()));
21335
21336           // Zero extend the condition if needed.
21337           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21338
21339           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21340           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21341                              DAG.getConstant(ShAmt, DL, MVT::i8));
21342         }
21343
21344         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21345         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21346           if (NeedsCondInvert) // Invert the condition if needed.
21347             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21348                                DAG.getConstant(1, DL, Cond.getValueType()));
21349
21350           // Zero extend the condition if needed.
21351           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21352                              FalseC->getValueType(0), Cond);
21353           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21354                              SDValue(FalseC, 0));
21355         }
21356
21357         // Optimize cases that will turn into an LEA instruction.  This requires
21358         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21359         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21360           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21361           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21362
21363           bool isFastMultiplier = false;
21364           if (Diff < 10) {
21365             switch ((unsigned char)Diff) {
21366               default: break;
21367               case 1:  // result = add base, cond
21368               case 2:  // result = lea base(    , cond*2)
21369               case 3:  // result = lea base(cond, cond*2)
21370               case 4:  // result = lea base(    , cond*4)
21371               case 5:  // result = lea base(cond, cond*4)
21372               case 8:  // result = lea base(    , cond*8)
21373               case 9:  // result = lea base(cond, cond*8)
21374                 isFastMultiplier = true;
21375                 break;
21376             }
21377           }
21378
21379           if (isFastMultiplier) {
21380             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21381             if (NeedsCondInvert) // Invert the condition if needed.
21382               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21383                                  DAG.getConstant(1, DL, Cond.getValueType()));
21384
21385             // Zero extend the condition if needed.
21386             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21387                                Cond);
21388             // Scale the condition by the difference.
21389             if (Diff != 1)
21390               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21391                                  DAG.getConstant(Diff, DL,
21392                                                  Cond.getValueType()));
21393
21394             // Add the base if non-zero.
21395             if (FalseC->getAPIntValue() != 0)
21396               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21397                                  SDValue(FalseC, 0));
21398             return Cond;
21399           }
21400         }
21401       }
21402   }
21403
21404   // Canonicalize max and min:
21405   // (x > y) ? x : y -> (x >= y) ? x : y
21406   // (x < y) ? x : y -> (x <= y) ? x : y
21407   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21408   // the need for an extra compare
21409   // against zero. e.g.
21410   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21411   // subl   %esi, %edi
21412   // testl  %edi, %edi
21413   // movl   $0, %eax
21414   // cmovgl %edi, %eax
21415   // =>
21416   // xorl   %eax, %eax
21417   // subl   %esi, $edi
21418   // cmovsl %eax, %edi
21419   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21420       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21421       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21422     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21423     switch (CC) {
21424     default: break;
21425     case ISD::SETLT:
21426     case ISD::SETGT: {
21427       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21428       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21429                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21430       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21431     }
21432     }
21433   }
21434
21435   // Early exit check
21436   if (!TLI.isTypeLegal(VT))
21437     return SDValue();
21438
21439   // Match VSELECTs into subs with unsigned saturation.
21440   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21441       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21442       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21443        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21444     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21445
21446     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21447     // left side invert the predicate to simplify logic below.
21448     SDValue Other;
21449     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21450       Other = RHS;
21451       CC = ISD::getSetCCInverse(CC, true);
21452     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21453       Other = LHS;
21454     }
21455
21456     if (Other.getNode() && Other->getNumOperands() == 2 &&
21457         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21458       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21459       SDValue CondRHS = Cond->getOperand(1);
21460
21461       // Look for a general sub with unsigned saturation first.
21462       // x >= y ? x-y : 0 --> subus x, y
21463       // x >  y ? x-y : 0 --> subus x, y
21464       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21465           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21466         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21467
21468       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21469         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21470           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21471             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21472               // If the RHS is a constant we have to reverse the const
21473               // canonicalization.
21474               // x > C-1 ? x+-C : 0 --> subus x, C
21475               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21476                   CondRHSConst->getAPIntValue() ==
21477                       (-OpRHSConst->getAPIntValue() - 1))
21478                 return DAG.getNode(
21479                     X86ISD::SUBUS, DL, VT, OpLHS,
21480                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21481
21482           // Another special case: If C was a sign bit, the sub has been
21483           // canonicalized into a xor.
21484           // FIXME: Would it be better to use computeKnownBits to determine
21485           //        whether it's safe to decanonicalize the xor?
21486           // x s< 0 ? x^C : 0 --> subus x, C
21487           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21488               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21489               OpRHSConst->getAPIntValue().isSignBit())
21490             // Note that we have to rebuild the RHS constant here to ensure we
21491             // don't rely on particular values of undef lanes.
21492             return DAG.getNode(
21493                 X86ISD::SUBUS, DL, VT, OpLHS,
21494                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21495         }
21496     }
21497   }
21498
21499   // Try to match a min/max vector operation.
21500   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21501     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21502     unsigned Opc = ret.first;
21503     bool NeedSplit = ret.second;
21504
21505     if (Opc && NeedSplit) {
21506       unsigned NumElems = VT.getVectorNumElements();
21507       // Extract the LHS vectors
21508       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21509       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21510
21511       // Extract the RHS vectors
21512       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21513       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21514
21515       // Create min/max for each subvector
21516       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21517       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21518
21519       // Merge the result
21520       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21521     } else if (Opc)
21522       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21523   }
21524
21525   // Simplify vector selection if condition value type matches vselect
21526   // operand type
21527   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21528     assert(Cond.getValueType().isVector() &&
21529            "vector select expects a vector selector!");
21530
21531     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21532     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21533
21534     // Try invert the condition if true value is not all 1s and false value
21535     // is not all 0s.
21536     if (!TValIsAllOnes && !FValIsAllZeros &&
21537         // Check if the selector will be produced by CMPP*/PCMP*
21538         Cond.getOpcode() == ISD::SETCC &&
21539         // Check if SETCC has already been promoted
21540         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21541       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21542       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21543
21544       if (TValIsAllZeros || FValIsAllOnes) {
21545         SDValue CC = Cond.getOperand(2);
21546         ISD::CondCode NewCC =
21547           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21548                                Cond.getOperand(0).getValueType().isInteger());
21549         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21550         std::swap(LHS, RHS);
21551         TValIsAllOnes = FValIsAllOnes;
21552         FValIsAllZeros = TValIsAllZeros;
21553       }
21554     }
21555
21556     if (TValIsAllOnes || FValIsAllZeros) {
21557       SDValue Ret;
21558
21559       if (TValIsAllOnes && FValIsAllZeros)
21560         Ret = Cond;
21561       else if (TValIsAllOnes)
21562         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21563                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21564       else if (FValIsAllZeros)
21565         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21566                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21567
21568       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21569     }
21570   }
21571
21572   // We should generate an X86ISD::BLENDI from a vselect if its argument
21573   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21574   // constants. This specific pattern gets generated when we split a
21575   // selector for a 512 bit vector in a machine without AVX512 (but with
21576   // 256-bit vectors), during legalization:
21577   //
21578   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21579   //
21580   // Iff we find this pattern and the build_vectors are built from
21581   // constants, we translate the vselect into a shuffle_vector that we
21582   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21583   if ((N->getOpcode() == ISD::VSELECT ||
21584        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21585       !DCI.isBeforeLegalize()) {
21586     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21587     if (Shuffle.getNode())
21588       return Shuffle;
21589   }
21590
21591   // If this is a *dynamic* select (non-constant condition) and we can match
21592   // this node with one of the variable blend instructions, restructure the
21593   // condition so that the blends can use the high bit of each element and use
21594   // SimplifyDemandedBits to simplify the condition operand.
21595   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21596       !DCI.isBeforeLegalize() &&
21597       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21598     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21599
21600     // Don't optimize vector selects that map to mask-registers.
21601     if (BitWidth == 1)
21602       return SDValue();
21603
21604     // We can only handle the cases where VSELECT is directly legal on the
21605     // subtarget. We custom lower VSELECT nodes with constant conditions and
21606     // this makes it hard to see whether a dynamic VSELECT will correctly
21607     // lower, so we both check the operation's status and explicitly handle the
21608     // cases where a *dynamic* blend will fail even though a constant-condition
21609     // blend could be custom lowered.
21610     // FIXME: We should find a better way to handle this class of problems.
21611     // Potentially, we should combine constant-condition vselect nodes
21612     // pre-legalization into shuffles and not mark as many types as custom
21613     // lowered.
21614     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21615       return SDValue();
21616     // FIXME: We don't support i16-element blends currently. We could and
21617     // should support them by making *all* the bits in the condition be set
21618     // rather than just the high bit and using an i8-element blend.
21619     if (VT.getScalarType() == MVT::i16)
21620       return SDValue();
21621     // Dynamic blending was only available from SSE4.1 onward.
21622     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21623       return SDValue();
21624     // Byte blends are only available in AVX2
21625     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21626         !Subtarget->hasAVX2())
21627       return SDValue();
21628
21629     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21630     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21631
21632     APInt KnownZero, KnownOne;
21633     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21634                                           DCI.isBeforeLegalizeOps());
21635     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21636         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21637                                  TLO)) {
21638       // If we changed the computation somewhere in the DAG, this change
21639       // will affect all users of Cond.
21640       // Make sure it is fine and update all the nodes so that we do not
21641       // use the generic VSELECT anymore. Otherwise, we may perform
21642       // wrong optimizations as we messed up with the actual expectation
21643       // for the vector boolean values.
21644       if (Cond != TLO.Old) {
21645         // Check all uses of that condition operand to check whether it will be
21646         // consumed by non-BLEND instructions, which may depend on all bits are
21647         // set properly.
21648         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21649              I != E; ++I)
21650           if (I->getOpcode() != ISD::VSELECT)
21651             // TODO: Add other opcodes eventually lowered into BLEND.
21652             return SDValue();
21653
21654         // Update all the users of the condition, before committing the change,
21655         // so that the VSELECT optimizations that expect the correct vector
21656         // boolean value will not be triggered.
21657         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21658              I != E; ++I)
21659           DAG.ReplaceAllUsesOfValueWith(
21660               SDValue(*I, 0),
21661               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21662                           Cond, I->getOperand(1), I->getOperand(2)));
21663         DCI.CommitTargetLoweringOpt(TLO);
21664         return SDValue();
21665       }
21666       // At this point, only Cond is changed. Change the condition
21667       // just for N to keep the opportunity to optimize all other
21668       // users their own way.
21669       DAG.ReplaceAllUsesOfValueWith(
21670           SDValue(N, 0),
21671           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21672                       TLO.New, N->getOperand(1), N->getOperand(2)));
21673       return SDValue();
21674     }
21675   }
21676
21677   return SDValue();
21678 }
21679
21680 // Check whether a boolean test is testing a boolean value generated by
21681 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21682 // code.
21683 //
21684 // Simplify the following patterns:
21685 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21686 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21687 // to (Op EFLAGS Cond)
21688 //
21689 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21690 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21691 // to (Op EFLAGS !Cond)
21692 //
21693 // where Op could be BRCOND or CMOV.
21694 //
21695 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21696   // Quit if not CMP and SUB with its value result used.
21697   if (Cmp.getOpcode() != X86ISD::CMP &&
21698       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21699       return SDValue();
21700
21701   // Quit if not used as a boolean value.
21702   if (CC != X86::COND_E && CC != X86::COND_NE)
21703     return SDValue();
21704
21705   // Check CMP operands. One of them should be 0 or 1 and the other should be
21706   // an SetCC or extended from it.
21707   SDValue Op1 = Cmp.getOperand(0);
21708   SDValue Op2 = Cmp.getOperand(1);
21709
21710   SDValue SetCC;
21711   const ConstantSDNode* C = nullptr;
21712   bool needOppositeCond = (CC == X86::COND_E);
21713   bool checkAgainstTrue = false; // Is it a comparison against 1?
21714
21715   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21716     SetCC = Op2;
21717   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21718     SetCC = Op1;
21719   else // Quit if all operands are not constants.
21720     return SDValue();
21721
21722   if (C->getZExtValue() == 1) {
21723     needOppositeCond = !needOppositeCond;
21724     checkAgainstTrue = true;
21725   } else if (C->getZExtValue() != 0)
21726     // Quit if the constant is neither 0 or 1.
21727     return SDValue();
21728
21729   bool truncatedToBoolWithAnd = false;
21730   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21731   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21732          SetCC.getOpcode() == ISD::TRUNCATE ||
21733          SetCC.getOpcode() == ISD::AND) {
21734     if (SetCC.getOpcode() == ISD::AND) {
21735       int OpIdx = -1;
21736       ConstantSDNode *CS;
21737       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21738           CS->getZExtValue() == 1)
21739         OpIdx = 1;
21740       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21741           CS->getZExtValue() == 1)
21742         OpIdx = 0;
21743       if (OpIdx == -1)
21744         break;
21745       SetCC = SetCC.getOperand(OpIdx);
21746       truncatedToBoolWithAnd = true;
21747     } else
21748       SetCC = SetCC.getOperand(0);
21749   }
21750
21751   switch (SetCC.getOpcode()) {
21752   case X86ISD::SETCC_CARRY:
21753     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21754     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21755     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21756     // truncated to i1 using 'and'.
21757     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21758       break;
21759     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21760            "Invalid use of SETCC_CARRY!");
21761     // FALL THROUGH
21762   case X86ISD::SETCC:
21763     // Set the condition code or opposite one if necessary.
21764     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21765     if (needOppositeCond)
21766       CC = X86::GetOppositeBranchCondition(CC);
21767     return SetCC.getOperand(1);
21768   case X86ISD::CMOV: {
21769     // Check whether false/true value has canonical one, i.e. 0 or 1.
21770     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21771     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21772     // Quit if true value is not a constant.
21773     if (!TVal)
21774       return SDValue();
21775     // Quit if false value is not a constant.
21776     if (!FVal) {
21777       SDValue Op = SetCC.getOperand(0);
21778       // Skip 'zext' or 'trunc' node.
21779       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21780           Op.getOpcode() == ISD::TRUNCATE)
21781         Op = Op.getOperand(0);
21782       // A special case for rdrand/rdseed, where 0 is set if false cond is
21783       // found.
21784       if ((Op.getOpcode() != X86ISD::RDRAND &&
21785            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21786         return SDValue();
21787     }
21788     // Quit if false value is not the constant 0 or 1.
21789     bool FValIsFalse = true;
21790     if (FVal && FVal->getZExtValue() != 0) {
21791       if (FVal->getZExtValue() != 1)
21792         return SDValue();
21793       // If FVal is 1, opposite cond is needed.
21794       needOppositeCond = !needOppositeCond;
21795       FValIsFalse = false;
21796     }
21797     // Quit if TVal is not the constant opposite of FVal.
21798     if (FValIsFalse && TVal->getZExtValue() != 1)
21799       return SDValue();
21800     if (!FValIsFalse && TVal->getZExtValue() != 0)
21801       return SDValue();
21802     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21803     if (needOppositeCond)
21804       CC = X86::GetOppositeBranchCondition(CC);
21805     return SetCC.getOperand(3);
21806   }
21807   }
21808
21809   return SDValue();
21810 }
21811
21812 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21813 /// Match:
21814 ///   (X86or (X86setcc) (X86setcc))
21815 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21816 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21817                                            X86::CondCode &CC1, SDValue &Flags,
21818                                            bool &isAnd) {
21819   if (Cond->getOpcode() == X86ISD::CMP) {
21820     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21821     if (!CondOp1C || !CondOp1C->isNullValue())
21822       return false;
21823
21824     Cond = Cond->getOperand(0);
21825   }
21826
21827   isAnd = false;
21828
21829   SDValue SetCC0, SetCC1;
21830   switch (Cond->getOpcode()) {
21831   default: return false;
21832   case ISD::AND:
21833   case X86ISD::AND:
21834     isAnd = true;
21835     // fallthru
21836   case ISD::OR:
21837   case X86ISD::OR:
21838     SetCC0 = Cond->getOperand(0);
21839     SetCC1 = Cond->getOperand(1);
21840     break;
21841   };
21842
21843   // Make sure we have SETCC nodes, using the same flags value.
21844   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21845       SetCC1.getOpcode() != X86ISD::SETCC ||
21846       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21847     return false;
21848
21849   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21850   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21851   Flags = SetCC0->getOperand(1);
21852   return true;
21853 }
21854
21855 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21856 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21857                                   TargetLowering::DAGCombinerInfo &DCI,
21858                                   const X86Subtarget *Subtarget) {
21859   SDLoc DL(N);
21860
21861   // If the flag operand isn't dead, don't touch this CMOV.
21862   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21863     return SDValue();
21864
21865   SDValue FalseOp = N->getOperand(0);
21866   SDValue TrueOp = N->getOperand(1);
21867   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21868   SDValue Cond = N->getOperand(3);
21869
21870   if (CC == X86::COND_E || CC == X86::COND_NE) {
21871     switch (Cond.getOpcode()) {
21872     default: break;
21873     case X86ISD::BSR:
21874     case X86ISD::BSF:
21875       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21876       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21877         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21878     }
21879   }
21880
21881   SDValue Flags;
21882
21883   Flags = checkBoolTestSetCCCombine(Cond, CC);
21884   if (Flags.getNode() &&
21885       // Extra check as FCMOV only supports a subset of X86 cond.
21886       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21887     SDValue Ops[] = { FalseOp, TrueOp,
21888                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21889     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21890   }
21891
21892   // If this is a select between two integer constants, try to do some
21893   // optimizations.  Note that the operands are ordered the opposite of SELECT
21894   // operands.
21895   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21896     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21897       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21898       // larger than FalseC (the false value).
21899       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21900         CC = X86::GetOppositeBranchCondition(CC);
21901         std::swap(TrueC, FalseC);
21902         std::swap(TrueOp, FalseOp);
21903       }
21904
21905       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21906       // This is efficient for any integer data type (including i8/i16) and
21907       // shift amount.
21908       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21909         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21910                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21911
21912         // Zero extend the condition if needed.
21913         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21914
21915         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21916         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21917                            DAG.getConstant(ShAmt, DL, MVT::i8));
21918         if (N->getNumValues() == 2)  // Dead flag value?
21919           return DCI.CombineTo(N, Cond, SDValue());
21920         return Cond;
21921       }
21922
21923       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21924       // for any integer data type, including i8/i16.
21925       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21926         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21927                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21928
21929         // Zero extend the condition if needed.
21930         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21931                            FalseC->getValueType(0), Cond);
21932         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21933                            SDValue(FalseC, 0));
21934
21935         if (N->getNumValues() == 2)  // Dead flag value?
21936           return DCI.CombineTo(N, Cond, SDValue());
21937         return Cond;
21938       }
21939
21940       // Optimize cases that will turn into an LEA instruction.  This requires
21941       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21942       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21943         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21944         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21945
21946         bool isFastMultiplier = false;
21947         if (Diff < 10) {
21948           switch ((unsigned char)Diff) {
21949           default: break;
21950           case 1:  // result = add base, cond
21951           case 2:  // result = lea base(    , cond*2)
21952           case 3:  // result = lea base(cond, cond*2)
21953           case 4:  // result = lea base(    , cond*4)
21954           case 5:  // result = lea base(cond, cond*4)
21955           case 8:  // result = lea base(    , cond*8)
21956           case 9:  // result = lea base(cond, cond*8)
21957             isFastMultiplier = true;
21958             break;
21959           }
21960         }
21961
21962         if (isFastMultiplier) {
21963           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21964           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21965                              DAG.getConstant(CC, DL, MVT::i8), Cond);
21966           // Zero extend the condition if needed.
21967           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21968                              Cond);
21969           // Scale the condition by the difference.
21970           if (Diff != 1)
21971             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21972                                DAG.getConstant(Diff, DL, Cond.getValueType()));
21973
21974           // Add the base if non-zero.
21975           if (FalseC->getAPIntValue() != 0)
21976             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21977                                SDValue(FalseC, 0));
21978           if (N->getNumValues() == 2)  // Dead flag value?
21979             return DCI.CombineTo(N, Cond, SDValue());
21980           return Cond;
21981         }
21982       }
21983     }
21984   }
21985
21986   // Handle these cases:
21987   //   (select (x != c), e, c) -> select (x != c), e, x),
21988   //   (select (x == c), c, e) -> select (x == c), x, e)
21989   // where the c is an integer constant, and the "select" is the combination
21990   // of CMOV and CMP.
21991   //
21992   // The rationale for this change is that the conditional-move from a constant
21993   // needs two instructions, however, conditional-move from a register needs
21994   // only one instruction.
21995   //
21996   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21997   //  some instruction-combining opportunities. This opt needs to be
21998   //  postponed as late as possible.
21999   //
22000   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22001     // the DCI.xxxx conditions are provided to postpone the optimization as
22002     // late as possible.
22003
22004     ConstantSDNode *CmpAgainst = nullptr;
22005     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22006         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22007         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22008
22009       if (CC == X86::COND_NE &&
22010           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22011         CC = X86::GetOppositeBranchCondition(CC);
22012         std::swap(TrueOp, FalseOp);
22013       }
22014
22015       if (CC == X86::COND_E &&
22016           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22017         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22018                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22019         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22020       }
22021     }
22022   }
22023
22024   // Fold and/or of setcc's to double CMOV:
22025   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22026   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22027   //
22028   // This combine lets us generate:
22029   //   cmovcc1 (jcc1 if we don't have CMOV)
22030   //   cmovcc2 (same)
22031   // instead of:
22032   //   setcc1
22033   //   setcc2
22034   //   and/or
22035   //   cmovne (jne if we don't have CMOV)
22036   // When we can't use the CMOV instruction, it might increase branch
22037   // mispredicts.
22038   // When we can use CMOV, or when there is no mispredict, this improves
22039   // throughput and reduces register pressure.
22040   //
22041   if (CC == X86::COND_NE) {
22042     SDValue Flags;
22043     X86::CondCode CC0, CC1;
22044     bool isAndSetCC;
22045     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22046       if (isAndSetCC) {
22047         std::swap(FalseOp, TrueOp);
22048         CC0 = X86::GetOppositeBranchCondition(CC0);
22049         CC1 = X86::GetOppositeBranchCondition(CC1);
22050       }
22051
22052       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22053         Flags};
22054       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22055       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22056       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22057       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22058       return CMOV;
22059     }
22060   }
22061
22062   return SDValue();
22063 }
22064
22065 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22066                                                 const X86Subtarget *Subtarget) {
22067   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22068   switch (IntNo) {
22069   default: return SDValue();
22070   // SSE/AVX/AVX2 blend intrinsics.
22071   case Intrinsic::x86_avx2_pblendvb:
22072     // Don't try to simplify this intrinsic if we don't have AVX2.
22073     if (!Subtarget->hasAVX2())
22074       return SDValue();
22075     // FALL-THROUGH
22076   case Intrinsic::x86_avx_blendv_pd_256:
22077   case Intrinsic::x86_avx_blendv_ps_256:
22078     // Don't try to simplify this intrinsic if we don't have AVX.
22079     if (!Subtarget->hasAVX())
22080       return SDValue();
22081     // FALL-THROUGH
22082   case Intrinsic::x86_sse41_blendvps:
22083   case Intrinsic::x86_sse41_blendvpd:
22084   case Intrinsic::x86_sse41_pblendvb: {
22085     SDValue Op0 = N->getOperand(1);
22086     SDValue Op1 = N->getOperand(2);
22087     SDValue Mask = N->getOperand(3);
22088
22089     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22090     if (!Subtarget->hasSSE41())
22091       return SDValue();
22092
22093     // fold (blend A, A, Mask) -> A
22094     if (Op0 == Op1)
22095       return Op0;
22096     // fold (blend A, B, allZeros) -> A
22097     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22098       return Op0;
22099     // fold (blend A, B, allOnes) -> B
22100     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22101       return Op1;
22102
22103     // Simplify the case where the mask is a constant i32 value.
22104     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22105       if (C->isNullValue())
22106         return Op0;
22107       if (C->isAllOnesValue())
22108         return Op1;
22109     }
22110
22111     return SDValue();
22112   }
22113
22114   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22115   case Intrinsic::x86_sse2_psrai_w:
22116   case Intrinsic::x86_sse2_psrai_d:
22117   case Intrinsic::x86_avx2_psrai_w:
22118   case Intrinsic::x86_avx2_psrai_d:
22119   case Intrinsic::x86_sse2_psra_w:
22120   case Intrinsic::x86_sse2_psra_d:
22121   case Intrinsic::x86_avx2_psra_w:
22122   case Intrinsic::x86_avx2_psra_d: {
22123     SDValue Op0 = N->getOperand(1);
22124     SDValue Op1 = N->getOperand(2);
22125     EVT VT = Op0.getValueType();
22126     assert(VT.isVector() && "Expected a vector type!");
22127
22128     if (isa<BuildVectorSDNode>(Op1))
22129       Op1 = Op1.getOperand(0);
22130
22131     if (!isa<ConstantSDNode>(Op1))
22132       return SDValue();
22133
22134     EVT SVT = VT.getVectorElementType();
22135     unsigned SVTBits = SVT.getSizeInBits();
22136
22137     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22138     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22139     uint64_t ShAmt = C.getZExtValue();
22140
22141     // Don't try to convert this shift into a ISD::SRA if the shift
22142     // count is bigger than or equal to the element size.
22143     if (ShAmt >= SVTBits)
22144       return SDValue();
22145
22146     // Trivial case: if the shift count is zero, then fold this
22147     // into the first operand.
22148     if (ShAmt == 0)
22149       return Op0;
22150
22151     // Replace this packed shift intrinsic with a target independent
22152     // shift dag node.
22153     SDLoc DL(N);
22154     SDValue Splat = DAG.getConstant(C, DL, VT);
22155     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22156   }
22157   }
22158 }
22159
22160 /// PerformMulCombine - Optimize a single multiply with constant into two
22161 /// in order to implement it with two cheaper instructions, e.g.
22162 /// LEA + SHL, LEA + LEA.
22163 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22164                                  TargetLowering::DAGCombinerInfo &DCI) {
22165   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22166     return SDValue();
22167
22168   EVT VT = N->getValueType(0);
22169   if (VT != MVT::i64 && VT != MVT::i32)
22170     return SDValue();
22171
22172   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22173   if (!C)
22174     return SDValue();
22175   uint64_t MulAmt = C->getZExtValue();
22176   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22177     return SDValue();
22178
22179   uint64_t MulAmt1 = 0;
22180   uint64_t MulAmt2 = 0;
22181   if ((MulAmt % 9) == 0) {
22182     MulAmt1 = 9;
22183     MulAmt2 = MulAmt / 9;
22184   } else if ((MulAmt % 5) == 0) {
22185     MulAmt1 = 5;
22186     MulAmt2 = MulAmt / 5;
22187   } else if ((MulAmt % 3) == 0) {
22188     MulAmt1 = 3;
22189     MulAmt2 = MulAmt / 3;
22190   }
22191   if (MulAmt2 &&
22192       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22193     SDLoc DL(N);
22194
22195     if (isPowerOf2_64(MulAmt2) &&
22196         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22197       // If second multiplifer is pow2, issue it first. We want the multiply by
22198       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22199       // is an add.
22200       std::swap(MulAmt1, MulAmt2);
22201
22202     SDValue NewMul;
22203     if (isPowerOf2_64(MulAmt1))
22204       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22205                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22206     else
22207       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22208                            DAG.getConstant(MulAmt1, DL, VT));
22209
22210     if (isPowerOf2_64(MulAmt2))
22211       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22212                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22213     else
22214       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22215                            DAG.getConstant(MulAmt2, DL, VT));
22216
22217     // Do not add new nodes to DAG combiner worklist.
22218     DCI.CombineTo(N, NewMul, false);
22219   }
22220   return SDValue();
22221 }
22222
22223 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22224   SDValue N0 = N->getOperand(0);
22225   SDValue N1 = N->getOperand(1);
22226   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22227   EVT VT = N0.getValueType();
22228
22229   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22230   // since the result of setcc_c is all zero's or all ones.
22231   if (VT.isInteger() && !VT.isVector() &&
22232       N1C && N0.getOpcode() == ISD::AND &&
22233       N0.getOperand(1).getOpcode() == ISD::Constant) {
22234     SDValue N00 = N0.getOperand(0);
22235     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22236         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22237           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22238          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22239       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22240       APInt ShAmt = N1C->getAPIntValue();
22241       Mask = Mask.shl(ShAmt);
22242       if (Mask != 0) {
22243         SDLoc DL(N);
22244         return DAG.getNode(ISD::AND, DL, VT,
22245                            N00, DAG.getConstant(Mask, DL, VT));
22246       }
22247     }
22248   }
22249
22250   // Hardware support for vector shifts is sparse which makes us scalarize the
22251   // vector operations in many cases. Also, on sandybridge ADD is faster than
22252   // shl.
22253   // (shl V, 1) -> add V,V
22254   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22255     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22256       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22257       // We shift all of the values by one. In many cases we do not have
22258       // hardware support for this operation. This is better expressed as an ADD
22259       // of two values.
22260       if (N1SplatC->getZExtValue() == 1)
22261         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22262     }
22263
22264   return SDValue();
22265 }
22266
22267 /// \brief Returns a vector of 0s if the node in input is a vector logical
22268 /// shift by a constant amount which is known to be bigger than or equal
22269 /// to the vector element size in bits.
22270 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22271                                       const X86Subtarget *Subtarget) {
22272   EVT VT = N->getValueType(0);
22273
22274   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22275       (!Subtarget->hasInt256() ||
22276        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22277     return SDValue();
22278
22279   SDValue Amt = N->getOperand(1);
22280   SDLoc DL(N);
22281   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22282     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22283       APInt ShiftAmt = AmtSplat->getAPIntValue();
22284       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22285
22286       // SSE2/AVX2 logical shifts always return a vector of 0s
22287       // if the shift amount is bigger than or equal to
22288       // the element size. The constant shift amount will be
22289       // encoded as a 8-bit immediate.
22290       if (ShiftAmt.trunc(8).uge(MaxAmount))
22291         return getZeroVector(VT, Subtarget, DAG, DL);
22292     }
22293
22294   return SDValue();
22295 }
22296
22297 /// PerformShiftCombine - Combine shifts.
22298 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22299                                    TargetLowering::DAGCombinerInfo &DCI,
22300                                    const X86Subtarget *Subtarget) {
22301   if (N->getOpcode() == ISD::SHL) {
22302     SDValue V = PerformSHLCombine(N, DAG);
22303     if (V.getNode()) return V;
22304   }
22305
22306   if (N->getOpcode() != ISD::SRA) {
22307     // Try to fold this logical shift into a zero vector.
22308     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22309     if (V.getNode()) return V;
22310   }
22311
22312   return SDValue();
22313 }
22314
22315 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22316 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22317 // and friends.  Likewise for OR -> CMPNEQSS.
22318 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22319                             TargetLowering::DAGCombinerInfo &DCI,
22320                             const X86Subtarget *Subtarget) {
22321   unsigned opcode;
22322
22323   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22324   // we're requiring SSE2 for both.
22325   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22326     SDValue N0 = N->getOperand(0);
22327     SDValue N1 = N->getOperand(1);
22328     SDValue CMP0 = N0->getOperand(1);
22329     SDValue CMP1 = N1->getOperand(1);
22330     SDLoc DL(N);
22331
22332     // The SETCCs should both refer to the same CMP.
22333     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22334       return SDValue();
22335
22336     SDValue CMP00 = CMP0->getOperand(0);
22337     SDValue CMP01 = CMP0->getOperand(1);
22338     EVT     VT    = CMP00.getValueType();
22339
22340     if (VT == MVT::f32 || VT == MVT::f64) {
22341       bool ExpectingFlags = false;
22342       // Check for any users that want flags:
22343       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22344            !ExpectingFlags && UI != UE; ++UI)
22345         switch (UI->getOpcode()) {
22346         default:
22347         case ISD::BR_CC:
22348         case ISD::BRCOND:
22349         case ISD::SELECT:
22350           ExpectingFlags = true;
22351           break;
22352         case ISD::CopyToReg:
22353         case ISD::SIGN_EXTEND:
22354         case ISD::ZERO_EXTEND:
22355         case ISD::ANY_EXTEND:
22356           break;
22357         }
22358
22359       if (!ExpectingFlags) {
22360         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22361         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22362
22363         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22364           X86::CondCode tmp = cc0;
22365           cc0 = cc1;
22366           cc1 = tmp;
22367         }
22368
22369         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22370             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22371           // FIXME: need symbolic constants for these magic numbers.
22372           // See X86ATTInstPrinter.cpp:printSSECC().
22373           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22374           if (Subtarget->hasAVX512()) {
22375             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22376                                          CMP01,
22377                                          DAG.getConstant(x86cc, DL, MVT::i8));
22378             if (N->getValueType(0) != MVT::i1)
22379               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22380                                  FSetCC);
22381             return FSetCC;
22382           }
22383           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22384                                               CMP00.getValueType(), CMP00, CMP01,
22385                                               DAG.getConstant(x86cc, DL,
22386                                                               MVT::i8));
22387
22388           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22389           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22390
22391           if (is64BitFP && !Subtarget->is64Bit()) {
22392             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22393             // 64-bit integer, since that's not a legal type. Since
22394             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22395             // bits, but can do this little dance to extract the lowest 32 bits
22396             // and work with those going forward.
22397             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22398                                            OnesOrZeroesF);
22399             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22400                                            Vector64);
22401             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22402                                         Vector32, DAG.getIntPtrConstant(0, DL));
22403             IntVT = MVT::i32;
22404           }
22405
22406           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22407                                               OnesOrZeroesF);
22408           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22409                                       DAG.getConstant(1, DL, IntVT));
22410           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22411                                               ANDed);
22412           return OneBitOfTruth;
22413         }
22414       }
22415     }
22416   }
22417   return SDValue();
22418 }
22419
22420 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22421 /// so it can be folded inside ANDNP.
22422 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22423   EVT VT = N->getValueType(0);
22424
22425   // Match direct AllOnes for 128 and 256-bit vectors
22426   if (ISD::isBuildVectorAllOnes(N))
22427     return true;
22428
22429   // Look through a bit convert.
22430   if (N->getOpcode() == ISD::BITCAST)
22431     N = N->getOperand(0).getNode();
22432
22433   // Sometimes the operand may come from a insert_subvector building a 256-bit
22434   // allones vector
22435   if (VT.is256BitVector() &&
22436       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22437     SDValue V1 = N->getOperand(0);
22438     SDValue V2 = N->getOperand(1);
22439
22440     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22441         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22442         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22443         ISD::isBuildVectorAllOnes(V2.getNode()))
22444       return true;
22445   }
22446
22447   return false;
22448 }
22449
22450 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22451 // register. In most cases we actually compare or select YMM-sized registers
22452 // and mixing the two types creates horrible code. This method optimizes
22453 // some of the transition sequences.
22454 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22455                                  TargetLowering::DAGCombinerInfo &DCI,
22456                                  const X86Subtarget *Subtarget) {
22457   EVT VT = N->getValueType(0);
22458   if (!VT.is256BitVector())
22459     return SDValue();
22460
22461   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22462           N->getOpcode() == ISD::ZERO_EXTEND ||
22463           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22464
22465   SDValue Narrow = N->getOperand(0);
22466   EVT NarrowVT = Narrow->getValueType(0);
22467   if (!NarrowVT.is128BitVector())
22468     return SDValue();
22469
22470   if (Narrow->getOpcode() != ISD::XOR &&
22471       Narrow->getOpcode() != ISD::AND &&
22472       Narrow->getOpcode() != ISD::OR)
22473     return SDValue();
22474
22475   SDValue N0  = Narrow->getOperand(0);
22476   SDValue N1  = Narrow->getOperand(1);
22477   SDLoc DL(Narrow);
22478
22479   // The Left side has to be a trunc.
22480   if (N0.getOpcode() != ISD::TRUNCATE)
22481     return SDValue();
22482
22483   // The type of the truncated inputs.
22484   EVT WideVT = N0->getOperand(0)->getValueType(0);
22485   if (WideVT != VT)
22486     return SDValue();
22487
22488   // The right side has to be a 'trunc' or a constant vector.
22489   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22490   ConstantSDNode *RHSConstSplat = nullptr;
22491   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22492     RHSConstSplat = RHSBV->getConstantSplatNode();
22493   if (!RHSTrunc && !RHSConstSplat)
22494     return SDValue();
22495
22496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22497
22498   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22499     return SDValue();
22500
22501   // Set N0 and N1 to hold the inputs to the new wide operation.
22502   N0 = N0->getOperand(0);
22503   if (RHSConstSplat) {
22504     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22505                      SDValue(RHSConstSplat, 0));
22506     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22507     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22508   } else if (RHSTrunc) {
22509     N1 = N1->getOperand(0);
22510   }
22511
22512   // Generate the wide operation.
22513   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22514   unsigned Opcode = N->getOpcode();
22515   switch (Opcode) {
22516   case ISD::ANY_EXTEND:
22517     return Op;
22518   case ISD::ZERO_EXTEND: {
22519     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22520     APInt Mask = APInt::getAllOnesValue(InBits);
22521     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22522     return DAG.getNode(ISD::AND, DL, VT,
22523                        Op, DAG.getConstant(Mask, DL, VT));
22524   }
22525   case ISD::SIGN_EXTEND:
22526     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22527                        Op, DAG.getValueType(NarrowVT));
22528   default:
22529     llvm_unreachable("Unexpected opcode");
22530   }
22531 }
22532
22533 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22534                                  TargetLowering::DAGCombinerInfo &DCI,
22535                                  const X86Subtarget *Subtarget) {
22536   SDValue N0 = N->getOperand(0);
22537   SDValue N1 = N->getOperand(1);
22538   SDLoc DL(N);
22539
22540   // A vector zext_in_reg may be represented as a shuffle,
22541   // feeding into a bitcast (this represents anyext) feeding into
22542   // an and with a mask.
22543   // We'd like to try to combine that into a shuffle with zero
22544   // plus a bitcast, removing the and.
22545   if (N0.getOpcode() != ISD::BITCAST ||
22546       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22547     return SDValue();
22548
22549   // The other side of the AND should be a splat of 2^C, where C
22550   // is the number of bits in the source type.
22551   if (N1.getOpcode() == ISD::BITCAST)
22552     N1 = N1.getOperand(0);
22553   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22554     return SDValue();
22555   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22556
22557   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22558   EVT SrcType = Shuffle->getValueType(0);
22559
22560   // We expect a single-source shuffle
22561   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22562     return SDValue();
22563
22564   unsigned SrcSize = SrcType.getScalarSizeInBits();
22565
22566   APInt SplatValue, SplatUndef;
22567   unsigned SplatBitSize;
22568   bool HasAnyUndefs;
22569   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22570                                 SplatBitSize, HasAnyUndefs))
22571     return SDValue();
22572
22573   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22574   // Make sure the splat matches the mask we expect
22575   if (SplatBitSize > ResSize ||
22576       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22577     return SDValue();
22578
22579   // Make sure the input and output size make sense
22580   if (SrcSize >= ResSize || ResSize % SrcSize)
22581     return SDValue();
22582
22583   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22584   // The number of u's between each two values depends on the ratio between
22585   // the source and dest type.
22586   unsigned ZextRatio = ResSize / SrcSize;
22587   bool IsZext = true;
22588   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22589     if (i % ZextRatio) {
22590       if (Shuffle->getMaskElt(i) > 0) {
22591         // Expected undef
22592         IsZext = false;
22593         break;
22594       }
22595     } else {
22596       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22597         // Expected element number
22598         IsZext = false;
22599         break;
22600       }
22601     }
22602   }
22603
22604   if (!IsZext)
22605     return SDValue();
22606
22607   // Ok, perform the transformation - replace the shuffle with
22608   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22609   // (instead of undef) where the k elements come from the zero vector.
22610   SmallVector<int, 8> Mask;
22611   unsigned NumElems = SrcType.getVectorNumElements();
22612   for (unsigned i = 0; i < NumElems; ++i)
22613     if (i % ZextRatio)
22614       Mask.push_back(NumElems);
22615     else
22616       Mask.push_back(i / ZextRatio);
22617
22618   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22619     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22620   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22621 }
22622
22623 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22624                                  TargetLowering::DAGCombinerInfo &DCI,
22625                                  const X86Subtarget *Subtarget) {
22626   if (DCI.isBeforeLegalizeOps())
22627     return SDValue();
22628
22629   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22630     return Zext;
22631
22632   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22633     return R;
22634
22635   EVT VT = N->getValueType(0);
22636   SDValue N0 = N->getOperand(0);
22637   SDValue N1 = N->getOperand(1);
22638   SDLoc DL(N);
22639
22640   // Create BEXTR instructions
22641   // BEXTR is ((X >> imm) & (2**size-1))
22642   if (VT == MVT::i32 || VT == MVT::i64) {
22643     // Check for BEXTR.
22644     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22645         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22646       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22647       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22648       if (MaskNode && ShiftNode) {
22649         uint64_t Mask = MaskNode->getZExtValue();
22650         uint64_t Shift = ShiftNode->getZExtValue();
22651         if (isMask_64(Mask)) {
22652           uint64_t MaskSize = countPopulation(Mask);
22653           if (Shift + MaskSize <= VT.getSizeInBits())
22654             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22655                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22656                                                VT));
22657         }
22658       }
22659     } // BEXTR
22660
22661     return SDValue();
22662   }
22663
22664   // Want to form ANDNP nodes:
22665   // 1) In the hopes of then easily combining them with OR and AND nodes
22666   //    to form PBLEND/PSIGN.
22667   // 2) To match ANDN packed intrinsics
22668   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22669     return SDValue();
22670
22671   // Check LHS for vnot
22672   if (N0.getOpcode() == ISD::XOR &&
22673       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22674       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22675     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22676
22677   // Check RHS for vnot
22678   if (N1.getOpcode() == ISD::XOR &&
22679       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22680       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22681     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22682
22683   return SDValue();
22684 }
22685
22686 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22687                                 TargetLowering::DAGCombinerInfo &DCI,
22688                                 const X86Subtarget *Subtarget) {
22689   if (DCI.isBeforeLegalizeOps())
22690     return SDValue();
22691
22692   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22693   if (R.getNode())
22694     return R;
22695
22696   SDValue N0 = N->getOperand(0);
22697   SDValue N1 = N->getOperand(1);
22698   EVT VT = N->getValueType(0);
22699
22700   // look for psign/blend
22701   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22702     if (!Subtarget->hasSSSE3() ||
22703         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22704       return SDValue();
22705
22706     // Canonicalize pandn to RHS
22707     if (N0.getOpcode() == X86ISD::ANDNP)
22708       std::swap(N0, N1);
22709     // or (and (m, y), (pandn m, x))
22710     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22711       SDValue Mask = N1.getOperand(0);
22712       SDValue X    = N1.getOperand(1);
22713       SDValue Y;
22714       if (N0.getOperand(0) == Mask)
22715         Y = N0.getOperand(1);
22716       if (N0.getOperand(1) == Mask)
22717         Y = N0.getOperand(0);
22718
22719       // Check to see if the mask appeared in both the AND and ANDNP and
22720       if (!Y.getNode())
22721         return SDValue();
22722
22723       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22724       // Look through mask bitcast.
22725       if (Mask.getOpcode() == ISD::BITCAST)
22726         Mask = Mask.getOperand(0);
22727       if (X.getOpcode() == ISD::BITCAST)
22728         X = X.getOperand(0);
22729       if (Y.getOpcode() == ISD::BITCAST)
22730         Y = Y.getOperand(0);
22731
22732       EVT MaskVT = Mask.getValueType();
22733
22734       // Validate that the Mask operand is a vector sra node.
22735       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22736       // there is no psrai.b
22737       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22738       unsigned SraAmt = ~0;
22739       if (Mask.getOpcode() == ISD::SRA) {
22740         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22741           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22742             SraAmt = AmtConst->getZExtValue();
22743       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22744         SDValue SraC = Mask.getOperand(1);
22745         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22746       }
22747       if ((SraAmt + 1) != EltBits)
22748         return SDValue();
22749
22750       SDLoc DL(N);
22751
22752       // Now we know we at least have a plendvb with the mask val.  See if
22753       // we can form a psignb/w/d.
22754       // psign = x.type == y.type == mask.type && y = sub(0, x);
22755       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22756           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22757           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22758         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22759                "Unsupported VT for PSIGN");
22760         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22761         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22762       }
22763       // PBLENDVB only available on SSE 4.1
22764       if (!Subtarget->hasSSE41())
22765         return SDValue();
22766
22767       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22768
22769       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22770       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22771       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22772       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22773       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22774     }
22775   }
22776
22777   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22778     return SDValue();
22779
22780   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22781   MachineFunction &MF = DAG.getMachineFunction();
22782   bool OptForSize =
22783       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22784
22785   // SHLD/SHRD instructions have lower register pressure, but on some
22786   // platforms they have higher latency than the equivalent
22787   // series of shifts/or that would otherwise be generated.
22788   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22789   // have higher latencies and we are not optimizing for size.
22790   if (!OptForSize && Subtarget->isSHLDSlow())
22791     return SDValue();
22792
22793   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22794     std::swap(N0, N1);
22795   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22796     return SDValue();
22797   if (!N0.hasOneUse() || !N1.hasOneUse())
22798     return SDValue();
22799
22800   SDValue ShAmt0 = N0.getOperand(1);
22801   if (ShAmt0.getValueType() != MVT::i8)
22802     return SDValue();
22803   SDValue ShAmt1 = N1.getOperand(1);
22804   if (ShAmt1.getValueType() != MVT::i8)
22805     return SDValue();
22806   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22807     ShAmt0 = ShAmt0.getOperand(0);
22808   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22809     ShAmt1 = ShAmt1.getOperand(0);
22810
22811   SDLoc DL(N);
22812   unsigned Opc = X86ISD::SHLD;
22813   SDValue Op0 = N0.getOperand(0);
22814   SDValue Op1 = N1.getOperand(0);
22815   if (ShAmt0.getOpcode() == ISD::SUB) {
22816     Opc = X86ISD::SHRD;
22817     std::swap(Op0, Op1);
22818     std::swap(ShAmt0, ShAmt1);
22819   }
22820
22821   unsigned Bits = VT.getSizeInBits();
22822   if (ShAmt1.getOpcode() == ISD::SUB) {
22823     SDValue Sum = ShAmt1.getOperand(0);
22824     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22825       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22826       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22827         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22828       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22829         return DAG.getNode(Opc, DL, VT,
22830                            Op0, Op1,
22831                            DAG.getNode(ISD::TRUNCATE, DL,
22832                                        MVT::i8, ShAmt0));
22833     }
22834   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22835     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22836     if (ShAmt0C &&
22837         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22838       return DAG.getNode(Opc, DL, VT,
22839                          N0.getOperand(0), N1.getOperand(0),
22840                          DAG.getNode(ISD::TRUNCATE, DL,
22841                                        MVT::i8, ShAmt0));
22842   }
22843
22844   return SDValue();
22845 }
22846
22847 // Generate NEG and CMOV for integer abs.
22848 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22849   EVT VT = N->getValueType(0);
22850
22851   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22852   // 8-bit integer abs to NEG and CMOV.
22853   if (VT.isInteger() && VT.getSizeInBits() == 8)
22854     return SDValue();
22855
22856   SDValue N0 = N->getOperand(0);
22857   SDValue N1 = N->getOperand(1);
22858   SDLoc DL(N);
22859
22860   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22861   // and change it to SUB and CMOV.
22862   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22863       N0.getOpcode() == ISD::ADD &&
22864       N0.getOperand(1) == N1 &&
22865       N1.getOpcode() == ISD::SRA &&
22866       N1.getOperand(0) == N0.getOperand(0))
22867     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22868       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22869         // Generate SUB & CMOV.
22870         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22871                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22872
22873         SDValue Ops[] = { N0.getOperand(0), Neg,
22874                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22875                           SDValue(Neg.getNode(), 1) };
22876         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22877       }
22878   return SDValue();
22879 }
22880
22881 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22882 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22883                                  TargetLowering::DAGCombinerInfo &DCI,
22884                                  const X86Subtarget *Subtarget) {
22885   if (DCI.isBeforeLegalizeOps())
22886     return SDValue();
22887
22888   if (Subtarget->hasCMov()) {
22889     SDValue RV = performIntegerAbsCombine(N, DAG);
22890     if (RV.getNode())
22891       return RV;
22892   }
22893
22894   return SDValue();
22895 }
22896
22897 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22898 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22899                                   TargetLowering::DAGCombinerInfo &DCI,
22900                                   const X86Subtarget *Subtarget) {
22901   LoadSDNode *Ld = cast<LoadSDNode>(N);
22902   EVT RegVT = Ld->getValueType(0);
22903   EVT MemVT = Ld->getMemoryVT();
22904   SDLoc dl(Ld);
22905   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22906
22907   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22908   // into two 16-byte operations.
22909   ISD::LoadExtType Ext = Ld->getExtensionType();
22910   unsigned Alignment = Ld->getAlignment();
22911   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22912   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22913       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22914     unsigned NumElems = RegVT.getVectorNumElements();
22915     if (NumElems < 2)
22916       return SDValue();
22917
22918     SDValue Ptr = Ld->getBasePtr();
22919     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22920
22921     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22922                                   NumElems/2);
22923     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22924                                 Ld->getPointerInfo(), Ld->isVolatile(),
22925                                 Ld->isNonTemporal(), Ld->isInvariant(),
22926                                 Alignment);
22927     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22928     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22929                                 Ld->getPointerInfo(), Ld->isVolatile(),
22930                                 Ld->isNonTemporal(), Ld->isInvariant(),
22931                                 std::min(16U, Alignment));
22932     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22933                              Load1.getValue(1),
22934                              Load2.getValue(1));
22935
22936     SDValue NewVec = DAG.getUNDEF(RegVT);
22937     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22938     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22939     return DCI.CombineTo(N, NewVec, TF, true);
22940   }
22941
22942   return SDValue();
22943 }
22944
22945 /// PerformMLOADCombine - Resolve extending loads
22946 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22947                                    TargetLowering::DAGCombinerInfo &DCI,
22948                                    const X86Subtarget *Subtarget) {
22949   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22950   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22951     return SDValue();
22952
22953   EVT VT = Mld->getValueType(0);
22954   unsigned NumElems = VT.getVectorNumElements();
22955   EVT LdVT = Mld->getMemoryVT();
22956   SDLoc dl(Mld);
22957
22958   assert(LdVT != VT && "Cannot extend to the same type");
22959   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22960   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22961   // From, To sizes and ElemCount must be pow of two
22962   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22963     "Unexpected size for extending masked load");
22964
22965   unsigned SizeRatio  = ToSz / FromSz;
22966   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22967
22968   // Create a type on which we perform the shuffle
22969   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22970           LdVT.getScalarType(), NumElems*SizeRatio);
22971   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22972
22973   // Convert Src0 value
22974   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22975   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22976     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22977     for (unsigned i = 0; i != NumElems; ++i)
22978       ShuffleVec[i] = i * SizeRatio;
22979
22980     // Can't shuffle using an illegal type.
22981     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22982             && "WideVecVT should be legal");
22983     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22984                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22985   }
22986   // Prepare the new mask
22987   SDValue NewMask;
22988   SDValue Mask = Mld->getMask();
22989   if (Mask.getValueType() == VT) {
22990     // Mask and original value have the same type
22991     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22992     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22993     for (unsigned i = 0; i != NumElems; ++i)
22994       ShuffleVec[i] = i * SizeRatio;
22995     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22996       ShuffleVec[i] = NumElems*SizeRatio;
22997     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22998                                    DAG.getConstant(0, dl, WideVecVT),
22999                                    &ShuffleVec[0]);
23000   }
23001   else {
23002     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23003     unsigned WidenNumElts = NumElems*SizeRatio;
23004     unsigned MaskNumElts = VT.getVectorNumElements();
23005     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23006                                      WidenNumElts);
23007
23008     unsigned NumConcat = WidenNumElts / MaskNumElts;
23009     SmallVector<SDValue, 16> Ops(NumConcat);
23010     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23011     Ops[0] = Mask;
23012     for (unsigned i = 1; i != NumConcat; ++i)
23013       Ops[i] = ZeroVal;
23014
23015     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23016   }
23017
23018   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23019                                      Mld->getBasePtr(), NewMask, WideSrc0,
23020                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23021                                      ISD::NON_EXTLOAD);
23022   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23023   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23024
23025 }
23026 /// PerformMSTORECombine - Resolve truncating stores
23027 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23028                                     const X86Subtarget *Subtarget) {
23029   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23030   if (!Mst->isTruncatingStore())
23031     return SDValue();
23032
23033   EVT VT = Mst->getValue().getValueType();
23034   unsigned NumElems = VT.getVectorNumElements();
23035   EVT StVT = Mst->getMemoryVT();
23036   SDLoc dl(Mst);
23037
23038   assert(StVT != VT && "Cannot truncate to the same type");
23039   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23040   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23041
23042   // From, To sizes and ElemCount must be pow of two
23043   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23044     "Unexpected size for truncating masked store");
23045   // We are going to use the original vector elt for storing.
23046   // Accumulated smaller vector elements must be a multiple of the store size.
23047   assert (((NumElems * FromSz) % ToSz) == 0 &&
23048           "Unexpected ratio for truncating masked store");
23049
23050   unsigned SizeRatio  = FromSz / ToSz;
23051   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23052
23053   // Create a type on which we perform the shuffle
23054   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23055           StVT.getScalarType(), NumElems*SizeRatio);
23056
23057   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23058
23059   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23060   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23061   for (unsigned i = 0; i != NumElems; ++i)
23062     ShuffleVec[i] = i * SizeRatio;
23063
23064   // Can't shuffle using an illegal type.
23065   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23066           && "WideVecVT should be legal");
23067
23068   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23069                                         DAG.getUNDEF(WideVecVT),
23070                                         &ShuffleVec[0]);
23071
23072   SDValue NewMask;
23073   SDValue Mask = Mst->getMask();
23074   if (Mask.getValueType() == VT) {
23075     // Mask and original value have the same type
23076     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23077     for (unsigned i = 0; i != NumElems; ++i)
23078       ShuffleVec[i] = i * SizeRatio;
23079     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23080       ShuffleVec[i] = NumElems*SizeRatio;
23081     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23082                                    DAG.getConstant(0, dl, WideVecVT),
23083                                    &ShuffleVec[0]);
23084   }
23085   else {
23086     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23087     unsigned WidenNumElts = NumElems*SizeRatio;
23088     unsigned MaskNumElts = VT.getVectorNumElements();
23089     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23090                                      WidenNumElts);
23091
23092     unsigned NumConcat = WidenNumElts / MaskNumElts;
23093     SmallVector<SDValue, 16> Ops(NumConcat);
23094     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23095     Ops[0] = Mask;
23096     for (unsigned i = 1; i != NumConcat; ++i)
23097       Ops[i] = ZeroVal;
23098
23099     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23100   }
23101
23102   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23103                             NewMask, StVT, Mst->getMemOperand(), false);
23104 }
23105 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23106 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23107                                    const X86Subtarget *Subtarget) {
23108   StoreSDNode *St = cast<StoreSDNode>(N);
23109   EVT VT = St->getValue().getValueType();
23110   EVT StVT = St->getMemoryVT();
23111   SDLoc dl(St);
23112   SDValue StoredVal = St->getOperand(1);
23113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23114
23115   // If we are saving a concatenation of two XMM registers and 32-byte stores
23116   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23117   unsigned Alignment = St->getAlignment();
23118   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23119   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23120       StVT == VT && !IsAligned) {
23121     unsigned NumElems = VT.getVectorNumElements();
23122     if (NumElems < 2)
23123       return SDValue();
23124
23125     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23126     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23127
23128     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23129     SDValue Ptr0 = St->getBasePtr();
23130     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23131
23132     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23133                                 St->getPointerInfo(), St->isVolatile(),
23134                                 St->isNonTemporal(), Alignment);
23135     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23136                                 St->getPointerInfo(), St->isVolatile(),
23137                                 St->isNonTemporal(),
23138                                 std::min(16U, Alignment));
23139     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23140   }
23141
23142   // Optimize trunc store (of multiple scalars) to shuffle and store.
23143   // First, pack all of the elements in one place. Next, store to memory
23144   // in fewer chunks.
23145   if (St->isTruncatingStore() && VT.isVector()) {
23146     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23147     unsigned NumElems = VT.getVectorNumElements();
23148     assert(StVT != VT && "Cannot truncate to the same type");
23149     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23150     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23151
23152     // From, To sizes and ElemCount must be pow of two
23153     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23154     // We are going to use the original vector elt for storing.
23155     // Accumulated smaller vector elements must be a multiple of the store size.
23156     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23157
23158     unsigned SizeRatio  = FromSz / ToSz;
23159
23160     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23161
23162     // Create a type on which we perform the shuffle
23163     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23164             StVT.getScalarType(), NumElems*SizeRatio);
23165
23166     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23167
23168     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23169     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23170     for (unsigned i = 0; i != NumElems; ++i)
23171       ShuffleVec[i] = i * SizeRatio;
23172
23173     // Can't shuffle using an illegal type.
23174     if (!TLI.isTypeLegal(WideVecVT))
23175       return SDValue();
23176
23177     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23178                                          DAG.getUNDEF(WideVecVT),
23179                                          &ShuffleVec[0]);
23180     // At this point all of the data is stored at the bottom of the
23181     // register. We now need to save it to mem.
23182
23183     // Find the largest store unit
23184     MVT StoreType = MVT::i8;
23185     for (MVT Tp : MVT::integer_valuetypes()) {
23186       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23187         StoreType = Tp;
23188     }
23189
23190     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23191     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23192         (64 <= NumElems * ToSz))
23193       StoreType = MVT::f64;
23194
23195     // Bitcast the original vector into a vector of store-size units
23196     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23197             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23198     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23199     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23200     SmallVector<SDValue, 8> Chains;
23201     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23202                                         TLI.getPointerTy());
23203     SDValue Ptr = St->getBasePtr();
23204
23205     // Perform one or more big stores into memory.
23206     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23207       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23208                                    StoreType, ShuffWide,
23209                                    DAG.getIntPtrConstant(i, dl));
23210       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23211                                 St->getPointerInfo(), St->isVolatile(),
23212                                 St->isNonTemporal(), St->getAlignment());
23213       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23214       Chains.push_back(Ch);
23215     }
23216
23217     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23218   }
23219
23220   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23221   // the FP state in cases where an emms may be missing.
23222   // A preferable solution to the general problem is to figure out the right
23223   // places to insert EMMS.  This qualifies as a quick hack.
23224
23225   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23226   if (VT.getSizeInBits() != 64)
23227     return SDValue();
23228
23229   const Function *F = DAG.getMachineFunction().getFunction();
23230   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23231   bool F64IsLegal =
23232       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23233   if ((VT.isVector() ||
23234        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23235       isa<LoadSDNode>(St->getValue()) &&
23236       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23237       St->getChain().hasOneUse() && !St->isVolatile()) {
23238     SDNode* LdVal = St->getValue().getNode();
23239     LoadSDNode *Ld = nullptr;
23240     int TokenFactorIndex = -1;
23241     SmallVector<SDValue, 8> Ops;
23242     SDNode* ChainVal = St->getChain().getNode();
23243     // Must be a store of a load.  We currently handle two cases:  the load
23244     // is a direct child, and it's under an intervening TokenFactor.  It is
23245     // possible to dig deeper under nested TokenFactors.
23246     if (ChainVal == LdVal)
23247       Ld = cast<LoadSDNode>(St->getChain());
23248     else if (St->getValue().hasOneUse() &&
23249              ChainVal->getOpcode() == ISD::TokenFactor) {
23250       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23251         if (ChainVal->getOperand(i).getNode() == LdVal) {
23252           TokenFactorIndex = i;
23253           Ld = cast<LoadSDNode>(St->getValue());
23254         } else
23255           Ops.push_back(ChainVal->getOperand(i));
23256       }
23257     }
23258
23259     if (!Ld || !ISD::isNormalLoad(Ld))
23260       return SDValue();
23261
23262     // If this is not the MMX case, i.e. we are just turning i64 load/store
23263     // into f64 load/store, avoid the transformation if there are multiple
23264     // uses of the loaded value.
23265     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23266       return SDValue();
23267
23268     SDLoc LdDL(Ld);
23269     SDLoc StDL(N);
23270     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23271     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23272     // pair instead.
23273     if (Subtarget->is64Bit() || F64IsLegal) {
23274       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23275       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23276                                   Ld->getPointerInfo(), Ld->isVolatile(),
23277                                   Ld->isNonTemporal(), Ld->isInvariant(),
23278                                   Ld->getAlignment());
23279       SDValue NewChain = NewLd.getValue(1);
23280       if (TokenFactorIndex != -1) {
23281         Ops.push_back(NewChain);
23282         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23283       }
23284       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23285                           St->getPointerInfo(),
23286                           St->isVolatile(), St->isNonTemporal(),
23287                           St->getAlignment());
23288     }
23289
23290     // Otherwise, lower to two pairs of 32-bit loads / stores.
23291     SDValue LoAddr = Ld->getBasePtr();
23292     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23293                                  DAG.getConstant(4, LdDL, MVT::i32));
23294
23295     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23296                                Ld->getPointerInfo(),
23297                                Ld->isVolatile(), Ld->isNonTemporal(),
23298                                Ld->isInvariant(), Ld->getAlignment());
23299     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23300                                Ld->getPointerInfo().getWithOffset(4),
23301                                Ld->isVolatile(), Ld->isNonTemporal(),
23302                                Ld->isInvariant(),
23303                                MinAlign(Ld->getAlignment(), 4));
23304
23305     SDValue NewChain = LoLd.getValue(1);
23306     if (TokenFactorIndex != -1) {
23307       Ops.push_back(LoLd);
23308       Ops.push_back(HiLd);
23309       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23310     }
23311
23312     LoAddr = St->getBasePtr();
23313     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23314                          DAG.getConstant(4, StDL, MVT::i32));
23315
23316     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23317                                 St->getPointerInfo(),
23318                                 St->isVolatile(), St->isNonTemporal(),
23319                                 St->getAlignment());
23320     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23321                                 St->getPointerInfo().getWithOffset(4),
23322                                 St->isVolatile(),
23323                                 St->isNonTemporal(),
23324                                 MinAlign(St->getAlignment(), 4));
23325     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23326   }
23327
23328   // This is similar to the above case, but here we handle a scalar 64-bit
23329   // integer store that is extracted from a vector on a 32-bit target.
23330   // If we have SSE2, then we can treat it like a floating-point double
23331   // to get past legalization. The execution dependencies fixup pass will
23332   // choose the optimal machine instruction for the store if this really is
23333   // an integer or v2f32 rather than an f64.
23334   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23335       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23336     SDValue OldExtract = St->getOperand(1);
23337     SDValue ExtOp0 = OldExtract.getOperand(0);
23338     unsigned VecSize = ExtOp0.getValueSizeInBits();
23339     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23340     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23341     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23342                                      BitCast, OldExtract.getOperand(1));
23343     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23344                         St->getPointerInfo(), St->isVolatile(),
23345                         St->isNonTemporal(), St->getAlignment());
23346   }
23347
23348   return SDValue();
23349 }
23350
23351 /// Return 'true' if this vector operation is "horizontal"
23352 /// and return the operands for the horizontal operation in LHS and RHS.  A
23353 /// horizontal operation performs the binary operation on successive elements
23354 /// of its first operand, then on successive elements of its second operand,
23355 /// returning the resulting values in a vector.  For example, if
23356 ///   A = < float a0, float a1, float a2, float a3 >
23357 /// and
23358 ///   B = < float b0, float b1, float b2, float b3 >
23359 /// then the result of doing a horizontal operation on A and B is
23360 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23361 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23362 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23363 /// set to A, RHS to B, and the routine returns 'true'.
23364 /// Note that the binary operation should have the property that if one of the
23365 /// operands is UNDEF then the result is UNDEF.
23366 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23367   // Look for the following pattern: if
23368   //   A = < float a0, float a1, float a2, float a3 >
23369   //   B = < float b0, float b1, float b2, float b3 >
23370   // and
23371   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23372   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23373   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23374   // which is A horizontal-op B.
23375
23376   // At least one of the operands should be a vector shuffle.
23377   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23378       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23379     return false;
23380
23381   MVT VT = LHS.getSimpleValueType();
23382
23383   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23384          "Unsupported vector type for horizontal add/sub");
23385
23386   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23387   // operate independently on 128-bit lanes.
23388   unsigned NumElts = VT.getVectorNumElements();
23389   unsigned NumLanes = VT.getSizeInBits()/128;
23390   unsigned NumLaneElts = NumElts / NumLanes;
23391   assert((NumLaneElts % 2 == 0) &&
23392          "Vector type should have an even number of elements in each lane");
23393   unsigned HalfLaneElts = NumLaneElts/2;
23394
23395   // View LHS in the form
23396   //   LHS = VECTOR_SHUFFLE A, B, LMask
23397   // If LHS is not a shuffle then pretend it is the shuffle
23398   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23399   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23400   // type VT.
23401   SDValue A, B;
23402   SmallVector<int, 16> LMask(NumElts);
23403   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23404     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23405       A = LHS.getOperand(0);
23406     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23407       B = LHS.getOperand(1);
23408     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23409     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23410   } else {
23411     if (LHS.getOpcode() != ISD::UNDEF)
23412       A = LHS;
23413     for (unsigned i = 0; i != NumElts; ++i)
23414       LMask[i] = i;
23415   }
23416
23417   // Likewise, view RHS in the form
23418   //   RHS = VECTOR_SHUFFLE C, D, RMask
23419   SDValue C, D;
23420   SmallVector<int, 16> RMask(NumElts);
23421   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23422     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23423       C = RHS.getOperand(0);
23424     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23425       D = RHS.getOperand(1);
23426     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23427     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23428   } else {
23429     if (RHS.getOpcode() != ISD::UNDEF)
23430       C = RHS;
23431     for (unsigned i = 0; i != NumElts; ++i)
23432       RMask[i] = i;
23433   }
23434
23435   // Check that the shuffles are both shuffling the same vectors.
23436   if (!(A == C && B == D) && !(A == D && B == C))
23437     return false;
23438
23439   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23440   if (!A.getNode() && !B.getNode())
23441     return false;
23442
23443   // If A and B occur in reverse order in RHS, then "swap" them (which means
23444   // rewriting the mask).
23445   if (A != C)
23446     ShuffleVectorSDNode::commuteMask(RMask);
23447
23448   // At this point LHS and RHS are equivalent to
23449   //   LHS = VECTOR_SHUFFLE A, B, LMask
23450   //   RHS = VECTOR_SHUFFLE A, B, RMask
23451   // Check that the masks correspond to performing a horizontal operation.
23452   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23453     for (unsigned i = 0; i != NumLaneElts; ++i) {
23454       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23455
23456       // Ignore any UNDEF components.
23457       if (LIdx < 0 || RIdx < 0 ||
23458           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23459           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23460         continue;
23461
23462       // Check that successive elements are being operated on.  If not, this is
23463       // not a horizontal operation.
23464       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23465       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23466       if (!(LIdx == Index && RIdx == Index + 1) &&
23467           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23468         return false;
23469     }
23470   }
23471
23472   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23473   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23474   return true;
23475 }
23476
23477 /// Do target-specific dag combines on floating point adds.
23478 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23479                                   const X86Subtarget *Subtarget) {
23480   EVT VT = N->getValueType(0);
23481   SDValue LHS = N->getOperand(0);
23482   SDValue RHS = N->getOperand(1);
23483
23484   // Try to synthesize horizontal adds from adds of shuffles.
23485   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23486        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23487       isHorizontalBinOp(LHS, RHS, true))
23488     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23489   return SDValue();
23490 }
23491
23492 /// Do target-specific dag combines on floating point subs.
23493 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23494                                   const X86Subtarget *Subtarget) {
23495   EVT VT = N->getValueType(0);
23496   SDValue LHS = N->getOperand(0);
23497   SDValue RHS = N->getOperand(1);
23498
23499   // Try to synthesize horizontal subs from subs of shuffles.
23500   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23501        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23502       isHorizontalBinOp(LHS, RHS, false))
23503     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23504   return SDValue();
23505 }
23506
23507 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23508 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23509   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23510
23511   // F[X]OR(0.0, x) -> x
23512   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23513     if (C->getValueAPF().isPosZero())
23514       return N->getOperand(1);
23515
23516   // F[X]OR(x, 0.0) -> x
23517   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23518     if (C->getValueAPF().isPosZero())
23519       return N->getOperand(0);
23520   return SDValue();
23521 }
23522
23523 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23524 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23525   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23526
23527   // Only perform optimizations if UnsafeMath is used.
23528   if (!DAG.getTarget().Options.UnsafeFPMath)
23529     return SDValue();
23530
23531   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23532   // into FMINC and FMAXC, which are Commutative operations.
23533   unsigned NewOp = 0;
23534   switch (N->getOpcode()) {
23535     default: llvm_unreachable("unknown opcode");
23536     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23537     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23538   }
23539
23540   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23541                      N->getOperand(0), N->getOperand(1));
23542 }
23543
23544 /// Do target-specific dag combines on X86ISD::FAND nodes.
23545 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23546   // FAND(0.0, x) -> 0.0
23547   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23548     if (C->getValueAPF().isPosZero())
23549       return N->getOperand(0);
23550
23551   // FAND(x, 0.0) -> 0.0
23552   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23553     if (C->getValueAPF().isPosZero())
23554       return N->getOperand(1);
23555
23556   return SDValue();
23557 }
23558
23559 /// Do target-specific dag combines on X86ISD::FANDN nodes
23560 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23561   // FANDN(0.0, x) -> x
23562   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23563     if (C->getValueAPF().isPosZero())
23564       return N->getOperand(1);
23565
23566   // FANDN(x, 0.0) -> 0.0
23567   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23568     if (C->getValueAPF().isPosZero())
23569       return N->getOperand(1);
23570
23571   return SDValue();
23572 }
23573
23574 static SDValue PerformBTCombine(SDNode *N,
23575                                 SelectionDAG &DAG,
23576                                 TargetLowering::DAGCombinerInfo &DCI) {
23577   // BT ignores high bits in the bit index operand.
23578   SDValue Op1 = N->getOperand(1);
23579   if (Op1.hasOneUse()) {
23580     unsigned BitWidth = Op1.getValueSizeInBits();
23581     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23582     APInt KnownZero, KnownOne;
23583     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23584                                           !DCI.isBeforeLegalizeOps());
23585     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23586     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23587         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23588       DCI.CommitTargetLoweringOpt(TLO);
23589   }
23590   return SDValue();
23591 }
23592
23593 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23594   SDValue Op = N->getOperand(0);
23595   if (Op.getOpcode() == ISD::BITCAST)
23596     Op = Op.getOperand(0);
23597   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23598   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23599       VT.getVectorElementType().getSizeInBits() ==
23600       OpVT.getVectorElementType().getSizeInBits()) {
23601     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23602   }
23603   return SDValue();
23604 }
23605
23606 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23607                                                const X86Subtarget *Subtarget) {
23608   EVT VT = N->getValueType(0);
23609   if (!VT.isVector())
23610     return SDValue();
23611
23612   SDValue N0 = N->getOperand(0);
23613   SDValue N1 = N->getOperand(1);
23614   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23615   SDLoc dl(N);
23616
23617   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23618   // both SSE and AVX2 since there is no sign-extended shift right
23619   // operation on a vector with 64-bit elements.
23620   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23621   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23622   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23623       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23624     SDValue N00 = N0.getOperand(0);
23625
23626     // EXTLOAD has a better solution on AVX2,
23627     // it may be replaced with X86ISD::VSEXT node.
23628     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23629       if (!ISD::isNormalLoad(N00.getNode()))
23630         return SDValue();
23631
23632     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23633         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23634                                   N00, N1);
23635       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23636     }
23637   }
23638   return SDValue();
23639 }
23640
23641 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23642                                   TargetLowering::DAGCombinerInfo &DCI,
23643                                   const X86Subtarget *Subtarget) {
23644   SDValue N0 = N->getOperand(0);
23645   EVT VT = N->getValueType(0);
23646
23647   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23648   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23649   // This exposes the sext to the sdivrem lowering, so that it directly extends
23650   // from AH (which we otherwise need to do contortions to access).
23651   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23652       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23653     SDLoc dl(N);
23654     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23655     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23656                             N0.getOperand(0), N0.getOperand(1));
23657     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23658     return R.getValue(1);
23659   }
23660
23661   if (!DCI.isBeforeLegalizeOps())
23662     return SDValue();
23663
23664   if (!Subtarget->hasFp256())
23665     return SDValue();
23666
23667   if (VT.isVector() && VT.getSizeInBits() == 256) {
23668     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23669     if (R.getNode())
23670       return R;
23671   }
23672
23673   return SDValue();
23674 }
23675
23676 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23677                                  const X86Subtarget* Subtarget) {
23678   SDLoc dl(N);
23679   EVT VT = N->getValueType(0);
23680
23681   // Let legalize expand this if it isn't a legal type yet.
23682   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23683     return SDValue();
23684
23685   EVT ScalarVT = VT.getScalarType();
23686   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23687       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23688     return SDValue();
23689
23690   SDValue A = N->getOperand(0);
23691   SDValue B = N->getOperand(1);
23692   SDValue C = N->getOperand(2);
23693
23694   bool NegA = (A.getOpcode() == ISD::FNEG);
23695   bool NegB = (B.getOpcode() == ISD::FNEG);
23696   bool NegC = (C.getOpcode() == ISD::FNEG);
23697
23698   // Negative multiplication when NegA xor NegB
23699   bool NegMul = (NegA != NegB);
23700   if (NegA)
23701     A = A.getOperand(0);
23702   if (NegB)
23703     B = B.getOperand(0);
23704   if (NegC)
23705     C = C.getOperand(0);
23706
23707   unsigned Opcode;
23708   if (!NegMul)
23709     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23710   else
23711     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23712
23713   return DAG.getNode(Opcode, dl, VT, A, B, C);
23714 }
23715
23716 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23717                                   TargetLowering::DAGCombinerInfo &DCI,
23718                                   const X86Subtarget *Subtarget) {
23719   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23720   //           (and (i32 x86isd::setcc_carry), 1)
23721   // This eliminates the zext. This transformation is necessary because
23722   // ISD::SETCC is always legalized to i8.
23723   SDLoc dl(N);
23724   SDValue N0 = N->getOperand(0);
23725   EVT VT = N->getValueType(0);
23726
23727   if (N0.getOpcode() == ISD::AND &&
23728       N0.hasOneUse() &&
23729       N0.getOperand(0).hasOneUse()) {
23730     SDValue N00 = N0.getOperand(0);
23731     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23732       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23733       if (!C || C->getZExtValue() != 1)
23734         return SDValue();
23735       return DAG.getNode(ISD::AND, dl, VT,
23736                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23737                                      N00.getOperand(0), N00.getOperand(1)),
23738                          DAG.getConstant(1, dl, VT));
23739     }
23740   }
23741
23742   if (N0.getOpcode() == ISD::TRUNCATE &&
23743       N0.hasOneUse() &&
23744       N0.getOperand(0).hasOneUse()) {
23745     SDValue N00 = N0.getOperand(0);
23746     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23747       return DAG.getNode(ISD::AND, dl, VT,
23748                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23749                                      N00.getOperand(0), N00.getOperand(1)),
23750                          DAG.getConstant(1, dl, VT));
23751     }
23752   }
23753   if (VT.is256BitVector()) {
23754     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23755     if (R.getNode())
23756       return R;
23757   }
23758
23759   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23760   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23761   // This exposes the zext to the udivrem lowering, so that it directly extends
23762   // from AH (which we otherwise need to do contortions to access).
23763   if (N0.getOpcode() == ISD::UDIVREM &&
23764       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23765       (VT == MVT::i32 || VT == MVT::i64)) {
23766     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23767     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23768                             N0.getOperand(0), N0.getOperand(1));
23769     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23770     return R.getValue(1);
23771   }
23772
23773   return SDValue();
23774 }
23775
23776 // Optimize x == -y --> x+y == 0
23777 //          x != -y --> x+y != 0
23778 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23779                                       const X86Subtarget* Subtarget) {
23780   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23781   SDValue LHS = N->getOperand(0);
23782   SDValue RHS = N->getOperand(1);
23783   EVT VT = N->getValueType(0);
23784   SDLoc DL(N);
23785
23786   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23787     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23788       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23789         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23790                                    LHS.getOperand(1));
23791         return DAG.getSetCC(DL, N->getValueType(0), addV,
23792                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23793       }
23794   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23795     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23796       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23797         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23798                                    RHS.getOperand(1));
23799         return DAG.getSetCC(DL, N->getValueType(0), addV,
23800                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23801       }
23802
23803   if (VT.getScalarType() == MVT::i1 &&
23804       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23805     bool IsSEXT0 =
23806         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23807         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23808     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23809
23810     if (!IsSEXT0 || !IsVZero1) {
23811       // Swap the operands and update the condition code.
23812       std::swap(LHS, RHS);
23813       CC = ISD::getSetCCSwappedOperands(CC);
23814
23815       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23816                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23817       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23818     }
23819
23820     if (IsSEXT0 && IsVZero1) {
23821       assert(VT == LHS.getOperand(0).getValueType() &&
23822              "Uexpected operand type");
23823       if (CC == ISD::SETGT)
23824         return DAG.getConstant(0, DL, VT);
23825       if (CC == ISD::SETLE)
23826         return DAG.getConstant(1, DL, VT);
23827       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23828         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23829
23830       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23831              "Unexpected condition code!");
23832       return LHS.getOperand(0);
23833     }
23834   }
23835
23836   return SDValue();
23837 }
23838
23839 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23840                                          SelectionDAG &DAG) {
23841   SDLoc dl(Load);
23842   MVT VT = Load->getSimpleValueType(0);
23843   MVT EVT = VT.getVectorElementType();
23844   SDValue Addr = Load->getOperand(1);
23845   SDValue NewAddr = DAG.getNode(
23846       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23847       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23848                       Addr.getSimpleValueType()));
23849
23850   SDValue NewLoad =
23851       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23852                   DAG.getMachineFunction().getMachineMemOperand(
23853                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23854   return NewLoad;
23855 }
23856
23857 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23858                                       const X86Subtarget *Subtarget) {
23859   SDLoc dl(N);
23860   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23861   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23862          "X86insertps is only defined for v4x32");
23863
23864   SDValue Ld = N->getOperand(1);
23865   if (MayFoldLoad(Ld)) {
23866     // Extract the countS bits from the immediate so we can get the proper
23867     // address when narrowing the vector load to a specific element.
23868     // When the second source op is a memory address, insertps doesn't use
23869     // countS and just gets an f32 from that address.
23870     unsigned DestIndex =
23871         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23872
23873     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23874
23875     // Create this as a scalar to vector to match the instruction pattern.
23876     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23877     // countS bits are ignored when loading from memory on insertps, which
23878     // means we don't need to explicitly set them to 0.
23879     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23880                        LoadScalarToVector, N->getOperand(2));
23881   }
23882   return SDValue();
23883 }
23884
23885 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23886   SDValue V0 = N->getOperand(0);
23887   SDValue V1 = N->getOperand(1);
23888   SDLoc DL(N);
23889   EVT VT = N->getValueType(0);
23890
23891   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23892   // operands and changing the mask to 1. This saves us a bunch of
23893   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23894   // x86InstrInfo knows how to commute this back after instruction selection
23895   // if it would help register allocation.
23896
23897   // TODO: If optimizing for size or a processor that doesn't suffer from
23898   // partial register update stalls, this should be transformed into a MOVSD
23899   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23900
23901   if (VT == MVT::v2f64)
23902     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23903       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23904         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23905         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23906       }
23907
23908   return SDValue();
23909 }
23910
23911 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23912 // as "sbb reg,reg", since it can be extended without zext and produces
23913 // an all-ones bit which is more useful than 0/1 in some cases.
23914 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23915                                MVT VT) {
23916   if (VT == MVT::i8)
23917     return DAG.getNode(ISD::AND, DL, VT,
23918                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23919                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23920                                    EFLAGS),
23921                        DAG.getConstant(1, DL, VT));
23922   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23923   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23924                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23925                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23926                                  EFLAGS));
23927 }
23928
23929 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23930 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23931                                    TargetLowering::DAGCombinerInfo &DCI,
23932                                    const X86Subtarget *Subtarget) {
23933   SDLoc DL(N);
23934   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23935   SDValue EFLAGS = N->getOperand(1);
23936
23937   if (CC == X86::COND_A) {
23938     // Try to convert COND_A into COND_B in an attempt to facilitate
23939     // materializing "setb reg".
23940     //
23941     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23942     // cannot take an immediate as its first operand.
23943     //
23944     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23945         EFLAGS.getValueType().isInteger() &&
23946         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23947       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23948                                    EFLAGS.getNode()->getVTList(),
23949                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23950       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23951       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23952     }
23953   }
23954
23955   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23956   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23957   // cases.
23958   if (CC == X86::COND_B)
23959     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23960
23961   SDValue Flags;
23962
23963   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23964   if (Flags.getNode()) {
23965     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23966     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23967   }
23968
23969   return SDValue();
23970 }
23971
23972 // Optimize branch condition evaluation.
23973 //
23974 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23975                                     TargetLowering::DAGCombinerInfo &DCI,
23976                                     const X86Subtarget *Subtarget) {
23977   SDLoc DL(N);
23978   SDValue Chain = N->getOperand(0);
23979   SDValue Dest = N->getOperand(1);
23980   SDValue EFLAGS = N->getOperand(3);
23981   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23982
23983   SDValue Flags;
23984
23985   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23986   if (Flags.getNode()) {
23987     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23988     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23989                        Flags);
23990   }
23991
23992   return SDValue();
23993 }
23994
23995 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23996                                                          SelectionDAG &DAG) {
23997   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23998   // optimize away operation when it's from a constant.
23999   //
24000   // The general transformation is:
24001   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24002   //       AND(VECTOR_CMP(x,y), constant2)
24003   //    constant2 = UNARYOP(constant)
24004
24005   // Early exit if this isn't a vector operation, the operand of the
24006   // unary operation isn't a bitwise AND, or if the sizes of the operations
24007   // aren't the same.
24008   EVT VT = N->getValueType(0);
24009   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24010       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24011       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24012     return SDValue();
24013
24014   // Now check that the other operand of the AND is a constant. We could
24015   // make the transformation for non-constant splats as well, but it's unclear
24016   // that would be a benefit as it would not eliminate any operations, just
24017   // perform one more step in scalar code before moving to the vector unit.
24018   if (BuildVectorSDNode *BV =
24019           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24020     // Bail out if the vector isn't a constant.
24021     if (!BV->isConstant())
24022       return SDValue();
24023
24024     // Everything checks out. Build up the new and improved node.
24025     SDLoc DL(N);
24026     EVT IntVT = BV->getValueType(0);
24027     // Create a new constant of the appropriate type for the transformed
24028     // DAG.
24029     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24030     // The AND node needs bitcasts to/from an integer vector type around it.
24031     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24032     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24033                                  N->getOperand(0)->getOperand(0), MaskConst);
24034     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24035     return Res;
24036   }
24037
24038   return SDValue();
24039 }
24040
24041 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24042                                         const X86Subtarget *Subtarget) {
24043   // First try to optimize away the conversion entirely when it's
24044   // conditionally from a constant. Vectors only.
24045   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24046   if (Res != SDValue())
24047     return Res;
24048
24049   // Now move on to more general possibilities.
24050   SDValue Op0 = N->getOperand(0);
24051   EVT InVT = Op0->getValueType(0);
24052
24053   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24054   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24055     SDLoc dl(N);
24056     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24057     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24058     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24059   }
24060
24061   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24062   // a 32-bit target where SSE doesn't support i64->FP operations.
24063   if (Op0.getOpcode() == ISD::LOAD) {
24064     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24065     EVT VT = Ld->getValueType(0);
24066
24067     // This transformation is not supported if the result type is f16
24068     if (N->getValueType(0) == MVT::f16)
24069       return SDValue();
24070
24071     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24072         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24073         !Subtarget->is64Bit() && VT == MVT::i64) {
24074       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24075           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24076       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24077       return FILDChain;
24078     }
24079   }
24080   return SDValue();
24081 }
24082
24083 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24084 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24085                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24086   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24087   // the result is either zero or one (depending on the input carry bit).
24088   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24089   if (X86::isZeroNode(N->getOperand(0)) &&
24090       X86::isZeroNode(N->getOperand(1)) &&
24091       // We don't have a good way to replace an EFLAGS use, so only do this when
24092       // dead right now.
24093       SDValue(N, 1).use_empty()) {
24094     SDLoc DL(N);
24095     EVT VT = N->getValueType(0);
24096     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24097     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24098                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24099                                            DAG.getConstant(X86::COND_B, DL,
24100                                                            MVT::i8),
24101                                            N->getOperand(2)),
24102                                DAG.getConstant(1, DL, VT));
24103     return DCI.CombineTo(N, Res1, CarryOut);
24104   }
24105
24106   return SDValue();
24107 }
24108
24109 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24110 //      (add Y, (setne X, 0)) -> sbb -1, Y
24111 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24112 //      (sub (setne X, 0), Y) -> adc -1, Y
24113 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24114   SDLoc DL(N);
24115
24116   // Look through ZExts.
24117   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24118   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24119     return SDValue();
24120
24121   SDValue SetCC = Ext.getOperand(0);
24122   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24123     return SDValue();
24124
24125   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24126   if (CC != X86::COND_E && CC != X86::COND_NE)
24127     return SDValue();
24128
24129   SDValue Cmp = SetCC.getOperand(1);
24130   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24131       !X86::isZeroNode(Cmp.getOperand(1)) ||
24132       !Cmp.getOperand(0).getValueType().isInteger())
24133     return SDValue();
24134
24135   SDValue CmpOp0 = Cmp.getOperand(0);
24136   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24137                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24138
24139   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24140   if (CC == X86::COND_NE)
24141     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24142                        DL, OtherVal.getValueType(), OtherVal,
24143                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24144                        NewCmp);
24145   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24146                      DL, OtherVal.getValueType(), OtherVal,
24147                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24148 }
24149
24150 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24151 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24152                                  const X86Subtarget *Subtarget) {
24153   EVT VT = N->getValueType(0);
24154   SDValue Op0 = N->getOperand(0);
24155   SDValue Op1 = N->getOperand(1);
24156
24157   // Try to synthesize horizontal adds from adds of shuffles.
24158   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24159        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24160       isHorizontalBinOp(Op0, Op1, true))
24161     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24162
24163   return OptimizeConditionalInDecrement(N, DAG);
24164 }
24165
24166 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24167                                  const X86Subtarget *Subtarget) {
24168   SDValue Op0 = N->getOperand(0);
24169   SDValue Op1 = N->getOperand(1);
24170
24171   // X86 can't encode an immediate LHS of a sub. See if we can push the
24172   // negation into a preceding instruction.
24173   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24174     // If the RHS of the sub is a XOR with one use and a constant, invert the
24175     // immediate. Then add one to the LHS of the sub so we can turn
24176     // X-Y -> X+~Y+1, saving one register.
24177     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24178         isa<ConstantSDNode>(Op1.getOperand(1))) {
24179       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24180       EVT VT = Op0.getValueType();
24181       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24182                                    Op1.getOperand(0),
24183                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24184       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24185                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24186     }
24187   }
24188
24189   // Try to synthesize horizontal adds from adds of shuffles.
24190   EVT VT = N->getValueType(0);
24191   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24192        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24193       isHorizontalBinOp(Op0, Op1, true))
24194     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24195
24196   return OptimizeConditionalInDecrement(N, DAG);
24197 }
24198
24199 /// performVZEXTCombine - Performs build vector combines
24200 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24201                                    TargetLowering::DAGCombinerInfo &DCI,
24202                                    const X86Subtarget *Subtarget) {
24203   SDLoc DL(N);
24204   MVT VT = N->getSimpleValueType(0);
24205   SDValue Op = N->getOperand(0);
24206   MVT OpVT = Op.getSimpleValueType();
24207   MVT OpEltVT = OpVT.getVectorElementType();
24208   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24209
24210   // (vzext (bitcast (vzext (x)) -> (vzext x)
24211   SDValue V = Op;
24212   while (V.getOpcode() == ISD::BITCAST)
24213     V = V.getOperand(0);
24214
24215   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24216     MVT InnerVT = V.getSimpleValueType();
24217     MVT InnerEltVT = InnerVT.getVectorElementType();
24218
24219     // If the element sizes match exactly, we can just do one larger vzext. This
24220     // is always an exact type match as vzext operates on integer types.
24221     if (OpEltVT == InnerEltVT) {
24222       assert(OpVT == InnerVT && "Types must match for vzext!");
24223       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24224     }
24225
24226     // The only other way we can combine them is if only a single element of the
24227     // inner vzext is used in the input to the outer vzext.
24228     if (InnerEltVT.getSizeInBits() < InputBits)
24229       return SDValue();
24230
24231     // In this case, the inner vzext is completely dead because we're going to
24232     // only look at bits inside of the low element. Just do the outer vzext on
24233     // a bitcast of the input to the inner.
24234     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24235                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24236   }
24237
24238   // Check if we can bypass extracting and re-inserting an element of an input
24239   // vector. Essentialy:
24240   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24241   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24242       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24243       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24244     SDValue ExtractedV = V.getOperand(0);
24245     SDValue OrigV = ExtractedV.getOperand(0);
24246     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24247       if (ExtractIdx->getZExtValue() == 0) {
24248         MVT OrigVT = OrigV.getSimpleValueType();
24249         // Extract a subvector if necessary...
24250         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24251           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24252           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24253                                     OrigVT.getVectorNumElements() / Ratio);
24254           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24255                               DAG.getIntPtrConstant(0, DL));
24256         }
24257         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24258         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24259       }
24260   }
24261
24262   return SDValue();
24263 }
24264
24265 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24266                                              DAGCombinerInfo &DCI) const {
24267   SelectionDAG &DAG = DCI.DAG;
24268   switch (N->getOpcode()) {
24269   default: break;
24270   case ISD::EXTRACT_VECTOR_ELT:
24271     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24272   case ISD::VSELECT:
24273   case ISD::SELECT:
24274   case X86ISD::SHRUNKBLEND:
24275     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24276   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24277   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24278   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24279   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24280   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24281   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24282   case ISD::SHL:
24283   case ISD::SRA:
24284   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24285   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24286   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24287   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24288   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24289   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24290   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24291   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24292   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24293   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24294   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24295   case X86ISD::FXOR:
24296   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24297   case X86ISD::FMIN:
24298   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24299   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24300   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24301   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24302   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24303   case ISD::ANY_EXTEND:
24304   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24305   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24306   case ISD::SIGN_EXTEND_INREG:
24307     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24308   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
24309   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24310   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24311   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24312   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24313   case X86ISD::SHUFP:       // Handle all target specific shuffles
24314   case X86ISD::PALIGNR:
24315   case X86ISD::UNPCKH:
24316   case X86ISD::UNPCKL:
24317   case X86ISD::MOVHLPS:
24318   case X86ISD::MOVLHPS:
24319   case X86ISD::PSHUFB:
24320   case X86ISD::PSHUFD:
24321   case X86ISD::PSHUFHW:
24322   case X86ISD::PSHUFLW:
24323   case X86ISD::MOVSS:
24324   case X86ISD::MOVSD:
24325   case X86ISD::VPERMILPI:
24326   case X86ISD::VPERM2X128:
24327   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24328   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24329   case ISD::INTRINSIC_WO_CHAIN:
24330     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24331   case X86ISD::INSERTPS: {
24332     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24333       return PerformINSERTPSCombine(N, DAG, Subtarget);
24334     break;
24335   }
24336   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24337   }
24338
24339   return SDValue();
24340 }
24341
24342 /// isTypeDesirableForOp - Return true if the target has native support for
24343 /// the specified value type and it is 'desirable' to use the type for the
24344 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24345 /// instruction encodings are longer and some i16 instructions are slow.
24346 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24347   if (!isTypeLegal(VT))
24348     return false;
24349   if (VT != MVT::i16)
24350     return true;
24351
24352   switch (Opc) {
24353   default:
24354     return true;
24355   case ISD::LOAD:
24356   case ISD::SIGN_EXTEND:
24357   case ISD::ZERO_EXTEND:
24358   case ISD::ANY_EXTEND:
24359   case ISD::SHL:
24360   case ISD::SRL:
24361   case ISD::SUB:
24362   case ISD::ADD:
24363   case ISD::MUL:
24364   case ISD::AND:
24365   case ISD::OR:
24366   case ISD::XOR:
24367     return false;
24368   }
24369 }
24370
24371 /// IsDesirableToPromoteOp - This method query the target whether it is
24372 /// beneficial for dag combiner to promote the specified node. If true, it
24373 /// should return the desired promotion type by reference.
24374 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24375   EVT VT = Op.getValueType();
24376   if (VT != MVT::i16)
24377     return false;
24378
24379   bool Promote = false;
24380   bool Commute = false;
24381   switch (Op.getOpcode()) {
24382   default: break;
24383   case ISD::LOAD: {
24384     LoadSDNode *LD = cast<LoadSDNode>(Op);
24385     // If the non-extending load has a single use and it's not live out, then it
24386     // might be folded.
24387     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24388                                                      Op.hasOneUse()*/) {
24389       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24390              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24391         // The only case where we'd want to promote LOAD (rather then it being
24392         // promoted as an operand is when it's only use is liveout.
24393         if (UI->getOpcode() != ISD::CopyToReg)
24394           return false;
24395       }
24396     }
24397     Promote = true;
24398     break;
24399   }
24400   case ISD::SIGN_EXTEND:
24401   case ISD::ZERO_EXTEND:
24402   case ISD::ANY_EXTEND:
24403     Promote = true;
24404     break;
24405   case ISD::SHL:
24406   case ISD::SRL: {
24407     SDValue N0 = Op.getOperand(0);
24408     // Look out for (store (shl (load), x)).
24409     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24410       return false;
24411     Promote = true;
24412     break;
24413   }
24414   case ISD::ADD:
24415   case ISD::MUL:
24416   case ISD::AND:
24417   case ISD::OR:
24418   case ISD::XOR:
24419     Commute = true;
24420     // fallthrough
24421   case ISD::SUB: {
24422     SDValue N0 = Op.getOperand(0);
24423     SDValue N1 = Op.getOperand(1);
24424     if (!Commute && MayFoldLoad(N1))
24425       return false;
24426     // Avoid disabling potential load folding opportunities.
24427     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24428       return false;
24429     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24430       return false;
24431     Promote = true;
24432   }
24433   }
24434
24435   PVT = MVT::i32;
24436   return Promote;
24437 }
24438
24439 //===----------------------------------------------------------------------===//
24440 //                           X86 Inline Assembly Support
24441 //===----------------------------------------------------------------------===//
24442
24443 // Helper to match a string separated by whitespace.
24444 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24445   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24446
24447   for (StringRef Piece : Pieces) {
24448     if (!S.startswith(Piece)) // Check if the piece matches.
24449       return false;
24450
24451     S = S.substr(Piece.size());
24452     StringRef::size_type Pos = S.find_first_not_of(" \t");
24453     if (Pos == 0) // We matched a prefix.
24454       return false;
24455
24456     S = S.substr(Pos);
24457   }
24458
24459   return S.empty();
24460 }
24461
24462 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24463
24464   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24465     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24466         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24467         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24468
24469       if (AsmPieces.size() == 3)
24470         return true;
24471       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24472         return true;
24473     }
24474   }
24475   return false;
24476 }
24477
24478 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24479   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24480
24481   std::string AsmStr = IA->getAsmString();
24482
24483   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24484   if (!Ty || Ty->getBitWidth() % 16 != 0)
24485     return false;
24486
24487   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24488   SmallVector<StringRef, 4> AsmPieces;
24489   SplitString(AsmStr, AsmPieces, ";\n");
24490
24491   switch (AsmPieces.size()) {
24492   default: return false;
24493   case 1:
24494     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24495     // we will turn this bswap into something that will be lowered to logical
24496     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24497     // lower so don't worry about this.
24498     // bswap $0
24499     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24500         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24501         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24502         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24503         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24504         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24505       // No need to check constraints, nothing other than the equivalent of
24506       // "=r,0" would be valid here.
24507       return IntrinsicLowering::LowerToByteSwap(CI);
24508     }
24509
24510     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24511     if (CI->getType()->isIntegerTy(16) &&
24512         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24513         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24514          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24515       AsmPieces.clear();
24516       const std::string &ConstraintsStr = IA->getConstraintString();
24517       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24518       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24519       if (clobbersFlagRegisters(AsmPieces))
24520         return IntrinsicLowering::LowerToByteSwap(CI);
24521     }
24522     break;
24523   case 3:
24524     if (CI->getType()->isIntegerTy(32) &&
24525         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24526         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24527         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24528         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24529       AsmPieces.clear();
24530       const std::string &ConstraintsStr = IA->getConstraintString();
24531       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24532       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24533       if (clobbersFlagRegisters(AsmPieces))
24534         return IntrinsicLowering::LowerToByteSwap(CI);
24535     }
24536
24537     if (CI->getType()->isIntegerTy(64)) {
24538       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24539       if (Constraints.size() >= 2 &&
24540           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24541           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24542         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24543         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24544             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24545             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24546           return IntrinsicLowering::LowerToByteSwap(CI);
24547       }
24548     }
24549     break;
24550   }
24551   return false;
24552 }
24553
24554 /// getConstraintType - Given a constraint letter, return the type of
24555 /// constraint it is for this target.
24556 X86TargetLowering::ConstraintType
24557 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24558   if (Constraint.size() == 1) {
24559     switch (Constraint[0]) {
24560     case 'R':
24561     case 'q':
24562     case 'Q':
24563     case 'f':
24564     case 't':
24565     case 'u':
24566     case 'y':
24567     case 'x':
24568     case 'Y':
24569     case 'l':
24570       return C_RegisterClass;
24571     case 'a':
24572     case 'b':
24573     case 'c':
24574     case 'd':
24575     case 'S':
24576     case 'D':
24577     case 'A':
24578       return C_Register;
24579     case 'I':
24580     case 'J':
24581     case 'K':
24582     case 'L':
24583     case 'M':
24584     case 'N':
24585     case 'G':
24586     case 'C':
24587     case 'e':
24588     case 'Z':
24589       return C_Other;
24590     default:
24591       break;
24592     }
24593   }
24594   return TargetLowering::getConstraintType(Constraint);
24595 }
24596
24597 /// Examine constraint type and operand type and determine a weight value.
24598 /// This object must already have been set up with the operand type
24599 /// and the current alternative constraint selected.
24600 TargetLowering::ConstraintWeight
24601   X86TargetLowering::getSingleConstraintMatchWeight(
24602     AsmOperandInfo &info, const char *constraint) const {
24603   ConstraintWeight weight = CW_Invalid;
24604   Value *CallOperandVal = info.CallOperandVal;
24605     // If we don't have a value, we can't do a match,
24606     // but allow it at the lowest weight.
24607   if (!CallOperandVal)
24608     return CW_Default;
24609   Type *type = CallOperandVal->getType();
24610   // Look at the constraint type.
24611   switch (*constraint) {
24612   default:
24613     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24614   case 'R':
24615   case 'q':
24616   case 'Q':
24617   case 'a':
24618   case 'b':
24619   case 'c':
24620   case 'd':
24621   case 'S':
24622   case 'D':
24623   case 'A':
24624     if (CallOperandVal->getType()->isIntegerTy())
24625       weight = CW_SpecificReg;
24626     break;
24627   case 'f':
24628   case 't':
24629   case 'u':
24630     if (type->isFloatingPointTy())
24631       weight = CW_SpecificReg;
24632     break;
24633   case 'y':
24634     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24635       weight = CW_SpecificReg;
24636     break;
24637   case 'x':
24638   case 'Y':
24639     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24640         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24641       weight = CW_Register;
24642     break;
24643   case 'I':
24644     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24645       if (C->getZExtValue() <= 31)
24646         weight = CW_Constant;
24647     }
24648     break;
24649   case 'J':
24650     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24651       if (C->getZExtValue() <= 63)
24652         weight = CW_Constant;
24653     }
24654     break;
24655   case 'K':
24656     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24657       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24658         weight = CW_Constant;
24659     }
24660     break;
24661   case 'L':
24662     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24663       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24664         weight = CW_Constant;
24665     }
24666     break;
24667   case 'M':
24668     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24669       if (C->getZExtValue() <= 3)
24670         weight = CW_Constant;
24671     }
24672     break;
24673   case 'N':
24674     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24675       if (C->getZExtValue() <= 0xff)
24676         weight = CW_Constant;
24677     }
24678     break;
24679   case 'G':
24680   case 'C':
24681     if (isa<ConstantFP>(CallOperandVal)) {
24682       weight = CW_Constant;
24683     }
24684     break;
24685   case 'e':
24686     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24687       if ((C->getSExtValue() >= -0x80000000LL) &&
24688           (C->getSExtValue() <= 0x7fffffffLL))
24689         weight = CW_Constant;
24690     }
24691     break;
24692   case 'Z':
24693     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24694       if (C->getZExtValue() <= 0xffffffff)
24695         weight = CW_Constant;
24696     }
24697     break;
24698   }
24699   return weight;
24700 }
24701
24702 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24703 /// with another that has more specific requirements based on the type of the
24704 /// corresponding operand.
24705 const char *X86TargetLowering::
24706 LowerXConstraint(EVT ConstraintVT) const {
24707   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24708   // 'f' like normal targets.
24709   if (ConstraintVT.isFloatingPoint()) {
24710     if (Subtarget->hasSSE2())
24711       return "Y";
24712     if (Subtarget->hasSSE1())
24713       return "x";
24714   }
24715
24716   return TargetLowering::LowerXConstraint(ConstraintVT);
24717 }
24718
24719 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24720 /// vector.  If it is invalid, don't add anything to Ops.
24721 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24722                                                      std::string &Constraint,
24723                                                      std::vector<SDValue>&Ops,
24724                                                      SelectionDAG &DAG) const {
24725   SDValue Result;
24726
24727   // Only support length 1 constraints for now.
24728   if (Constraint.length() > 1) return;
24729
24730   char ConstraintLetter = Constraint[0];
24731   switch (ConstraintLetter) {
24732   default: break;
24733   case 'I':
24734     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24735       if (C->getZExtValue() <= 31) {
24736         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24737                                        Op.getValueType());
24738         break;
24739       }
24740     }
24741     return;
24742   case 'J':
24743     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24744       if (C->getZExtValue() <= 63) {
24745         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24746                                        Op.getValueType());
24747         break;
24748       }
24749     }
24750     return;
24751   case 'K':
24752     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24753       if (isInt<8>(C->getSExtValue())) {
24754         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24755                                        Op.getValueType());
24756         break;
24757       }
24758     }
24759     return;
24760   case 'L':
24761     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24762       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24763           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24764         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24765                                        Op.getValueType());
24766         break;
24767       }
24768     }
24769     return;
24770   case 'M':
24771     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24772       if (C->getZExtValue() <= 3) {
24773         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24774                                        Op.getValueType());
24775         break;
24776       }
24777     }
24778     return;
24779   case 'N':
24780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24781       if (C->getZExtValue() <= 255) {
24782         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24783                                        Op.getValueType());
24784         break;
24785       }
24786     }
24787     return;
24788   case 'O':
24789     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24790       if (C->getZExtValue() <= 127) {
24791         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24792                                        Op.getValueType());
24793         break;
24794       }
24795     }
24796     return;
24797   case 'e': {
24798     // 32-bit signed value
24799     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24800       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24801                                            C->getSExtValue())) {
24802         // Widen to 64 bits here to get it sign extended.
24803         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24804         break;
24805       }
24806     // FIXME gcc accepts some relocatable values here too, but only in certain
24807     // memory models; it's complicated.
24808     }
24809     return;
24810   }
24811   case 'Z': {
24812     // 32-bit unsigned value
24813     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24814       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24815                                            C->getZExtValue())) {
24816         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24817                                        Op.getValueType());
24818         break;
24819       }
24820     }
24821     // FIXME gcc accepts some relocatable values here too, but only in certain
24822     // memory models; it's complicated.
24823     return;
24824   }
24825   case 'i': {
24826     // Literal immediates are always ok.
24827     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24828       // Widen to 64 bits here to get it sign extended.
24829       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24830       break;
24831     }
24832
24833     // In any sort of PIC mode addresses need to be computed at runtime by
24834     // adding in a register or some sort of table lookup.  These can't
24835     // be used as immediates.
24836     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24837       return;
24838
24839     // If we are in non-pic codegen mode, we allow the address of a global (with
24840     // an optional displacement) to be used with 'i'.
24841     GlobalAddressSDNode *GA = nullptr;
24842     int64_t Offset = 0;
24843
24844     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24845     while (1) {
24846       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24847         Offset += GA->getOffset();
24848         break;
24849       } else if (Op.getOpcode() == ISD::ADD) {
24850         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24851           Offset += C->getZExtValue();
24852           Op = Op.getOperand(0);
24853           continue;
24854         }
24855       } else if (Op.getOpcode() == ISD::SUB) {
24856         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24857           Offset += -C->getZExtValue();
24858           Op = Op.getOperand(0);
24859           continue;
24860         }
24861       }
24862
24863       // Otherwise, this isn't something we can handle, reject it.
24864       return;
24865     }
24866
24867     const GlobalValue *GV = GA->getGlobal();
24868     // If we require an extra load to get this address, as in PIC mode, we
24869     // can't accept it.
24870     if (isGlobalStubReference(
24871             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24872       return;
24873
24874     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24875                                         GA->getValueType(0), Offset);
24876     break;
24877   }
24878   }
24879
24880   if (Result.getNode()) {
24881     Ops.push_back(Result);
24882     return;
24883   }
24884   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24885 }
24886
24887 std::pair<unsigned, const TargetRegisterClass *>
24888 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24889                                                 const std::string &Constraint,
24890                                                 MVT VT) const {
24891   // First, see if this is a constraint that directly corresponds to an LLVM
24892   // register class.
24893   if (Constraint.size() == 1) {
24894     // GCC Constraint Letters
24895     switch (Constraint[0]) {
24896     default: break;
24897       // TODO: Slight differences here in allocation order and leaving
24898       // RIP in the class. Do they matter any more here than they do
24899       // in the normal allocation?
24900     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24901       if (Subtarget->is64Bit()) {
24902         if (VT == MVT::i32 || VT == MVT::f32)
24903           return std::make_pair(0U, &X86::GR32RegClass);
24904         if (VT == MVT::i16)
24905           return std::make_pair(0U, &X86::GR16RegClass);
24906         if (VT == MVT::i8 || VT == MVT::i1)
24907           return std::make_pair(0U, &X86::GR8RegClass);
24908         if (VT == MVT::i64 || VT == MVT::f64)
24909           return std::make_pair(0U, &X86::GR64RegClass);
24910         break;
24911       }
24912       // 32-bit fallthrough
24913     case 'Q':   // Q_REGS
24914       if (VT == MVT::i32 || VT == MVT::f32)
24915         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24916       if (VT == MVT::i16)
24917         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24918       if (VT == MVT::i8 || VT == MVT::i1)
24919         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24920       if (VT == MVT::i64)
24921         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24922       break;
24923     case 'r':   // GENERAL_REGS
24924     case 'l':   // INDEX_REGS
24925       if (VT == MVT::i8 || VT == MVT::i1)
24926         return std::make_pair(0U, &X86::GR8RegClass);
24927       if (VT == MVT::i16)
24928         return std::make_pair(0U, &X86::GR16RegClass);
24929       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24930         return std::make_pair(0U, &X86::GR32RegClass);
24931       return std::make_pair(0U, &X86::GR64RegClass);
24932     case 'R':   // LEGACY_REGS
24933       if (VT == MVT::i8 || VT == MVT::i1)
24934         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24935       if (VT == MVT::i16)
24936         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24937       if (VT == MVT::i32 || !Subtarget->is64Bit())
24938         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24939       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24940     case 'f':  // FP Stack registers.
24941       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24942       // value to the correct fpstack register class.
24943       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24944         return std::make_pair(0U, &X86::RFP32RegClass);
24945       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24946         return std::make_pair(0U, &X86::RFP64RegClass);
24947       return std::make_pair(0U, &X86::RFP80RegClass);
24948     case 'y':   // MMX_REGS if MMX allowed.
24949       if (!Subtarget->hasMMX()) break;
24950       return std::make_pair(0U, &X86::VR64RegClass);
24951     case 'Y':   // SSE_REGS if SSE2 allowed
24952       if (!Subtarget->hasSSE2()) break;
24953       // FALL THROUGH.
24954     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24955       if (!Subtarget->hasSSE1()) break;
24956
24957       switch (VT.SimpleTy) {
24958       default: break;
24959       // Scalar SSE types.
24960       case MVT::f32:
24961       case MVT::i32:
24962         return std::make_pair(0U, &X86::FR32RegClass);
24963       case MVT::f64:
24964       case MVT::i64:
24965         return std::make_pair(0U, &X86::FR64RegClass);
24966       // Vector types.
24967       case MVT::v16i8:
24968       case MVT::v8i16:
24969       case MVT::v4i32:
24970       case MVT::v2i64:
24971       case MVT::v4f32:
24972       case MVT::v2f64:
24973         return std::make_pair(0U, &X86::VR128RegClass);
24974       // AVX types.
24975       case MVT::v32i8:
24976       case MVT::v16i16:
24977       case MVT::v8i32:
24978       case MVT::v4i64:
24979       case MVT::v8f32:
24980       case MVT::v4f64:
24981         return std::make_pair(0U, &X86::VR256RegClass);
24982       case MVT::v8f64:
24983       case MVT::v16f32:
24984       case MVT::v16i32:
24985       case MVT::v8i64:
24986         return std::make_pair(0U, &X86::VR512RegClass);
24987       }
24988       break;
24989     }
24990   }
24991
24992   // Use the default implementation in TargetLowering to convert the register
24993   // constraint into a member of a register class.
24994   std::pair<unsigned, const TargetRegisterClass*> Res;
24995   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24996
24997   // Not found as a standard register?
24998   if (!Res.second) {
24999     // Map st(0) -> st(7) -> ST0
25000     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25001         tolower(Constraint[1]) == 's' &&
25002         tolower(Constraint[2]) == 't' &&
25003         Constraint[3] == '(' &&
25004         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25005         Constraint[5] == ')' &&
25006         Constraint[6] == '}') {
25007
25008       Res.first = X86::FP0+Constraint[4]-'0';
25009       Res.second = &X86::RFP80RegClass;
25010       return Res;
25011     }
25012
25013     // GCC allows "st(0)" to be called just plain "st".
25014     if (StringRef("{st}").equals_lower(Constraint)) {
25015       Res.first = X86::FP0;
25016       Res.second = &X86::RFP80RegClass;
25017       return Res;
25018     }
25019
25020     // flags -> EFLAGS
25021     if (StringRef("{flags}").equals_lower(Constraint)) {
25022       Res.first = X86::EFLAGS;
25023       Res.second = &X86::CCRRegClass;
25024       return Res;
25025     }
25026
25027     // 'A' means EAX + EDX.
25028     if (Constraint == "A") {
25029       Res.first = X86::EAX;
25030       Res.second = &X86::GR32_ADRegClass;
25031       return Res;
25032     }
25033     return Res;
25034   }
25035
25036   // Otherwise, check to see if this is a register class of the wrong value
25037   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25038   // turn into {ax},{dx}.
25039   if (Res.second->hasType(VT))
25040     return Res;   // Correct type already, nothing to do.
25041
25042   // All of the single-register GCC register classes map their values onto
25043   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25044   // really want an 8-bit or 32-bit register, map to the appropriate register
25045   // class and return the appropriate register.
25046   if (Res.second == &X86::GR16RegClass) {
25047     if (VT == MVT::i8 || VT == MVT::i1) {
25048       unsigned DestReg = 0;
25049       switch (Res.first) {
25050       default: break;
25051       case X86::AX: DestReg = X86::AL; break;
25052       case X86::DX: DestReg = X86::DL; break;
25053       case X86::CX: DestReg = X86::CL; break;
25054       case X86::BX: DestReg = X86::BL; break;
25055       }
25056       if (DestReg) {
25057         Res.first = DestReg;
25058         Res.second = &X86::GR8RegClass;
25059       }
25060     } else if (VT == MVT::i32 || VT == MVT::f32) {
25061       unsigned DestReg = 0;
25062       switch (Res.first) {
25063       default: break;
25064       case X86::AX: DestReg = X86::EAX; break;
25065       case X86::DX: DestReg = X86::EDX; break;
25066       case X86::CX: DestReg = X86::ECX; break;
25067       case X86::BX: DestReg = X86::EBX; break;
25068       case X86::SI: DestReg = X86::ESI; break;
25069       case X86::DI: DestReg = X86::EDI; break;
25070       case X86::BP: DestReg = X86::EBP; break;
25071       case X86::SP: DestReg = X86::ESP; break;
25072       }
25073       if (DestReg) {
25074         Res.first = DestReg;
25075         Res.second = &X86::GR32RegClass;
25076       }
25077     } else if (VT == MVT::i64 || VT == MVT::f64) {
25078       unsigned DestReg = 0;
25079       switch (Res.first) {
25080       default: break;
25081       case X86::AX: DestReg = X86::RAX; break;
25082       case X86::DX: DestReg = X86::RDX; break;
25083       case X86::CX: DestReg = X86::RCX; break;
25084       case X86::BX: DestReg = X86::RBX; break;
25085       case X86::SI: DestReg = X86::RSI; break;
25086       case X86::DI: DestReg = X86::RDI; break;
25087       case X86::BP: DestReg = X86::RBP; break;
25088       case X86::SP: DestReg = X86::RSP; break;
25089       }
25090       if (DestReg) {
25091         Res.first = DestReg;
25092         Res.second = &X86::GR64RegClass;
25093       }
25094     }
25095   } else if (Res.second == &X86::FR32RegClass ||
25096              Res.second == &X86::FR64RegClass ||
25097              Res.second == &X86::VR128RegClass ||
25098              Res.second == &X86::VR256RegClass ||
25099              Res.second == &X86::FR32XRegClass ||
25100              Res.second == &X86::FR64XRegClass ||
25101              Res.second == &X86::VR128XRegClass ||
25102              Res.second == &X86::VR256XRegClass ||
25103              Res.second == &X86::VR512RegClass) {
25104     // Handle references to XMM physical registers that got mapped into the
25105     // wrong class.  This can happen with constraints like {xmm0} where the
25106     // target independent register mapper will just pick the first match it can
25107     // find, ignoring the required type.
25108
25109     if (VT == MVT::f32 || VT == MVT::i32)
25110       Res.second = &X86::FR32RegClass;
25111     else if (VT == MVT::f64 || VT == MVT::i64)
25112       Res.second = &X86::FR64RegClass;
25113     else if (X86::VR128RegClass.hasType(VT))
25114       Res.second = &X86::VR128RegClass;
25115     else if (X86::VR256RegClass.hasType(VT))
25116       Res.second = &X86::VR256RegClass;
25117     else if (X86::VR512RegClass.hasType(VT))
25118       Res.second = &X86::VR512RegClass;
25119   }
25120
25121   return Res;
25122 }
25123
25124 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25125                                             Type *Ty) const {
25126   // Scaling factors are not free at all.
25127   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25128   // will take 2 allocations in the out of order engine instead of 1
25129   // for plain addressing mode, i.e. inst (reg1).
25130   // E.g.,
25131   // vaddps (%rsi,%drx), %ymm0, %ymm1
25132   // Requires two allocations (one for the load, one for the computation)
25133   // whereas:
25134   // vaddps (%rsi), %ymm0, %ymm1
25135   // Requires just 1 allocation, i.e., freeing allocations for other operations
25136   // and having less micro operations to execute.
25137   //
25138   // For some X86 architectures, this is even worse because for instance for
25139   // stores, the complex addressing mode forces the instruction to use the
25140   // "load" ports instead of the dedicated "store" port.
25141   // E.g., on Haswell:
25142   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25143   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25144   if (isLegalAddressingMode(AM, Ty))
25145     // Scale represents reg2 * scale, thus account for 1
25146     // as soon as we use a second register.
25147     return AM.Scale != 0;
25148   return -1;
25149 }
25150
25151 bool X86TargetLowering::isTargetFTOL() const {
25152   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25153 }